# Webhook Integration

Canonical: https://docs.bluehola.com/docs/guides/webhook-integration
OpenAPI: https://docs.bluehola.com/openapi.yaml

Create a callback endpoint to receive user messages, status updates and asset changes such as phone numbers and templates, without polling.

## Creating an endpoint

```bash
curl -X POST https://api.bluehola.com/v1/webhook-endpoints \
  -H "Authorization: Bearer <API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://your-server.example.com/whatsapp-webhook", "events": ["message", "status"] }'
```

`events` is optional; the permitted values are in the "Event types" table below, and leaving it out saves `*` (receive everything, including types added later). `secret` is optional; if you supply your own it must be **at least 16 characters**, and if you do not the platform generates a random value prefixed `whsec_`. **The secret is returned only once, in the creation response** — it is what verifies signatures, so save it immediately; the platform will never show it in plaintext again.

Optional fields narrow the scope and select the protocol:

| Field | Purpose |
| ---- | ---- |
| `customerId` | Receive events for every Business Portfolio the customer entity (`cust_...`) currently owns, including Portfolios it adds later. Recommended when one receiver serves one customer. A customer Key must pass its own customer entity here. |
| `projectId` | Receive events only for that single Business Portfolio (`bm_...`). Mutually exclusive with `customerId`; customer Keys cannot use it. |

With neither `customerId` nor `projectId` the endpoint is account-level and receives every event under the account. **An endpoint with a binding never receives events outside it**; when an event's ownership cannot be resolved it is not delivered there either (better to miss a delivery than to send it to the wrong party).

| Field | Purpose |
| ---- | ---- |
| `connectionId` | Use the **connection protocol**: the newer signature scheme described below, with the endpoint starting out `pending` and delivering nothing until ownership verification passes. It can also be written as `metadata.connection_id`; the two forms are equivalent. |

`metadata` accepts arbitrary JSON, which the platform stores verbatim and returns when you read the endpoint.

## Endpoint states

| How it was created | Initial status | Notes |
| -------- | ----------- | ---- |
| Without `connectionId` / `metadata.connection_id` | `active` | **Delivery starts immediately**; no further action needed. |
| With `connectionId` | `pending` | It only becomes `active` after `POST /v1/webhook-endpoints/{id}/verify` passes ownership verification; nothing is delivered before that. |

`DELETE /v1/webhook-endpoints/{id}` is a **soft disable** (status becomes `disabled`, delivery stops, history is retained), and the response body is the disabled endpoint object rather than an empty body. To restore it use `POST /v1/webhook-endpoints/{id}/enable`: a verified endpoint returns to `active`; an unverified connection-protocol endpoint returns to `pending` (it must pass verification again — this is not something the caller can override).

:::note

**Read this before rotating a secret.** `POST .../rotate-secret` takes effect immediately with no overlap period: the very next delivery is signed with the new secret, so any delivery that arrives before you have stored the new value will fail verification and — being a 4xx — is treated as a **permanent failure and not retried**. The safe approach is to rotate during a quiet period, or to `DELETE` (disable) → rotate → store the value → `POST .../enable`.

:::

## URL restrictions

Endpoint URLs are checked on both creation and update, and a failure returns `400 VALIDATION_FAILED`:

- production URLs **must be https**;
- the hostname cannot be an internal name such as `localhost` or `metadata.google.internal`;
- the resolved address must not fall in a private, loopback, link-local (including the cloud metadata address `169.254.169.254`) or CGNAT reserved range — and **resolution is repeated before every delivery**, so repointing the domain at an internal address afterwards is blocked too.

## Ownership verification and testing

`POST .../verify` and `POST .../test` use the **same mechanism** (what a test needs to answer is exactly "can this address receive, and can it verify signatures" — a separate path would allow tests to pass while real deliveries fail):

1. The platform synchronously POSTs a `webhook.verification` event to your URL, with `data.challenge` holding a random value prefixed `ch_`;
2. Your endpoint verifies the signature first, then echoes that value back in the response body — either as top-level `{"challenge":"..."}` or as `{"data":{"challenge":"..."}}`;
3. The platform compares it with a constant-time comparison, and on success the endpoint becomes `active`.

The challenge request times out after **5 seconds** (shorter than a regular delivery, because the caller is waiting for the result), and at most 4 KB of the response body is read. Failure does **not** change the status — the endpoint stays `pending`, so fix the receiving side and call again; the reason is in the response's `reason` field.

