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

# Webhooks

> Receive real-time WhatsApp events on your own infrastructure with signed, retried, idempotent deliveries.

Webhooks let your code react to events from your WhatsApp numbers in real time. Every delivery is signed, retried, and recorded so you can debug from the dashboard.

> [!NOTE]
>
> The Webhooks dashboard lives at [wassist.app/developers/webhooks](https://wassist.app/developers/webhooks). Create one there, copy the signing secret, and you're done.

## How a delivery works

```mermaid theme={null}
sequenceDiagram
    participant W as Wassist
    participant Q as Delivery queue
    participant You as Your endpoint

    W->>Q: dispatch event (writes WebhookDelivery row)
    Q->>You: POST with X-Wassist-Signature + Delivery ID
    You-->>Q: 2xx
    Note over Q: 4xx → no retry; 5xx/network → retry with backoff
    Q->>W: update delivery + record attempt
```

Behind the scenes:

1. The event is committed to our outbox as a `WebhookDelivery` with a stable UUID.
2. A worker POSTs the JSON body to your URL.
3. We record an attempt row with status code, duration, and response body.
4. On `5xx` or network errors we retry up to **3 times** with exponential backoff
   (10s, 30s, 90s).
5. After **20 consecutive failures** the webhook is auto-disabled and you get a banner in the dashboard.

## Headers

| Header | Purpose |
| - | - |
| `Content-Type` | Always `application/json`. |
| `User-Agent` | `Wassist-Webhook/1.0` |
| `X-Wassist-Event` | The event name, e.g. `message.received`. |
| `X-Wassist-Delivery` | Stable UUID. **Use this as your idempotency key.** It does not change across retries. |
| `X-Wassist-Timestamp` | Unix seconds. The time we signed the request. Every attempt, including retries and replays, is re-signed with a fresh timestamp. |
| `X-Wassist-Signature` | `t=<ts>,v1=<hex hmac sha256>` — Stripe-style. |

## Verifying signatures

Compute `HMAC-SHA256` over the string `<timestamp>.<raw body>` using the webhook's signing secret and compare it in constant time to the `v1` component.

> [tab] Node.js
>
> ```ts theme={null}
> import crypto from "node:crypto";
>
> app.post("/webhooks/wassist", express.raw({ type: "application/json" }), (req, res) => {
>   const header = req.header("x-wassist-signature") ?? "";
>   const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
>   const signedPayload = `${parts.t}.${req.body.toString("utf-8")}`;
>   const expected = crypto
>     .createHmac("sha256", process.env.WASSIST_WEBHOOK_SECRET!)
>     .update(signedPayload)
>     .digest("hex");
>
>   const ok = crypto.timingSafeEqual(
>     Buffer.from(parts.v1, "hex"),
>     Buffer.from(expected, "hex"),
>   );
>   if (!ok) return res.status(400).send("bad signature");
>
>   // Replay protection: reject events more than 5 minutes old.
>   if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) {
>     return res.status(400).send("stale");
>   }
>
>   // Idempotency: drop duplicate deliveries.
>   const deliveryId = req.header("x-wassist-delivery")!;
>   if (await alreadyProcessed(deliveryId)) return res.status(200).send("ok");
>
>   await handle(JSON.parse(req.body.toString("utf-8")));
>   await markProcessed(deliveryId);
>   res.status(200).send("ok");
> });
> ```

> [tab] Python
>
> ```python theme={null}
> import hmac, hashlib, time
>
> def verify(request, secret: str) -> bool:
>     header = request.headers.get("X-Wassist-Signature", "")
>     parts = dict(p.split("=", 1) for p in header.split(","))
>     ts, received = parts.get("t", ""), parts.get("v1", "")
>     signed = f"{ts}.".encode() + request.body
>     expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
>     if not hmac.compare_digest(received, expected):
>         return False
>     return abs(time.time() - int(ts)) <= 300
> ```

> [tab] Go
>
> ```go theme={null}
> func verify(r *http.Request, secret string) bool {
>     body, _ := io.ReadAll(r.Body)
>     header := r.Header.Get("X-Wassist-Signature")
>     var ts, sig string
>     for _, p := range strings.Split(header, ",") {
>         kv := strings.SplitN(p, "=", 2)
>         if len(kv) == 2 {
>             if kv[0] == "t" { ts = kv[1] }
>             if kv[0] == "v1" { sig = kv[1] }
>         }
>     }
>     mac := hmac.New(sha256.New, []byte(secret))
>     mac.Write([]byte(ts + "."))
>     mac.Write(body)
>     expected := hex.EncodeToString(mac.Sum(nil))
>     if !hmac.Equal([]byte(sig), []byte(expected)) {
>         return false
>     }
>     epoch, _ := strconv.ParseInt(ts, 10, 64)
>     return time.Now().Unix()-epoch <= 300
> }
> ```

## Event catalog

### `message.received`

Fired when a customer sends a message to one of your numbers.

```json theme={null}
{
  "event": "message.received",
  "timestamp": "2026-06-23T16:48:00.000000+00:00",
  "conversationId": "5a3f...e2",
  "whatsappNumber": "447700900100",
  "contact": { "id": "c81d...4b", "name": "Alex", "phoneNumber": "447700900200" },
  "message": {
    "id": "01HXYZ...",
    "body": "Hey, can I add another item to my order?",
    "media": [],
    "buttons": [],
    "referral": null,
    "replyTo": null
  },
  "latestReferral": null,
  "routing": "agent"
}
```

Phone numbers are digits only, with no `+`. All IDs are Wassist IDs.

* `message.body` holds the text, the media caption, or, for voice notes, a transcription.
* `message.replyTo` is the Wassist ID of the message the customer quoted, or `null`. To quote the customer's message in your reply, pass `message.id` as `replyTo` when you [send a message](https://docs.wassist.app/api-reference/conversations/messages/send.md#quoted-replies).
* `message.media` is a list of `{ "url", "mimeType", "filename" }`. `filename` is set for documents and `null` otherwise.
* Audio items also carry `transcription` and `voice`. `transcription` matches `body`: the transcript, `"[unintelligible audio]"` when nothing could be heard, or `null` if transcription failed. `voice` is `true` for a recorded voice note and `false` for an uploaded audio file.

Media is sent for images, voice notes and audio (converted to MP3, `audio/mpeg`), video, and documents. Voice note, video and document events are sent once the file has downloaded (and, for voice notes, been transcribed), so they can arrive a few seconds after the message.

```json theme={null}
"media": [
  {
    "url": "https://...",
    "mimeType": "audio/mpeg",
    "filename": null,
    "transcription": "Hi, has my order shipped yet?",
    "voice": true
  }
]
```

The `url` is a pre-signed link that needs no API key and expires **one hour after the message arrived**. Download the file when you receive the event, or fetch a fresh link from [`GET /conversations/{id}/messages/`](https://docs.wassist.app/api-reference/conversations/messages/list).

#### Ad attribution (Click-to-WhatsApp)

When the customer starts the chat by tapping a [Click-to-WhatsApp ad](https://www.facebook.com/business/help/447934475640650) (or a boosted post), `message.referral` carries the ad details WhatsApp attached to that message. `latestReferral` has the same shape and holds the most recent referral in the conversation. That means later messages in an ad-driven chat can still be attributed to the ad.

```json theme={null}
"referral": {
  "messageId": "01HXYZ...",
  "sourceType": "ad",
  "sourceId": "120210000000000000",
  "sourceUrl": "https://fb.me/abc123",
  "headline": "Summer sale — 20% off",
  "body": "Chat with us to find your size",
  "mediaType": "image",
  "imageUrl": "https://scontent.xx.fbcdn.net/...",
  "videoUrl": null,
  "thumbnailUrl": null,
  "ctwaClid": "ARAkLkA8rmlFeiCktEJQ-QTwRiyYHAFDLMNDBH0CD3qpjd0HR4irJ6LEkR7JwFF4XvnO2E4Nx0-eM-GABDLOPaOdRMv-_zfUQ2a",
  "welcomeMessage": "Hi! How can we help?",
  "createdAt": "2026-06-23T16:48:00Z"
}
```

`ctwaClid` is the Click-to-WhatsApp click ID. Send it back to Meta via the [Conversions API for Business Messaging](https://developers.facebook.com/docs/marketing-api/conversions-api/business-messaging) to attribute leads and purchases to the ad. `sourceId` is the Meta ad (or post) ID. You can also look these up later: they're on `referral` for each message returned by `GET /conversations/{id}/messages/`, and on `latestReferral` for each conversation. To filter conversations, use `hasReferral`, `referralSourceId` or `ctwaClid`. See [Ad Attribution](https://docs.wassist.app/guides/ad-attribution.md) for the full field reference and a Conversions API example.

### `message.status.updated`

Fired once each time the delivery status of a message you sent changes. WhatsApp sometimes reports statuses twice or out of order. Those callbacks are dropped, so a status never goes backwards. Deduplicate on `message.id` plus `message.status`.

```json theme={null}
{
  "event": "message.status.updated",
  "timestamp": "2026-06-23T16:48:05.000000+00:00",
  "conversationId": "5a3f...e2",
  "whatsappNumber": "447700900100",
  "contact": { "id": "c81d...4b", "name": "Alex", "phoneNumber": "447700900200" },
  "message": {
    "id": "7f2c...91",
    "status": "failed",
    "statusAt": "2026-06-23T16:48:04+00:00",
    "failure": { "code": 131047, "reason": "Message failed to send because more than 24 hours have passed since the customer last replied to this number." }
  },
  "latestReferral": null,
  "routing": "webhook",
  "webhookId": "9c1c...a0"
}
```

* `status` is one of `sent`, `delivered`, `read` or `failed`.
* `failure` is only present when `status` is `failed`. `code` is Meta's error code.

### `message.reaction.updated`

Fired when the customer adds, changes or removes a reaction. `reaction.messageId` is the Wassist ID of the message they reacted to, and `emoji` is `null` when the reaction was removed. Reactions don't trigger `message.received`, `subscription.message.received`, or the agent.

```json theme={null}
{
  "event": "message.reaction.updated",
  "timestamp": "2026-06-23T16:49:00.000000+00:00",
  "conversationId": "5a3f...e2",
  "whatsappNumber": "447700900100",
  "contact": { "id": "c81d...4b", "name": "Alex", "phoneNumber": "447700900200" },
  "message": null,
  "reaction": { "messageId": "7f2c...91", "emoji": "👍", "reactedAt": "2026-06-23T16:49:00+00:00" },
  "latestReferral": null,
  "routing": "webhook",
  "webhookId": "9c1c...a0"
}
```

Both events go to every active webhook in the organization that has the event ticked, whatever the conversation's routing.

To react from your own code, send a message with `type: "reaction"`:

```json theme={null}
POST /api/v1/conversations/{id}/messages/
{ "type": "reaction", "reaction": { "messageId": "7f2c...91", "emoji": "👍" } }
```

Send `"emoji": null` (or leave it out) to remove the reaction.

### `test.ping`

Triggered by the dashboard **Send test event** button. Same envelope as a real event with a stub payload — use it to validate signature verification in CI.

## Best practices

* **Idempotency.** Store the `X-Wassist-Delivery` ID and reject duplicates. We use the same ID across all retries.
* **Respond fast.** Send a `2xx` within 10 seconds and do real work asynchronously. We treat slow responses as failures and retry.
* **Replay protection.** Reject events where `X-Wassist-Timestamp` is more than 5 minutes from now.
* **Rotate secrets.** From the dashboard, **Rotate secret** generates a new secret. The old one stops working immediately.
* **Local development.** Use the CLI: `wassist listen` tunnels real events to `localhost` without exposing a public URL.

## Replaying deliveries

Every delivery is stored with its full payload. From the dashboard you can:

* Filter deliveries by status (all / failed / succeeded).
* Open a delivery to see request headers, response body, and the timeline of every retry attempt.
* Click **Replay** to send a fresh copy of the same payload. It gets a new `X-Wassist-Delivery` ID and is re-signed with a fresh timestamp, but the JSON body is identical, including its `timestamp` and any media URLs (which may have expired). Deduplicate replays on `message.id`.

You can also replay programmatically via [`POST /api/v1/webhook-deliveries/{id}/replay/`](https://docs.wassist.app/api-reference/webhooks/replay-delivery).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.