# Webhooks

## What this is

Otobiz can `POST` a signed JSON event to a URL you register, when something happens on your brand,
a WhatsApp template gets approved, a message fails to deliver, a customer checks out a cart. Register
endpoints and read their delivery log at **Developers → Webhooks** in the dashboard, or through the
public API with a key of the owner or admin role.

## Registering an endpoint

`POST /api/v1/webhooks/settings` (dashboard: the **Add webhook** button).

| Field | Required | Notes |
|---|---|---|
| `name` | yes | Your own label. |
| `url` | yes | Must be public `http`/`https`. Loopback, private, link-local and cloud-metadata hosts are refused, at registration and again on every delivery attempt, since DNS can move between attempt 1 and attempt 7. |
| `events` | yes | One or more names from the catalog below, or `["*"]` for every event **your key may read**, including ones added later; a list of names gains no event added later. The wildcard is a filter, not a demand: it never fails on a scope you lack, it simply does not send you those events. A name you list explicitly IS a demand, and is refused with `403 insufficient_scope` if your key cannot read it. Dashboard-created endpoints are the brand owner's and are never narrowed. |
| `secret` | no | Your own signing secret. Omit it and one (`whsec_…`) is made and returned once as `secret` in the create answer: every endpoint is signed by default. `secret: null` on update removes it. |
| `customHeaders` | no | Sent verbatim on every delivery. A name that collides with one of ours, in any case, is dropped. A value under a name that names a secret (Authorization, a token, a key) reads back as `••••••`; send it back unchanged to keep it. |
| `disabledResourceGroups` | no | Group ids you never want delivered here, whatever `events` says; see below. |
| `disabledLocationIds` | no | Location ids you never want delivered here; see below. |
| `disabledConnections` | no | Connection (connected account) ids you never want delivered here; see below. |
| `paused` | no | Register it already paused, so nothing is delivered until you resume it. Default `false`. |

**Registering ahead of your receiver.** An endpoint is live from the moment it exists, so if you
register one before the service behind it is answering, every matching event becomes a seven-attempt
retry tail against a URL that cannot reply. Send `paused: true` at create and `PATCH {"paused": false}`
when your handler is up; the events that match while it is paused are kept and sent then, oldest first.

## Turning off a group you never want

`disabledResourceGroups` is an opt-out **denylist** of event-group ids, the `id` on each group in the catalog
below. An event whose group you have listed is never delivered to this endpoint, and that holds:

- even when the event is named in your `events`, and even when `events` is `["*"]`. The wildcard
  subscribes you to everything present and future; the denylist is what carves a hole in it that a
  later catalog addition cannot quietly fill.
- on every replay path, a retry already in flight, **Re-run**, and **Send test**. Re-run and Send
  test on a denied group are refused with a `409` that names the reason.

```json
{ "name": "Orders sheet", "url": "https://…", "events": ["*"], "disabledResourceGroups": ["messages", "publishing"] }
```

On update the array **replaces** the whole list, send `[]` to clear it, omit it to leave it alone.
It belongs to the subscription, not to whoever reads it: a key's role narrows what that key may
be told, and this narrows what this receiver is sent, no matter which key or dashboard session set it.
Editing it applies to everything emitted afterwards, and stops a retry tail already running.

## Leaving one event out

`events` is the whole subscription: the names you list, or `["*"]` for every event including ones added later. To leave one
event out, list the others; the dashboard's "All events" with one box un-ticked sends every name but that one. A list of names receives only those names: an event added to the catalog later is not sent to it until you
add it. An unknown name is refused with `400`; the list holds at most every catalog name once. Once an endpoint no longer
receives an event, nothing of it is sent, on retry, **Re-run** and **Send test** (refused with `409 event_disabled`). A name
we have removed from the catalog that your endpoint still held is dropped when you send the list back, not refused.

## Turning off a location

