> ## Documentation Index
> Fetch the complete documentation index at: https://docs.wappfy.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Messages, delivery events, और instance status changes के लिए real-time notifications प्राप्त करें।

# Webhooks

Webhooks आपको अपने WhatsApp instances पर events होने पर real-time HTTP callbacks प्राप्त करने की सुविधा देते हैं। API को poll करने के बजाय, Wappfy events को आपके server पर push करता है जैसे ही वे होते हैं।

## Supported Events

Wappfy 12 webhook event types को support करता है:

<AccordionGroup>
  <Accordion title="Message Events">
    | Event               | विवरण                                                                       |
    | ------------------- | --------------------------------------------------------------------------- |
    | `message.received`  | एक नया inbound message प्राप्त हुआ।                                         |
    | `message.sent`      | एक outbound message सफलतापूर्वक भेजा गया।                                   |
    | `message.delivered` | भेजा गया message प्राप्तकर्ता के device पर deliver हुआ (double check mark)। |
    | `message.read`      | भेजा गया message प्राप्तकर्ता द्वारा पढ़ा गया (blue check marks)।           |
    | `message.failed`    | एक outbound message भेजने में विफल रहा।                                     |
    | `message.reaction`  | किसी ने message पर emoji से react किया।                                     |
  </Accordion>

  <Accordion title="Instance Events">
    | Event                   | विवरण                                               |
    | ----------------------- | --------------------------------------------------- |
    | `instance.connected`    | एक instance सफलतापूर्वक WhatsApp से connect हो गया। |
    | `instance.disconnected` | एक instance ने अपना WhatsApp connection खो दिया।    |
    | `instance.qr`           | Scanning के लिए एक नया QR code उपलब्ध है।           |
  </Accordion>

  <Accordion title="Group और Contact Events">
    | Event             | विवरण                                                |
    | ----------------- | ---------------------------------------------------- |
    | `group.joined`    | एक participant group में शामिल हुआ (bot स्वयं सहित)। |
    | `group.left`      | एक participant ने group छोड़ा।                       |
    | `contact.created` | एक नया contact save या detect किया गया।              |
  </Accordion>
</AccordionGroup>

***

## एक Webhook बनाएं

Events प्राप्त करना शुरू करने के लिए webhook endpoint register करें।

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST https://api.wappfy.io/api/webhooks \
    -H "X-Api-Key: YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "url": "https://your-server.com/webhooks/wappfy",
      "events": ["message.received", "message.sent", "message.delivered"],
      "instance_id": "inst_abc123",
      "secret": "whsec_my_signing_secret",
      "retry_count": 3,
      "timeout_ms": 10000
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch("https://api.wappfy.io/api/webhooks", {
    method: "POST",
    headers: {
      "X-Api-Key": "YOUR_API_KEY",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      url: "https://your-server.com/webhooks/wappfy",
      events: ["message.received", "message.sent", "message.delivered"],
      instance_id: "inst_abc123",
      secret: "whsec_my_signing_secret",
      retry_count: 3,
      timeout_ms: 10000,
    }),
  });

  const webhook = await response.json();
  console.log(webhook.data.id);
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "data": {
    "id": "wh_xyz789",
    "url": "https://your-server.com/webhooks/wappfy",
    "events": ["message.received", "message.sent", "message.delivered"],
    "instance_id": "inst_abc123",
    "is_active": true,
    "retry_count": 3,
    "timeout_ms": 10000,
    "created_at": "2026-02-10T12:00:00Z"
  }
}
```

### Configuration Options

| Field         | Type      | Default    | विवरण                                                                                                   |
| ------------- | --------- | ---------- | ------------------------------------------------------------------------------------------------------- |
| `url`         | string    | **आवश्यक** | वह HTTPS URL जो webhook POST requests प्राप्त करेगा।                                                    |
| `events`      | string\[] | **आवश्यक** | Subscribe करने के लिए event types की array।                                                             |
| `instance_id` | string    | `null`     | Webhook को किसी specific instance तक सीमित करें। यदि null है, तो सभी instances से events प्राप्त होंगे। |
| `secret`      | string    | `null`     | Payload verification के लिए HMAC signatures generate करने में उपयोग किया जाने वाला secret।              |
| `retry_count` | number    | `3`        | Delivery failure पर retry attempts की संख्या (0-5)।                                                     |
| `timeout_ms`  | number    | `10000`    | Milliseconds में request timeout (1000-30000)।                                                          |

<Note>
  `instance_id` field वैकल्पिक है। यदि छोड़ दिया जाए, तो webhook आपके account की **सभी** instances से events प्राप्त करेगा।
</Note>

***

## Webhooks की सूची

```bash theme={null}
curl https://api.wappfy.io/api/webhooks \
  -H "X-Api-Key: YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "data": [
    {
      "id": "wh_xyz789",
      "url": "https://your-server.com/webhooks/wappfy",
      "events": ["message.received", "message.sent", "message.delivered"],
      "instance_id": "inst_abc123",
      "is_active": true,
      "retry_count": 3,
      "timeout_ms": 10000
    }
  ]
}
```

***

## एक Webhook Update करें

किसी मौजूदा webhook का URL, events, या configuration update करें।

```bash theme={null}
curl -X PATCH https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": ["message.received", "message.sent", "message.delivered", "message.read"],
    "is_active": true
  }'
