# Webhooks

Receive events and verify the signature.

A webhook is an address on your server that we call on every event: a message status, a customer reply, a template change.

## Register an address

`POST /webhook-endpoints` with:

- `url`: an HTTPS address;
- `scope`: `account` (the whole account), `company` or `connection`;
- `events`: optional, to receive only some types.

The `whsec_...` secret is returned only once.

To change the URL or the `events` filter without recreating the secret: `PATCH /webhook-endpoints/{id}`.

## What you receive

```json
{
  "account_id": "acc_...", "company_id": "cmp_...", "connection_id": "con_...",
  "waba_id": "...", "phone_number_id": "...",
  "event_type": "messages",
  "payload": { "object": "whatsapp_business_account", "entry": [ ... ] }
}
```

The `payload` is the event exactly as Meta sends it. The `X-Wa-Signature` and `X-Wa-Delivery` headers come with every delivery.

## Verify the signature

The header looks like `X-Wa-Signature: t=<timestamp>,v1=<signature>`, with `v1 = HMAC-SHA256("{t}.{raw body}", whsec_...)`. Verify on the **raw** body, before any JSON decoding, and reject any request whose timestamp is more than 300 seconds off.

```php title="PHP"
$header = $_SERVER['HTTP_X_WA_SIGNATURE'] ?? '';
parse_str(str_replace(',', '&', $header), $parts);
$raw = file_get_contents('php://input');
$expected = hash_hmac('sha256', $parts['t'].'.'.$raw, $secret);
$valid = hash_equals($expected, $parts['v1'] ?? '') && abs(time() - (int) $parts['t']) <= 300;
```
```js title="Node.js"
import crypto from 'node:crypto';

export function isValid(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const expected = crypto.createHmac('sha256', secret).update(parts.t + '.' + rawBody).digest('hex');
  const fresh = Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300;
  const a = Buffer.from(expected);
  const b = Buffer.from(parts.v1 || '');
  return fresh && a.length === b.length && crypto.timingSafeEqual(a, b);
}
```
```python title="Python"
import hmac, hashlib, time

def is_valid(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    expected = hmac.new(secret.encode(), parts["t"].encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", "")) and abs(time.time() - int(parts["t"])) <= 300
```

## Answer fast

Answer `2xx` quickly, then process the event on your side. Without a 2xx answer, the delivery is attempted **5 times in total**: the first one, then four retries after 10 seconds, 1 minute, 5 minutes and 15 minutes.

Handle events idempotently: `X-Wa-Delivery` identifies each delivery, and the same event can arrive twice.

> **Tip**

> Put the event in a queue (database, message queue) and answer right away. It is the safest way to lose nothing and not overload your server.