The challenge is **signed exactly the way real events are**, so passing verification means real events will verify too.

```mermaid
sequenceDiagram
    autonumber
    participant C as Caller
    participant P as BlueMedia
    participant E as Your endpoint
    C->>P: POST /v1/webhook-endpoints/{id}/verify
    P->>E: POST webhook.verification (data.challenge = ch_...)
    Note over P,E: 5 second timeout, at most 4 KB of the body read
    E->>E: Verify the signature, then read the challenge
    E-->>P: Echo {"challenge":"ch_..."}
    P->>P: Constant-time comparison
    P-->>C: Success → active. Failure → stays pending (see reason)
```


## Verifying signatures

There are two signature schemes, **chosen by whether the endpoint was created with the connection protocol**. When reading an endpoint, an `apiVersion` of `null` means the first scheme below.

### Default scheme (`apiVersion: null`)

Every callback carries `X-Webhook-Signature-256: sha256=<hex>`, which is an HMAC-SHA256 over the **raw request body bytes** using the endpoint secret. You must verify it before parsing the JSON — compute the same value yourself and compare against the header:

```js
const crypto = require('node:crypto');

function verify(rawBody, signatureHeader, secret) {
  if (typeof signatureHeader !== 'string') return false;   // header missing
  const expected = Buffer.from('sha256=' + crypto
    .createHmac('sha256', secret)
    .update(rawBody)      // must be the raw bytes, not the result of parsing and re-stringifying
    .digest('hex'));
  const provided = Buffer.from(signatureHeader);
  // timingSafeEqual throws when the lengths differ — check first, or a malformed header becomes a 500 instead of a rejection
  if (provided.length !== expected.length) return false;
  return crypto.timingSafeEqual(expected, provided);
}
```