`disabledLocationIds` is an opt-out **denylist** of location ids, the outlets on the brand's Locations
page. An event that belongs to a location you have listed is never delivered to this endpoint ("this
receiver does not cover Koramangala". The location is the one the event's conversation or contact sits
in; an event with no location (a template decision, a broadcast, a post) always arrives. It is a
denylist, so a location opened later is covered automatically. Same update
rule as `disabledResourceGroups`: the array replaces the list, `[]` clears it, omitted leaves it alone.

## Turning off a connection

`disabledConnections` is an opt-out **denylist** of connection ids, the connected accounts the
brand has on the Channels page (the `connectionId` an event payload carries). An event that came from
a connection you have listed is never delivered to this endpoint ("this receiver does not cover our
TikTok account"), and that holds:

- for every event in `events`, including under `["*"]`. A denylist, not an allowlist: an account
  connected later is covered automatically, because its id is in nobody's list.
- on every replay path, a retry already in flight and **Re-run**. Re-run on an excluded connection is
  refused with `409 connection_disabled`.
- never against an event with no connection (a broadcast, a contact created by hand, a post's overall
  verdict across several accounts): those always arrive.

```json
{ "name": "TikTok CRM", "url": "https://…", "events": ["*"], "disabledConnections": ["<instagram connection id>"] }
```

On update the array **replaces** the whole list, send `[]` to clear it, omit it to leave it alone.
Each id must be a uuid, and an id you are adding must be one of this brand's connections (`400`
otherwise); an id already on the list is kept even if that connection was later removed.

## Every delivery

```
POST <your url>
Content-Type: application/json
User-Agent: Otobiz-Webhooks/1.0
X-Otobiz-Event: message.received
X-Otobiz-Event-Id: evt_3y5ebc87r8999srxhxg6re9wn9
webhook-id: 7e2b96c4-1f08-4a53-9c76-3d81b0e4f2a9                                   (unless the secret was removed)
webhook-timestamp: 1788700800                                                     (unless the secret was removed)
webhook-signature: v1,lxbFi0dxLQaIclbdtsy3QQIW/7tiUM94M3wLOFoNP6s=                 (unless the secret was removed)

{
  "id": "7e2b96c4-1f08-4a53-9c76-3d81b0e4f2a9",
  "type": "message.received",
  "createdAt": "2026-09-06T10:00:00.000Z",
  "apiVersion": "v1",
  "brand": { "id": "brd_…", "externalId": null },
  "source": "platform",
  "actor": null,
  "data": {
    "object": {
      "id": "…", "providerMessageId": "wamid.…", "conversationId": "…", "connectionId": "…", "channel": "whatsapp",
      "type": "image", "text": "Is the blue one still in stock?", "choice": null,
      "sender": { "contactId": "…", "externalId": "•••10", "displayName": "Priya", "bsuid": null, "username": null },
      "attachments": [{ "kind": "image", "fileName": "IMG_0042.jpg", "mimeType": "image/jpeg", "sizeBytes": 183211 }],
      "referral": null
    },
    "previous": null
  },
  "test": false
}
```

- **One envelope for every event** (the same one MCP events and the inbox stream carry): `id`, `type` (the event
  name), `createdAt`, `apiVersion` (`v1`), `brand` (`id`, `externalId`), `source`, `actor`, `data` and `test`. The
  event's content is `data.object`; on an update `data.previous` holds the fields that changed, as they were
  before (`null` otherwise). Copied from Stripe's event object.
- **`source` and `actor` say who caused it**, so a receiver can ignore the echo of its own write.
  `source` is `api` (an API key or an AI app), `dashboard` (a person signed in), `automation`, `ai_agent` (our AI
  agent), `broadcast`, `sequence`, `platform` (a message, comment, order or status the platform delivered) or
  `system` (a timer). `actor` is `{ type, id, name }` (`member`, `api_key`, `oauth_grant`, `automation`, `ai_agent`,
  `broadcast`, `sequence`; `name` is the person, the key's name or the AI app's name) and `null` for `platform` and
  `system`.
- **`X-Otobiz-Event-Id`, `webhook-id` and `payload.id` are the same value: your dedupe key.** Deliveries are
  at-least-once: a retry, and a rare provider redelivery upstream of us, carry the same id. Insert it
  into a unique-indexed table before you process the event and skip on conflict. Events can also arrive
  **out of order** (retries run independently), order by `createdAt`, never by arrival.
- **`metadata`** (WH-3): set an object (≤ 1 KB) on the endpoint and it rides every body as a top-level
  `metadata` key, e.g. the id your system keys the subscription on.
- **The content rides the payload.** A message carries its text, its sender and its attachment
  references; an order carries its id and totals; a flow response carries its answers. What stays
  behind the authenticated API is **media bytes**; a photo or document is referenced by kind and
  name here and fetched with your API key, because files are large, are replayed on retry, and are
  the sharpest kind of customer data to push at a URL.
- **Success is a `2xx` inside 5 seconds.** Anything else (a non-2xx status, a timeout, a connection
  error, or any `3xx`, with redirects refused outright and never followed) is a failure.

## Verifying the signature

Signatures follow [Standard Webhooks](https://github.com/standard-webhooks/standard-webhooks), so any
Standard Webhooks library verifies them. A delivery to an endpoint with a secret carries three headers:

| Header | Value |
|---|---|
| `webhook-id` | the event id (same as `X-Otobiz-Event-Id`) |
| `webhook-timestamp` | Unix seconds when this attempt was signed; every retry signs again |
| `webhook-signature` | `v1,<base64 HMAC-SHA256>` over `"{webhook-id}.{webhook-timestamp}.{raw body}"` |

**Key:** a `whsec_…` secret (the default) is the base64-decoded bytes after the prefix (24 to 64 bytes); any
other secret is its UTF-8 bytes. Binding the timestamp in is what stops a captured delivery being replayed
later with a still-valid signature, so **check freshness first**: refuse a `webhook-timestamp` more than
**300 seconds** from your clock, then compute, then compare in constant time.

**Rotation:** after you PATCH a new `secret`, the old one keeps signing beside it for 24 h, and
`webhook-signature` then holds two space-separated `v1,` values; accept if any verifies, and switch your
receiver at leisure.

Use the **raw body bytes**, never a re-serialised object: `JSON.parse` then `JSON.stringify` can
reorder keys or reformat numbers, and the signature will then disagree for a body that was never
tampered with.

```js
// Node: capture the raw body before any JSON.parse; freshness first; timing-safe compare
import { createHmac, timingSafeEqual } from "node:crypto";
const FRESHNESS_SECONDS = 300;
function signingKey(secret) {
  const b64 = secret.startsWith("whsec_") ? secret.slice(6) : "";
  if (b64 && b64.length <= 128 && b64.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(b64)) {
    const bytes = Buffer.from(b64, "base64");
    if (bytes.length >= 24 && bytes.length <= 64) return bytes;
  }
  return Buffer.from(secret, "utf8");
}
function verifyOtobiz(rawBody /* Buffer */, headers /* lower-cased */, secret /* string */) {
  const id = String(headers["webhook-id"] ?? ""), ts = String(headers["webhook-timestamp"] ?? "");
  const header = String(headers["webhook-signature"] ?? "");
  if (!id || !header || !/^\d+$/.test(ts)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > FRESHNESS_SECONDS) return false;
  const input = Buffer.concat([Buffer.from(`${id}.${ts}.`, "utf8"), rawBody]);
  const expected = Buffer.from(`v1,${createHmac("sha256", signingKey(secret)).update(input).digest("base64")}`, "utf8");
  return header.split(" ").some((part) => {
    const given = Buffer.from(part, "utf8");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

```python
# Python, flask: request.get_data() is the raw body
import base64, binascii, hmac, hashlib, time
FRESHNESS_SECONDS = 300
def signing_key(secret: str) -> bytes:
    if secret.startswith("whsec_"):
        try:
            key = base64.b64decode(secret[6:], validate=True)
        except (binascii.Error, ValueError):
            key = b""
        if 24 <= len(key) <= 64:
            return key
    return secret.encode()
def verify_otobiz(raw_body: bytes, headers, secret: str) -> bool:
    wid = headers.get("webhook-id") or ""
    ts = headers.get("webhook-timestamp") or ""
    header = headers.get("webhook-signature") or ""
    if not wid or not header or not ts.isdigit():
        return False
    if abs(int(time.time()) - int(ts)) > FRESHNESS_SECONDS:
        return False
    digest = hmac.new(signing_key(secret), f"{wid}.{ts}.".encode() + raw_body, hashlib.sha256).digest()
    expected = "v1," + base64.b64encode(digest).decode()
    return any(hmac.compare_digest(expected, part) for part in header.split(" "))
```

Reject an unsigned, stale or mismatched request and do not process the payload. Zapier users: choose
**Catch Raw Hook**, not Catch Hook. Only the raw variant hands you the unparsed body and the headers
this check needs.

Copy-paste verifiers for Node, Python, PHP and Go, n8n files to import, and a sample payload
for every event: [WEBHOOK-CONNECTORS.md](webhook-connectors.md).

## Signed, not encrypted

Deliveries are signed (above) and sent over the URL you register; the body is not encrypted. Register an `https` URL so
the event is encrypted in transit, as every major webhook sender asks.

## Delivery metrics

Dashboard: **Developers → Webhooks →** an endpoint **→ Overview → Delivery metrics**: success and failed attempts,
failure rate, average and maximum latency, and an average-latency chart (hourly for 24 hours, daily for 7 and 30
days). One attempt is one POST; a failure is any attempt that ended in an error. Read-only, from the delivery log.

## Retries and dead-letter

Seven attempts on a fixed backoff, about 51 hours end to end:

| Attempt | Delay before it |
|---|---|
| 1 | immediate |
| 2 | 10s |
| 3 | 100s |
| 4 | 1,000s (~17m) |
| 5 | 10,000s (~2h 46m) |
| 6 | 24h |
| 7 | 24h |

After the seventh failure the delivery is **dead-lettered** and you're notified in-app (a bell entry
on the brand) and, if you have a Telegram owner-notify connection connected, there too. That delivery is not
tried again. Press **Re-run** from the log once your endpoint is fixed to give it
a fresh attempt tail with the same event id.

### Asking us to redeliver, using the id YOU have

Re-run is also an API call, and you can address the delivery by the **event id**: the `id` field of
the envelope we sent you, which your receiver already stores to dedupe on. You do not need our
internal delivery id, and you no longer have to search our log to find it first:

```
POST /api/v1/webhooks/{endpointId}/events/{eventId}/retry     # the id from the payload we sent
POST /api/v1/webhooks/logs/redeliver   # our id, from the delivery log
```

Both do exactly the same thing: the stored payload replayed byte for byte to the endpoint's current
URL, the same event id, a fresh attempt tail continuing the attempt numbering. The endpoint id is
required in both forms and is not a formality: one event fans out to every subscribed endpoint, so
an event id on its own names a set of deliveries, not one delivery.

A 404 means "this endpoint was never sent that event". It does not distinguish "no such event" from
"that event went to a different endpoint", deliberately. Otherwise the pair would let a caller map
which of your endpoints received what.

**An endpoint that stops answering is paused for you.** One that has not succeeded for three days, after a run of
failed deliveries, is paused and the brand's developers are told in the app and by email, once per pause. An AI app's event
subscription follows the same rule; it starts again when the app subscribes again. You can also pause an endpoint yourself. A delivery whose group you
have since added to `disabledResourceGroups` is not retried and cannot be re-run, clear the group first if you want it after all.
Pausing stops deliveries to that endpoint and ends any retry tail in flight; the events that match meanwhile are kept.
Resuming (`PATCH {"paused": false}`, or **Resume** on the page) sends every kept event and everything that was mid-tail
when you paused, oldest first, a page at a time, so a long pause does not slow the answer. The answer's `deliveries_requeued`
warning says how many are being sent. A kept event older than the delivery log's 180 days is pruned with it. An endpoint that answered 410
Gone is paused and keeps nothing until you resume it.

## How it behaves

- Every event is delivered at least once, so the same event can arrive twice: dedupe on the event id.
- Events can arrive out of order: order by `createdAt`.
- Success is a `2xx` within 5 seconds. Anything else is retried on the schedule above, then dead-lettered.
- A paused endpoint keeps its events and sends them when you resume it.

### Where a delivery comes from

Each change is stored as one event in the same database transaction as the change, and every delivery is made from
that stored event: a change that was undone sends nothing, and one that happened is never lost. The event's `id` is the
same on every endpoint, on MCP Events and on every retry, so one dedupe covers them all. A delivery usually leaves
within a second of the change.

## If it fails

| What you see | Cause | Fix |
|---|---|---|
| Deliveries show failed attempts | Your URL answered non-2xx, timed out, or redirected (redirects are refused) | Answer `2xx` inside 5 seconds. Failed ones retry on their own. |
| A delivery is dead-lettered | Seven attempts failed | Fix the endpoint, then **Re-run** it from the log. |
| The endpoint shows paused | You paused it, it answered 410, or it failed for three days | Fix the URL, then resume it. Kept events are sent. |
| Signature check fails | A changed body, a wrong secret, or a timestamp more than 300 seconds from your clock | Verify against the raw body with the endpoint's secret. |
| Re-run answers `409` | The event's group or connection is on the endpoint's denylist | Clear it, then re-run. |
| Re-run answers `404` | That endpoint was never sent that event | Check the endpoint id and the event id. |

## `webhook_endpoint.tested`

The **Send test** button (or `POST /webhooks/{id}/test`) sends one synchronous delivery,
regardless of which events the endpoint subscribes to, with no retries:

```json
{ "id": "evt_...", "type": "webhook_endpoint.tested", "createdAt": "...", "apiVersion": "v1", "brand": { "id": "...", "externalId": null },
  "source": "system", "actor": null, "data": { "object": { "message": "This is a test webhook from Otobiz" }, "previous": null }, "test": true }
```

It's logged like any other delivery and is
re-runnable from the log; a failed test is dead-lettered at once (it has no retry tail). Use it to
prove your receiver verifies the signature and answers inside 5 seconds before subscribing it to
anything real.

## Event catalog

Every name is `<noun>.<past tense>`, and `data.object` is that noun's summary, as its own reads print it. The list
with each event's description is served live: the dashboard's create form, `GET /webhooks?include=catalog`
(`catalog`), the published document's `webhooks` (`apps/openapi/public.json`) and `docs/events.md`, all generated from
`base/webhooks/events.ts`. Nothing here repeats it.

Events are grouped by what they are about (`messages`, `engagement`, `publishing`, `contacts`, `ads`, `commerce`,
`accounts`, `analytics`, `billing`, `webhooks`), plus our own `ai_agent`, `automations`, `campaigns` and `team`. A
group's **id** is the value `disabledResourceGroups` takes, its `area` the area its nouns live in, and its **read scope** that
area's read, the scope the noun's own reads take. A key holds the reads of its
role: every role but the Billing manager reads every area but Developers; `developers:read` is an owner's or admin's.

| Group id | Scope | Its nouns' events |
|---|---|---|
| `inbox` | `inbox:read` | messages, conversations, comments, reviews, mentions, requests, labels, saved replies, approvals |
| `contacts` | `contacts:read` | contacts, contact fields, leads, segments, tags, declared events |
| `ai_agent` | `ai_agent:read` | the AI's settings, skills and knowledge, research runs |
| `automations` | `automations:read` | automations, their runs and settings, variables, post groups, templates, keyword links, QR codes, sequence enrolments |
| `campaigns` | `campaigns:read` | broadcasts, message templates, WhatsApp forms and their responses, tracked link clicks |
| `posts` | `posts:read` | posts, posting times |
| `ads` | `ads:read` | ads, lead forms |
| `store` | `store:read` | orders (`order.created` for every source, `source` saying which), products, store settings, payment setups, bookings |
| `connections` | `connections:read` | connections |
| `developers` | `developers:read` | tool calls, the Send-test delivery |
| `account` | `account:read` | the plan and purchases, usage, notices, the team, routing queues and rules (who gets handed-off chats; read with the inbox's roles, never the Billing manager's) |

An envelope's `id` is the event's id (`evt_...`): the same in `X-Otobiz-Event-Id`, `webhook-id` and every retry.

### Routing for partners: which field names the tenant

Running one endpoint for many of your own customers (each an Otobiz brand)? Stamp a custom header
per endpoint and route on it. That is what custom headers are for. Inside the payload, the field
that identifies the customer-side record is:

| Events | Route on |
|---|---|
| `message.*` | `data.object.sender.contactId`, `data.object.conversationId` |
| `conversation.*` | `data.object.id` (or `data.object.conversationId` on `started` and `rated`), `data.object.contact.id` |
| `commerce.*`, `order.*` | `data.object.id`, `data.object.contactId` |
| `contact.*` | `data.object.id` |
| `flow.*`, `lead.*` | `data.object.contactId` (`lead.created`); `data.object.connectionId` (`lead.created`) |
| `comment.*`, `review.*` | `data.object.contactId` when matched, else `data.object.connectionId` |
| `post.*`, `ad.*` | `data.object.id`, `data.object.connectionId` on the per-account events |
| `approval.*` | `data.object.conversationId` / `data.object.contactId` when the subject names them, else brand-level |
| `template.*`, `number.*`, `account.*`, `connection.*`, `broadcast.*` | brand-level; route on your custom header |

## What this is not

Not the consent / suppression / 24-hour-window gauntlet a customer message goes through. A webhook
is a system-to-system notification to your own infrastructure, not a message to your customer. If a
webhook should trigger a message on your side, send it back in through `POST /api/v1/events` and it
meets that gauntlet there, the same as any other message.
