# Webhooks

Relay posts every event for your numbers to the `https://` URL you set in **Settings**. Meta's events arrive in Meta's own JSON shape, unchanged; Relay's own events (`relay.*`) use a small envelope described below.

## Respond fast

Answer `2xx` within 8 seconds, then do the work. Anything else (timeout, network error, 3xx, 4xx, 5xx) counts as failed.

## Retries

A failed delivery is retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 24 hours, then given up. **Settings → Recent events** shows the result of each event and the next retry. Retried deliveries carry the same `webhook-id`.

Deliveries are not ordered and can repeat (Meta itself retries for up to 7 days). Deduplicate on `webhook-id`, or on the message or status id inside the payload.

## Verify the signature

Every delivery carries two signatures over the raw request body. Check either one, and always on the raw bytes, before parsing JSON.

**X-Relay-Signature-256**: `sha256=` + hex HMAC-SHA256 of the body with your webhook secret.

```python
import hashlib, hmac
def valid(secret: str, body: bytes, header: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header or "")
```

```javascript
import crypto from "node:crypto";
function valid(secret, rawBody, header) {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  return header && expected.length === header.length &&
         crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(header));
}
```

**Standard Webhooks** headers `webhook-id`, `webhook-timestamp` and `webhook-signature` follow the [Standard Webhooks](https://www.standardwebhooks.com/) spec, so its libraries in nine languages verify them and reject replays older than five minutes. Use the `whsec_…` secret shown in Settings:

```python
from standardwebhooks.webhooks import Webhook
payload = Webhook("whsec_…").verify(raw_body, request.headers)  # raises on bad or stale signature
```

The signed content is `{webhook-id}.{webhook-timestamp}.{body}`, HMAC-SHA256 with the secret's decoded bytes, base64, prefixed `v1,`.

Common mistake: frameworks that parse JSON first and hand you a re-serialised body. Read the raw bytes (Express: `express.raw({type: "application/json"})`; FastAPI: `await request.body()`).

## Headers

| Header | Value |
|---|---|
| `X-Relay-Signature-256` | `sha256=<hex>` |
| `webhook-id` | `evt_<n>`, stable across retries |
| `webhook-timestamp` | Unix seconds |
| `webhook-signature` | `v1,<base64>` |
| `X-Relay-Mode` | `live` or `test` |

## Event types

From Meta (`"object": "whatsapp_business_account"`), by `entry[].changes[].field`:

- `messages`: incoming messages (`value.messages`) and delivery statuses (`value.statuses`: sent, delivered, read, failed).
- `message_template_status_update`: a template was approved, rejected, paused or disabled.
- `smb_message_echoes`, `smb_app_state_sync`, `history`: coexistence events from the WhatsApp Business app.

From Relay (`"object": "relay"`):

```json
{"object": "relay", "type": "relay.number.connected", "created_at": "2026-10-08T09:12:00+00:00",
 "data": {"number_id": 3, "display_phone": "+41 79 841 72 47", "external_ref": "customer-4711", ...}}
```

- `relay.ping`: test event from **Send test event** or `POST /api/v1/webhook/ping`.
- `relay.number.connected`: a number joined your account (dashboard or onboarding link).
- `relay.number.disconnected`: a number was removed.
- `relay.number.app_inactive`: no sign of the WhatsApp Business app for 12 days; Meta disconnects after about 14. Ask the shop to open the app.

## Test your endpoint

```bash
curl -X POST https://relay.vesperai.ch/api/v1/webhook/ping -H "Authorization: Bearer $RELAY_KEY"
{"result": "200", "ok": true}
```