The other headers: `X-Webhook-Event` (this event's type, see below) and `X-Delivery-Id` (the unique id of this delivery, for reconciliation and de-duplication).

### Connection protocol scheme (`apiVersion` non-null)

Endpoints created with a `connectionId` use four different headers, and **none of the three above appear**:

| Header | Meaning |
| ------ | ---- |
| `Webhook-Id` | The event id, for idempotent de-duplication. Platform events use `evt_...`; the fan-out of Meta inbound events uses the delivery id (`wd_...`) |
| `Webhook-Endpoint-Id` | The endpoint id (`whe_...`) |
| `Webhook-Timestamp` | The unix seconds at signing time |
| `Webhook-Signature` | `v1,<hex>` |

`<hex>` is `HMAC_SHA256(secret, "<Webhook-Timestamp>.<raw request body>")`. **The timestamp is part of the signature** rather than just a header, so it cannot be tampered with, and the receiver can reject replays outside a tolerance window on that basis:

```js
const crypto = require('node:crypto');

function verifyV1(rawBody, timestampHeader, signatureHeader, secret) {
  const [version, provided] = String(signatureHeader).split(',', 2);
  if (version !== 'v1' || !provided) return false;
  const expected = crypto
    .createHmac('sha256', secret)
    .update(`${timestampHeader}.${rawBody}`)   // again, must be the raw bytes
    .digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(provided);
  if (a.length !== b.length) return false;   // compare byte lengths: a non-ASCII header has more bytes than characters
  return crypto.timingSafeEqual(a, b);
}
```

### Ownership headers (both schemes)

Every delivery, under either signature scheme, also carries ownership headers so the receiver can tell which account, Business Portfolio and customer entity an event belongs to — Meta inbound events are forwarded as-is and their body has no `account_id`:

| Header | Meaning |
| ------ | ---- |
| `X-Account-Id` | The account the event belongs to (the same value as `account_id` in the platform event envelope) |
| `X-Project-Id` | The Business Portfolio (`bm_...`) |
| `X-Customer-Id` | The customer entity (`cust_...`) |

`X-Project-Id` and `X-Customer-Id` are **omitted** — not sent empty — when that ownership cannot be resolved (for example the WABA has not finished onboarding, or the Portfolio has no customer entity). Use them for attribution, reporting and troubleshooting; to route Meta inbound events, key on `metadata.phone_number_id` in the payload, which is always present. These headers are not part of the signature, so existing signature verification is unaffected.

## Event types

The values of `X-Webhook-Event` (or `type` in the connection protocol's event envelope) fall into two groups, **listed together in the same `events` array when subscribing**:

Meta inbound events:

| kind      | When it fires                                                                           |
| --------- | ---------------------------------------------------------------------------------- |
| `message` | The user sent a new message (of any type, including images, documents and locations).                                   |
| `status`  | A status change on a message you sent: `sent` / `delivered` / `read` / `failed`.                   |
| `change`  | Other asset changes (phone numbers, template review outcomes and so on) — everything that is not one of the two above.               |
| `probe`   | The fallback classification for a Meta callback whose body **cannot be parsed as any known event** (a Meta connectivity probe, or a new payload shape we do not recognise yet). The raw body is in `value`. It is **not** the console's "Test" button, which sends `webhook.verification`. |

Platform events:

| kind                  | When it fires                                                       |
| --------------------- | -------------------------------------------------------------- |
| `job.completed`       | A platform-side asynchronous job completed.                                         |
| `job.failed`          | A platform-side asynchronous job failed.                                         |
| `usage.updated`       | Usage data changed.                                             |
| `webhook.verification` | The challenge event for ownership verification and testing (see the previous section).                        |
| `contact.identity_changed` | A user's BSUID changed, or Meta sent an identity-change system message. See Normalized events below. |
| `contact.info_shared` | A user shared contact details. See Normalized events below. |
| `marketing.preference_updated` | A user stopped or resumed marketing messages. See Normalized events below. |
| `phone_number.username_updated` | A business username's status changed. See Normalized events below. |

`*` means receive everything, **including types added in future** — make sure an endpoint subscribed to `*` ignores or logs types it does not recognize rather than failing. Prefix wildcards such as `job.*` are not supported — only exact values and `*`.

## Delivery and retries

A `2xx` from your endpoint counts as a successful delivery. `5xx`, `429` and network-level failures are treated as transient and retried; any other `4xx` (for example you deliberately rejecting after a failed signature check) is a terminal failure and is **not** retried — so make sure your endpoint returns 5xx rather than 4xx for transient faults. Each request times out after 10 seconds.

The retry schedule is a **fixed table**, not exponential backoff. After the first delivery there are at most 7 retries, for **8 attempts in total**:

| Retry # | Since previous failure |
| ---------- | ------------ |
| 1 | immediately |
| 2 | 1 minute |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 12 hours |
| 7 | 24 hours |

The early "immediately + 1 minute" steps cover the vast majority of transient faults; stretching the later ones out to hours gives the receiving side's operators time to fix things. **The whole retry window is about 38.6 hours**; after 8 attempts it gives up rather than retrying forever. An event your endpoint missed after that can be found with [List Deliveries](../webhooks/get-v1-webhook-endpoints-id-deliveries.md) (`status=failed`) and sent again with [Redeliver a Delivery](../webhooks/post-v1-webhook-endpoints-id-deliveries-deliveryid-redeliver.md).

Because retries exist, delivery is **at-least-once**: de-duplicate on the event id (`X-Delivery-Id` under the default scheme, `Webhook-Id` under the connection protocol). A manual redelivery keeps the original `Webhook-Id` under the connection protocol, but gets a new `X-Delivery-Id` under the default scheme — if you redeliver an event your endpoint may already have processed, de-duplicate on the event content (for example the message `id` / `wamid`).

`GET /v1/webhook-endpoints` returns each endpoint's **most recent** delivery result (`lastDelivery`: status, response code, attempt count, latest error, timestamp), or `null` if nothing has ever been delivered. Counts of delivered/failed/pending are deliberately not provided — that kind of aggregate gets slower as message volume grows, and "did the last one succeed" is the signal you actually need. For individual delivery records, use [List Deliveries](../webhooks/get-v1-webhook-endpoints-id-deliveries.md).

## Payload structure

There are two shapes, paired with the two signature schemes.

Every event type has a standalone schema suitable for Ajv, a JSON Schema validator or a code generator; the entry point is [OpenAPI & Agent Access](../reference/openapi.md). The `webhooks` section of the OpenAPI 3.1 document references the same contracts.

### Meta inbound events (fan-out, paired with the default signature scheme)

The callback body takes the shape `{ kind, ...context fields, message / status / value }`, with the fields varying by `kind`:

```json title="Example status event"
{
  "kind": "status",
  "wabaId": "waba_...",
  "phoneNumberId": "pn_...",
  "status": {
    "id": "wamid.HBg...",
    "status": "delivered",
    "timestamp": "1735000000",
    "recipient_id": "8613800138000",
    "pricing": {
      "billable": true,
      "pricing_model": "PMP",
      "category": "marketing_lite_dynamic",
      "type": "regular",
      "cost": { "amount": 0.035, "currency": "USD" }
    }
  }
}
```

For a Max Price template, `delivered` and `read` status events use `pricing.category: "marketing_lite_dynamic"` and may include `pricing.cost`. `cost.amount` is a number in the currency's base unit (for example dollars for USD), and `cost.currency` is the ISO currency. This is Meta's **estimated** charge; the Meta invoice is the source of truth for final pricing. Other pricing fields are forwarded unchanged.

### The platform event envelope (paired with the connection protocol signature scheme)

Events the platform publishes itself (`job.*`, `usage.updated`, `webhook.verification` and the normalized events below) use a fixed envelope with the business content in `data`:

```json title="Example webhook.verification"
{
  "id": "evt_...",
  "type": "webhook.verification",
  "api_version": "2026-01-01",
  "created_at": "2026-09-20T10:00:00.000Z",
  "account_id": "tenant_...",
  "project_id": "bm_...",
  "data": { "challenge": "ch_..." }
}
```

`project_id` is `null` on account-level endpoints. `created_at` is always UTC with millisecond precision.

## Normalized events

For a few kinds of Meta notification, the platform publishes an **additional** event in the platform envelope so you do not have to parse Meta's nested shapes. The original `message` / `change` event is still forwarded; the two carry the same content in different shapes, so subscribe to whichever you want to handle. Fields are snake_case. A field Meta did not provide is `null` — the platform never infers or fills it in (for example, it never substitutes a BSUID for a missing phone number).

Most of these events carry `meta_phone_number_id` and `meta_waba_id` (the Meta-side IDs of the number and WABA), and `occurred_at` (Meta's event time, `null` if it could not be parsed).

### `contact.identity_changed`

| Field | Meaning |
| --- | --- |
| `source` | `user_id_update` (Meta's structured BSUID change) or `system_message` (an identity-change system message). |
| `user_id` | `{ previous, current }`. For `system_message`, `previous` is `null`: Meta puts the old BSUID only in human-readable text, which is not a contract. |
| `parent_user_id` | `{ previous, current }` or `null`. |
| `wa_id` | The user's phone number, or `null`. |
| `detail` | Meta's `detail`, for `user_id_update`. |
| `conversations_remapped` | For `user_id_update`: how many conversations in this account were moved to the new BSUID. |
| `system_type` / `wamid` / `from` | For `system_message`: `user_changed_user_id` or `user_changed_number`, the system message ID and its sender. |

### `contact.info_shared`

| Field | Meaning |
| --- | --- |
| `wamid` / `from` / `from_user_id` | The `contacts` message ID, the sender's phone number and BSUID. |
| `context_wamid` | The message this one replied to, if any. |
| `contacts[]` | `origin`, `has_vcard` and `phones[]` (`phone`, `wa_id`, `type`). The vCard itself is in the original `message` event. |

`origin` is `contact_request` when the user tapped a [contact information request](../messaging/post-v1-messages.md) and shared their own details, `other` when they sent a contact card directly (which may be someone else's), and `null` when Meta did not say. The two cases need opposite handling, so **do not treat `null` as `contact_request`**.

### `marketing.preference_updated`

| Field | Meaning |
| --- | --- |
| `value` | `stop` or `resume`. Other values are not forwarded. |
| `wa_id` / `user_id` / `parent_user_id` | The user's phone number and BSUIDs. `wa_id` may be `null` with only `user_id` present; at least one of `wa_id` and `user_id` is set. |
| `applies_to_meta_phone_number_id` | The sending number this preference applies to. It is not extended to the whole business or to other numbers. |
| `category` | The preference category, `marketing_messages` by default. |
| `detail` | Meta's `detail`. |

The platform blocks marketing sends to an opted-out user whichever identifier you send to; see `MARKETING_OPT_OUT` in [Error Codes](error-codes.md).

### `phone_number.username_updated`

| Field | Meaning |
| --- | --- |
| `display_phone_number` | The phone number, digits only. |
| `username` / `status` | The business username and its status (`approved`, `reserved` or `deleted`). |
| `applied` | `false` means this was a late, older event and the platform did not use it to overwrite a newer value — do not use it to overwrite yours either. |

This event carries `meta_waba_id` but no `meta_phone_number_id`.
