# Webhooks

> Event catalogue, payloads, signature verification in Node, Python and PHP, retries, ordering and replay.

Create an endpoint with `POST /v1/webhook-endpoints` (`webhook_endpoints_create`): an `https` URL on a public host and
the events you want (`["message.received"]`, `["message.*"]`, or `["*"]`). The answer contains the signing **secret,
shown once**. Endpoints created with a test key get only test events.

Every event type and its payload schema is in the [API reference](/reference/webhooks) (the OpenAPI document's
`webhooks` section). `data.object` is the same JSON as the resource's GET endpoint.

## Delivery

- `POST` with `Content-Type: application/json`, the event envelope as the body.
- Answer any `2xx` within 10 seconds. Anything else is retried after 10 s, 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and
  3 x 24 h (11 attempts, about 3 days). An endpoint that fails for 3 days is disabled (`webhook_endpoint.disabled`).
- Ordering is not guaranteed: use `sequence` and `created_at`. Deliveries can repeat: de-duplicate on the event `id`
  (also the `webhook-id` header).
- See every attempt in `GET /v1/webhook-deliveries`; replay with `POST /v1/webhook-deliveries/{id}/replay`.

## Headers

| Header | Meaning |
|---|---|
| `Wapitick-Signature` | `t=<unix>,v1=<hex HMAC-SHA256(secret, "<t>.<body>")>`; during a secret rotation one `v1` per active secret |
| `webhook-id`, `webhook-timestamp`, `webhook-signature` | [Standard Webhooks](https://www.standardwebhooks.com): `v1,<base64 HMAC-SHA256(secret, "<id>.<timestamp>.<body>")>` |
| `Wapitick-Event-Id`, `Wapitick-Event-Type`, `Wapitick-Delivery-Id`, `Wapitick-Attempt` | for logs |

The HMAC key is your secret exactly as shown (`whsec_...`, its UTF-8 bytes). A Standard Webhooks library
base64-decodes the secret you give it, so pass it `base64(secret)`.

## Verify (always use the raw body)

**cURL**

```bash title="curl.sh"
#!/usr/bin/env bash
# Receive messages by webhook: webhook_endpoints_create, test_inbound_create (runs in test mode)
set -euo pipefail
API="${WAPITICK_API_URL:-https://api.wapitick.com}"
AUTH="Authorization: Bearer $WAPITICK_API_KEY"

# Register your HTTPS endpoint for incoming messages. The secret is shown ONCE: store it.
curl -sf "$API/v1/webhook-endpoints" -H "$AUTH" -H "Content-Type: application/json" -H "Idempotency-Key: wh-$(date +%s)" \
  -d "{\"url\":\"${WEBHOOK_URL:-https://example.com/wapitick/webhooks}\",\"events\":[\"message.received\",\"message.status_updated\"]}" \
  | jq '{id: .endpoint.id, livemode: .endpoint.livemode, secret_starts: (.secret[0:6])}'
# Fire one (test mode)
curl -sf "$API/v1/test/inbound" -H "$AUTH" -H "Content-Type: application/json" -H "Idempotency-Key: wh-in-$(date +%s)" \
  -d '{"from":"+15550100001","text":"Hello webhook"}' | jq '{status}'
# No public URL yet? `npx wapitick listen --forward-to http://localhost:3000/webhooks` streams the same events.
```

**Node**

```js title="node.mjs"
// biome-ignore-all lint/suspicious/noConsole: a docs sample prints its result
// Receive messages by webhook: a tiny server that verifies every delivery (verifyWebhook) and answers 200 fast.
import { createServer } from "node:http";
import { verifyWebhook } from "@wapitick/node";

const secret = process.env.WAPITICK_WEBHOOK_SECRET ?? "whsec_test";
const server = createServer((req, res) => {
  const chunks = [];
  req.on("data", (c) => chunks.push(c));
  req.on("end", () => {
    try {
      const event = verifyWebhook(Buffer.concat(chunks), req.headers, secret); // the RAW body
      if (event.type === "message.received") console.log("from", event.data.object.contact_id);
      res.writeHead(200).end(); // answer within 10 s; do slow work after
    } catch {
      res.writeHead(400).end();
    }
  });
});
if (process.env.CI_SAMPLE !== "1") server.listen(Number(process.env.PORT ?? 3000));
else console.log(JSON.stringify({ ok: true }));
```

**Python**

```python title="python.py"
# Receive messages by webhook (Flask): verify every delivery, answer 200 fast.
import json
import os

from wapitick import verify_webhook

SECRET = os.environ.get("WAPITICK_WEBHOOK_SECRET", "whsec_test")


def handle(raw_body: bytes, headers: dict) -> int:
    event = verify_webhook(raw_body, headers, SECRET)  # the RAW body
    if event["type"] == "message.received":
        print("from", event["data"]["object"].get("contact_id"))
    return 200


if os.environ.get("CI_SAMPLE") == "1":
    print(json.dumps({"ok": True}))
else:
    from flask import Flask, request  # pip install flask

    app = Flask(__name__)

    @app.post("/webhooks")
    def webhooks():
        try:
            return "", handle(request.get_data(), dict(request.headers))
        except Exception:
            return "", 400

    app.run(port=int(os.environ.get("PORT", 3000)))
```

**PHP**

```php title="php.php"
<?php
// Receive messages by webhook (plain PHP or a Laravel route): verify every delivery, answer 200 fast.
require __DIR__ . '/vendor/autoload.php';

try {
    $event = Wapitick\Webhook::verify(file_get_contents('php://input'), getallheaders(), getenv('WAPITICK_WEBHOOK_SECRET'));
    if ($event['type'] === 'message.received') {
        error_log('from ' . ($event['data']['object']['contact_id'] ?? '?'));
    }
    http_response_code(200);
} catch (Wapitick\WapitickException $e) {
    http_response_code(400);
}
```

Without an SDK, in any language: split `Wapitick-Signature` on commas, take `t`, compute
`hex(hmac_sha256(secret, t + "." + raw_body))`, compare with each `v1` in constant time, and refuse a `t` more than
5 minutes away from now.
