> ## 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

> Receive real-time notifications for messages, delivery events, and instance status changes.

# Webhooks

Webhooks let you receive real-time HTTP callbacks when events occur on your WhatsApp instances. Instead of polling the API, Wappfy pushes events to your server as they happen.

## Supported Events

Wappfy supports 12 webhook event types:

<AccordionGroup>
  <Accordion title="Message Events">
    | Event               | Description                                                                 |
    | ------------------- | --------------------------------------------------------------------------- |
    | `message.received`  | A new inbound message was received.                                         |
    | `message.sent`      | An outbound message was successfully sent.                                  |
    | `message.delivered` | A sent message was delivered to the recipient's device (double check mark). |
    | `message.read`      | A sent message was read by the recipient (blue check marks).                |
    | `message.failed`    | An outbound message failed to send.                                         |
    | `message.reaction`  | Someone reacted to a message with an emoji.                                 |
  </Accordion>

  <Accordion title="Instance Events">
    | Event                   | Description                                     |
    | ----------------------- | ----------------------------------------------- |
    | `instance.connected`    | An instance successfully connected to WhatsApp. |
    | `instance.disconnected` | An instance lost its WhatsApp connection.       |
    | `instance.qr`           | A new QR code is available for scanning.        |
  </Accordion>

  <Accordion title="Group & Contact Events">
    | Event             | Description                                              |
    | ----------------- | -------------------------------------------------------- |
    | `group.joined`    | A participant joined a group (including the bot itself). |
    | `group.left`      | A participant left a group.                              |
    | `contact.created` | A new contact was saved or detected.                     |
  </Accordion>
</AccordionGroup>

***

## Create a Webhook

Register a webhook endpoint to start receiving events.

<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      | Description                                                                            |
| ------------- | --------- | ------------ | -------------------------------------------------------------------------------------- |
| `url`         | string    | **required** | The HTTPS URL that will receive webhook POST requests.                                 |
| `events`      | string\[] | **required** | Array of event types to subscribe to.                                                  |
| `instance_id` | string    | `null`       | Scope the webhook to a specific instance. If null, receives events from all instances. |
| `secret`      | string    | `null`       | Secret used to generate HMAC signatures for payload verification.                      |
| `retry_count` | number    | `3`          | Number of retry attempts on delivery failure (0-5).                                    |
| `timeout_ms`  | number    | `10000`      | Request timeout in milliseconds (1000-30000).                                          |

<Note>
  The `instance_id` field is optional. If omitted, the webhook will receive events from **all** instances in your account.
</Note>

***

## List 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
    }
  ]
}
```

***

## Update a Webhook

Update the URL, events, or configuration of an existing webhook.

```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
  }'
```

***

## Delete a Webhook

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

***

## Delivery Payload Format

When an event occurs, Wappfy sends a POST request to your webhook URL with the following structure:

```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         | Description                                          |
| ------------- | ---------------------------------------------------- |
| `id`          | Unique delivery ID. Use this for deduplication.      |
| `event`       | The event type that triggered this delivery.         |
| `instance_id` | The instance that generated the event.               |
| `timestamp`   | ISO 8601 timestamp of when the event occurred.       |
| `data`        | Event-specific payload. Contents vary by event type. |

***

## HMAC Signature Verification

If you provide a `secret` when creating a webhook, every delivery will include an `X-Wappfy-Signature` header containing an HMAC-SHA256 signature of the request body.

**Always verify this signature** to ensure the request came from Wappfy and was not tampered with.

### Verification Examples

<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>
  Always use constant-time comparison (like `timingSafeEqual` or `hmac.compare_digest`) when verifying signatures to prevent timing attacks.
</Warning>

***

## Retry Behavior

If your server does not respond with a `2xx` status code within the configured `timeout_ms`, Wappfy will retry the delivery.

| Attempt   | Delay      |
| --------- | ---------- |
| 1st retry | 10 seconds |
| 2nd retry | 60 seconds |
| 3rd retry | 5 minutes  |
| 4th retry | 30 minutes |
| 5th retry | 2 hours    |

<Note>
  Retries stop when a `2xx` response is received or the `retry_count` is exhausted. The default retry count is 3.
</Note>

### Viewing Delivery History

Check the delivery log for a webhook to see past delivery attempts and their results.

```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 Examples

<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>

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Respond quickly" icon="bolt">
    Return a `200` status within 5 seconds. Process the event asynchronously to avoid timeouts.
  </Card>

  <Card title="Deduplicate" icon="clone">
    Use the delivery `id` to detect and skip duplicate deliveries caused by retries.
  </Card>

  <Card title="Verify signatures" icon="shield-halved">
    Always validate the `X-Wappfy-Signature` header if you configured a secret.
  </Card>

  <Card title="Use HTTPS" icon="lock">
    Webhook URLs must use HTTPS. HTTP endpoints will be rejected.
  </Card>
</CardGroup>