```

***

## एक Webhook Delete करें

```bash theme={null}
curl -X DELETE https://api.wappfy.io/api/webhooks/wh_xyz789 \
  -H "X-Api-Key: YOUR_API_KEY"
```

***

## Delivery Payload Format

जब कोई event होता है, Wappfy आपके webhook URL पर निम्न structure के साथ एक POST request भेजता है:

```json theme={null}
{
  "id": "dlv_abc123def456",
  "event": "message.received",
  "instance_id": "inst_abc123",
  "timestamp": "2026-02-10T14:30:00Z",
  "data": {
    "message_id": "BAE5F2C4D3B2A1",
    "chat_id": "5511999998888@s.whatsapp.net",
    "from": "5511999998888@s.whatsapp.net",
    "type": "text",
    "text": "Hello!",
    "timestamp": "2026-02-10T14:30:00Z"
  }
}
```

### Payload Fields

| Field         | विवरण                                                               |
| ------------- | ------------------------------------------------------------------- |
| `id`          | Unique delivery ID। Deduplication के लिए इसका उपयोग करें।           |
| `event`       | वह event type जिसने इस delivery को trigger किया।                    |
| `instance_id` | वह instance जिसने event generate किया।                              |
| `timestamp`   | ISO 8601 timestamp जब event हुआ।                                    |
| `data`        | Event-specific payload। सामग्री event type के अनुसार भिन्न होती है। |

***

## HMAC Signature Verification

यदि आपने webhook बनाते समय `secret` प्रदान किया है, तो प्रत्येक delivery में `X-Wappfy-Signature` header शामिल होगा जिसमें request body का HMAC-SHA256 signature होगा।

यह सुनिश्चित करने के लिए **हमेशा इस signature को verify करें** कि request Wappfy से आई है और उसमें छेड़छाड़ नहीं की गई है।

### Verification उदाहरण

<CodeGroup>
  ```javascript Node.js (Express) theme={null}
  const crypto = require("crypto");

  function verifyWebhookSignature(req, secret) {
    const signature = req.headers["x-wappfy-signature"];
    if (!signature) return false;

    const expectedSignature = crypto
      .createHmac("sha256", secret)
      .update(JSON.stringify(req.body))
      .digest("hex");

    return crypto.timingSafeEqual(
      Buffer.from(signature),
      Buffer.from(expectedSignature)
    );
  }

  // Express middleware
  app.post("/webhooks/wappfy", (req, res) => {
    const isValid = verifyWebhookSignature(req, "whsec_my_signing_secret");

    if (!isValid) {
      return res.status(401).json({ error: "Invalid signature" });
    }

    const { event, data } = req.body;
    console.log(`Received event: ${event}`, data);

    // Always respond with 200 quickly to prevent retries
    res.status(200).json({ received: true });
  });
  ```

  ```python Python (Flask) theme={null}
  import hmac
  import hashlib
  import json
  from flask import Flask, request, jsonify

  app = Flask(__name__)
  WEBHOOK_SECRET = "whsec_my_signing_secret"

  def verify_signature(payload, signature):
      expected = hmac.new(
          WEBHOOK_SECRET.encode(),
          json.dumps(payload).encode(),
          hashlib.sha256
      ).hexdigest()
      return hmac.compare_digest(expected, signature)

  @app.route("/webhooks/wappfy", methods=["POST"])
  def handle_webhook():
      signature = request.headers.get("X-Wappfy-Signature", "")
      if not verify_signature(request.json, signature):
          return jsonify({"error": "Invalid signature"}), 401

      event = request.json["event"]
      data = request.json["data"]
      print(f"Received event: {event}", data)

      return jsonify({"received": True}), 200
  ```
</CodeGroup>

<Warning>
  Timing attacks से बचने के लिए signatures verify करते समय हमेशा constant-time comparison (जैसे `timingSafeEqual` या `hmac.compare_digest`) का उपयोग करें।
</Warning>

***

## Retry Behavior

यदि आपका server configured `timeout_ms` के भीतर `2xx` status code से respond नहीं करता, तो Wappfy delivery को retry करेगा।

| Attempt       | Delay      |
| ------------- | ---------- |
| पहला retry    | 10 seconds |
| दूसरा retry   | 60 seconds |
| तीसरा retry   | 5 minutes  |
| चौथा retry    | 30 minutes |
| पांचवां retry | 2 hours    |

<Note>
  `2xx` response प्राप्त होने या `retry_count` समाप्त होने पर retries रुक जाते हैं। Default retry count 3 है।
</Note>

### Delivery History देखना

पिछले delivery attempts और उनके results देखने के लिए webhook का delivery log जांचें।

```bash theme={null}
curl https://api.wappfy.io/api/webhooks/wh_xyz789/deliveries \
  -H "X-Api-Key: YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "data": [
    {
      "id": "dlv_abc123def456",
      "event": "message.received",
      "status": "delivered",
      "http_status": 200,
      "attempts": 1,
      "created_at": "2026-02-10T14:30:00Z",
      "delivered_at": "2026-02-10T14:30:01Z"
    },
    {
      "id": "dlv_ghi789jkl012",
      "event": "message.sent",
      "status": "failed",
      "http_status": 500,
      "attempts": 3,
      "created_at": "2026-02-10T14:31:00Z",
      "last_error": "Server returned 500 Internal Server Error"
    }
  ]
}
```

***

## Event Payload उदाहरण

<AccordionGroup>
  <Accordion title="message.received">
    ```json theme={null}
    {
      "id": "dlv_abc123",
      "event": "message.received",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:30:00Z",
      "data": {
        "message_id": "BAE5F2C4D3B2A1",
        "chat_id": "5511999998888@s.whatsapp.net",
        "from": "5511999998888@s.whatsapp.net",
        "type": "text",
        "text": "Hello, I need help with my order",
        "timestamp": "2026-02-10T14:30:00Z"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.delivered">
    ```json theme={null}
    {
      "id": "dlv_def456",
      "event": "message.delivered",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:30:05Z",
      "data": {
        "message_id": "BAE5A1B2C3D4E5",
        "chat_id": "5511999998888@s.whatsapp.net",
        "status": "delivered"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.read">
    ```json theme={null}
    {
      "id": "dlv_ghi789",
      "event": "message.read",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:31:00Z",
      "data": {
        "message_id": "BAE5A1B2C3D4E5",
        "chat_id": "5511999998888@s.whatsapp.net",
        "status": "read"
      }
    }
    ```
  </Accordion>

  <Accordion title="message.reaction">
    ```json theme={null}
    {
      "id": "dlv_jkl012",
      "event": "message.reaction",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T14:32:00Z",
      "data": {
        "message_id": "BAE5F2C4D3B2A1",
        "chat_id": "5511999998888@s.whatsapp.net",
        "from": "5511999998888@s.whatsapp.net",
        "reaction": "\u2764\ufe0f"
      }
    }
    ```
  </Accordion>

  <Accordion title="instance.connected">
    ```json theme={null}
    {
      "id": "dlv_mno345",
      "event": "instance.connected",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T12:00:00Z",
      "data": {
        "instance_id": "inst_abc123",
        "status": "connected",
        "phone_number": "5511999998888"
      }
    }
    ```
  </Accordion>

  <Accordion title="instance.qr">
    ```json theme={null}
    {
      "id": "dlv_pqr678",
      "event": "instance.qr",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T11:59:00Z",
      "data": {
        "instance_id": "inst_abc123",
        "qr": "data:image/png;base64,iVBORw0KGgo..."
      }
    }
    ```
  </Accordion>

  <Accordion title="group.joined">
    ```json theme={null}
    {
      "id": "dlv_stu901",
      "event": "group.joined",
      "instance_id": "inst_abc123",
      "timestamp": "2026-02-10T15:00:00Z",
      "data": {
        "group_id": "120363012345678901@g.us",
        "participant": "5511888887777@s.whatsapp.net"
      }
    }
    ```
  </Accordion>
</AccordionGroup>

***

## सर्वोत्तम प्रथाएं

<CardGroup cols={2}>
  <Card title="तेजी से respond करें" icon="bolt">
    5 seconds के भीतर `200` status लौटाएं। Timeouts से बचने के लिए event को asynchronously process करें।
  </Card>

  <Card title="Deduplicate करें" icon="clone">
    Retries के कारण duplicate deliveries को detect और skip करने के लिए delivery `id` का उपयोग करें।
  </Card>

  <Card title="Signatures verify करें" icon="shield-halved">
    यदि आपने secret configure किया है तो हमेशा `X-Wappfy-Signature` header को validate करें।
  </Card>

  <Card title="HTTPS उपयोग करें" icon="lock">
    Webhook URLs को HTTPS उपयोग करना अनिवार्य है। HTTP endpoints reject कर दिए जाएंगे।
  </Card>
</CardGroup>
