> ## Documentation Index
> Fetch the complete documentation index at: https://exchanger-api.iexexchanger.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Receive and verify a webhook

> Subscribe to Exchanger API events, verify the exact v2 payload bytes, and acknowledge deliveries without processing the same event twice.

When the status of an order changes, Exchanger API sends your HTTPS handler a compact notification. Use its resource ID to read the current state. If the same event arrives again, acknowledge it and apply your business change once.

## 1. Register the receiver

Point the subscription at a publicly reachable HTTPS handler with valid TLS. Use the final URL that accepts JSON `POST` requests. The delivery service sends directly to that address.

In `order-webhook.json`, replace the example URL with your receiver. Run the [signed HTTP request](https://exchanger-api.iexexchanger.com/en/start/quickstart.md) with a key that has `public-api:webhooks:write`. Use `events: ["*"]` if your handler needs all event types. For `payload_version` use `v2` when supplying the field.

```json order-webhook.json theme={null}
{
  "name": "Order status receiver",
  "url": "https://partner.example.com/webhooks/exchanger",
  "events": ["order.created", "order.status_changed", "order.payment_received"],
  "payload_version": "v2"
}
```

```bash theme={null}
node request.mjs POST '/api/v3/private/webhooks' \
  --json order-webhook.json \
  --idempotency-key 'webhook-create-4e03d05d-3989-4ad0-9949-8bf525a095aa'
```

From `201`, save `result.endpoint.id` and put `result.endpoint.secret` in your secret store. The subscription secret verifies webhook deliveries. Your API key and API HMAC secret authorize requests to the exchange. Subscription list and detail responses expose the `secret_fingerprint` for identification.

## 2. Send a test

Put the subscription ID returned by the API in `test-webhook.json`.

```json test-webhook.json theme={null}
{
  "endpoint_id": "c4c6abae-9d53-4874-b55d-e94dee98df81",
  "event_type": "order.status_changed"
}
```

```bash theme={null}
node request.mjs POST '/api/v3/private/webhooks/test' \
  --json test-webhook.json \
  --idempotency-key 'webhook-test-cedc56cd-ef83-410b-9c58-82ef4638d915'
```

A `201` registers the test. The payload has `type: "api.test"`, `test: true`, and `sample_of: "order.status_changed"` when you choose this sample. When `endpoint_id` is omitted, the API sends to active subscriptions for `event_type` or defaults to `api.test`. A subscription for `*` also matches. Confirm receipt in [delivery history](https://exchanger-api.iexexchanger.com/en/guides/reliability/webhook-deliveries.md).

## 3. Verify the signature

Read the exact body bytes before parsing JSON. Require `X-Webhook-Signature-Version: v2`. The HMAC input consists of seven lines joined by LF, with no trailing newline.

```text theme={null}
webhook-v2
event_id
event_type
timestamp
attempt
nonce
sha256_body
```

| Canonical value | Source |
| - | - |
| `event_id` | `X-Webhook-Event-Id` |
| `event_type` | `X-Webhook-Event-Type` |
| `timestamp` | `X-Webhook-Timestamp`, Unix seconds |
| `attempt` | `X-Webhook-Attempt`, counting from `1` |
| `nonce` | `X-Webhook-Nonce` |
| `sha256_body` | Lowercase hexadecimal SHA-256 of the exact body bytes |

Compute HMAC-SHA256 with the subscription secret. The `X-Webhook-Signature` header contains `sha256=` followed by the lowercase hexadecimal value. Compare in constant time and match the signed event ID and type against the JSON. Use the timestamp to reject stale attempts. The example allows 300 seconds of clock skew.

Save the verification function as `verify-webhook.mjs`. It accepts the original bytes, request headers and subscription secret. Omit the optional clock argument when verifying live deliveries.

```javascript verify-webhook.mjs theme={null}
import { createHash, createHmac, timingSafeEqual } from 'node:crypto';

const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const positiveDecimal = /^[1-9][0-9]{0,15}$/;

export function verifyWebhook(rawBody, headers, secret, now = Math.floor(Date.now() / 1000)) {
  const id = headers.get('X-Webhook-Event-Id');
  const type = headers.get('X-Webhook-Event-Type');
  const timestamp = headers.get('X-Webhook-Timestamp');
  const attempt = headers.get('X-Webhook-Attempt');
  const nonce = headers.get('X-Webhook-Nonce');
  const signature = headers.get('X-Webhook-Signature') ?? '';

  if (!secret || headers.get('X-Webhook-Signature-Version') !== 'v2'
    || id === null || !uuid.test(id) || nonce === null || !uuid.test(nonce)
    || type === null || !/^[!-~]+$/.test(type) || type.includes(',')
    || timestamp === null || !positiveDecimal.test(timestamp)
    || attempt === null || !positiveDecimal.test(attempt)
    || !/^sha256=[0-9a-f]{64}$/.test(signature)) {
    return null;
  }

  const signedAt = Number(timestamp);
  if (!Number.isSafeInteger(signedAt) || !Number.isSafeInteger(Number(attempt))
    || Math.abs(now - signedAt) > 300) {
    return null;
  }

  const digest = createHash('sha256').update(rawBody).digest('hex');
  const canonical = ['webhook-v2', id, type, timestamp, attempt, nonce, digest].join('\n');
  const expected = createHmac('sha256', secret).update(canonical).digest();
  const received = Buffer.from(signature.slice('sha256='.length), 'hex');
  if (!timingSafeEqual(expected, received)) {
    return null;
  }

  try {
    const event = JSON.parse(new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(rawBody));
    if (event?.id !== id || event.type !== type || event.payload_version !== 'v2'
      || typeof event.created_at !== 'string' || typeof event.request_id !== 'string'
      || typeof event.correlation_id !== 'string'
      || event.data?.resource === null || typeof event.data?.resource !== 'object') {
      return null;
    }

    const { type: resourceType, id: resourceId } = event.data.resource;
    return (resourceType === null || typeof resourceType === 'string')
      && (resourceId === null || typeof resourceId === 'string') ? event : null;
  } catch {
    return null;
  }
}
```

Save the following fixture alongside the module as `test-webhook.mjs` and run `node test-webhook.mjs`. It prints the event ID for the original bytes and `null` after a newline is added.

```javascript test-webhook.mjs theme={null}
import { verifyWebhook } from './verify-webhook.mjs';

const body = Buffer.from('{"created_at":"2023-11-14T22:13:20.000000Z","request_id":"req-example","correlation_id":"exchange-example","payload_version":"v2","data":{"resource":{"type":"order","id":"TRK218"}},"id":"dad49ff8-971d-4a6e-a39a-5a6942321efc","type":"order.created"}');
const headers = new Headers({
  'X-Webhook-Event-Id': 'dad49ff8-971d-4a6e-a39a-5a6942321efc',
  'X-Webhook-Event-Type': 'order.created',
  'X-Webhook-Timestamp': '1700000000',
  'X-Webhook-Attempt': '2',
  'X-Webhook-Nonce': '95f1cb0c-5eac-429b-94bd-18326f787d62',
  'X-Webhook-Signature-Version': 'v2',
  'X-Webhook-Signature': 'sha256=568ac2976e18921678f63cdb5618ab572acc32af2cbf076d429de94a1c0b405c',
});
const secret = 'local-webhook-fixture';
const fixtureTime = 1700000000;

console.log(verifyWebhook(body, headers, secret, fixtureTime)?.id);
console.log(verifyWebhook(Buffer.concat([body, Buffer.from('\n')]), headers, secret, fixtureTime));
```

```text theme={null}
dad49ff8-971d-4a6e-a39a-5a6942321efc
null
```

## 4. Acknowledge and process

1. Reject a failed verification without changing the resource.
2. Insert the verified event into durable storage. Give the event ID a uniqueness constraint scoped to its source and receiver. Return `2xx` after a successful durable write or completed processing. If the same verified event is already stored, return `2xx` and skip the duplicate write.
3. Route `api.test` separately from production actions. For actual events, use `data.resource.id` with the read operation for that resource, such as `GET /api/v3/private/exchange/orders/{order}`. The resource fields `type` and `id` can be `null`. A concurrent or retried notification can arrive after a newer event, so fetch the resource when you need its latest state.

A v2 notification includes `id`, `type`, `created_at`, `request_id`, `correlation_id`, `payload_version: "v2"`, and `data.resource`. `X-Request-Id` and `X-Correlation-Id` help trace the source request. Delivery retries retain the event ID and change the attempt number and signature.

### Receive and store the event in PHP

The HTTP timeout defaults to 8 seconds. The operator can set 1–60 seconds. Use a durable inbox if processing may take longer. Create this PostgreSQL table once.

```sql theme={null}
CREATE TABLE webhook_inbox (
    receiver_id text NOT NULL,
    event_id uuid NOT NULL,
    payload jsonb NOT NULL,
    received_at timestamptz NOT NULL DEFAULT now(),
    processed_at timestamptz,
    PRIMARY KEY (receiver_id, event_id)
);
```

Run this endpoint with PHP and PDO\_PGSQL. Set `WEBHOOK_SECRET` to the subscription secret, `WEBHOOK_RECEIVER_ID` to a stable local identifier for this exchange and receiver, and `WEBHOOK_PG_DSN` to a PostgreSQL PDO connection string. Supply database credentials through your service environment. This receiver accepts up to 1 MiB of raw input and returns `413` above its local limit.

```php receiver.php theme={null}
<?php

declare(strict_types=1);

$secret = getenv('WEBHOOK_SECRET');
$receiver = getenv('WEBHOOK_RECEIVER_ID');
$dsn = getenv('WEBHOOK_PG_DSN');
if (!$secret || !$receiver || !$dsn) {
    http_response_code(503);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

$maxBodyBytes = 1024 * 1024;
$raw = file_get_contents('php://input', length: $maxBodyBytes + 1);
if ($raw === false) {
    http_response_code(503);
    exit;
}
if (strlen($raw) > $maxBodyBytes) {
    http_response_code(413);
    exit;
}
$id = $_SERVER['HTTP_X_WEBHOOK_EVENT_ID'] ?? '';
$type = $_SERVER['HTTP_X_WEBHOOK_EVENT_TYPE'] ?? '';
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
$attempt = $_SERVER['HTTP_X_WEBHOOK_ATTEMPT'] ?? '';
$nonce = $_SERVER['HTTP_X_WEBHOOK_NONCE'] ?? '';
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$uuidPattern = '/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/iD';

if (($_SERVER['HTTP_X_WEBHOOK_SIGNATURE_VERSION'] ?? '') !== 'v2'
    || !preg_match($uuidPattern, $id) || !preg_match($uuidPattern, $nonce)
    || !preg_match('/^[!-~]+$/D', $type) || str_contains($type, ',')
    || !preg_match('/^[1-9][0-9]{0,14}$/D', $attempt)
    || !preg_match('/^[1-9][0-9]{0,14}$/D', $timestamp)
    || abs(time() - (int) $timestamp) > 300) {
    http_response_code(401);
    exit;
}

$canonical = implode("\n", ['webhook-v2', $id, $type, $timestamp, $attempt, $nonce, hash('sha256', $raw)]);
if (!hash_equals('sha256='.hash_hmac('sha256', $canonical, $secret), $signature)) {
    http_response_code(401);
    exit;
}

$event = json_decode($raw);
$resource = $event->data->resource ?? null;
if (($event->id ?? null) !== $id || ($event->type ?? null) !== $type
    || ($event->payload_version ?? null) !== 'v2' || !is_object($resource)
    || !is_string($event->created_at ?? null) || !is_string($event->request_id ?? null)
    || !is_string($event->correlation_id ?? null)
    || !property_exists($resource, 'type') || !property_exists($resource, 'id')
    || ($resource->type !== null && !is_string($resource->type))
    || ($resource->id !== null && !is_string($resource->id))) {
    http_response_code(400);
    exit;
}

try {
    $db = new PDO($dsn, options: [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $insert = $db->prepare('INSERT INTO webhook_inbox (receiver_id, event_id, payload)
        VALUES (?, ?, ?) ON CONFLICT (receiver_id, event_id) DO NOTHING');
    $insert->execute([$receiver, $id, $raw]);
    http_response_code(204);
} catch (PDOException) {
    http_response_code(503);
}
```

A worker reads pending rows, fetches the resource, and marks the row processed. Commit any local business update and `processed_at` in one transaction. For an external write, use a separate durable operation key. Repeated notifications for a payment must never authorize another credit.

### Receive and store the event in Node.js

Use the same inbox table. Place the receiver beside `verify-webhook.mjs`. Install the PostgreSQL client with `npm install pg`. Set `WEBHOOK_SECRET`, `WEBHOOK_RECEIVER_ID`, and the PostgreSQL client environment variables for your database. Start the handler with `node receiver.mjs` behind your HTTPS reverse proxy. This example sets a local body size limit of 1 MiB.

```javascript receiver.mjs theme={null}
import { createServer } from 'node:http';
import pg from 'pg';
import { verifyWebhook } from './verify-webhook.mjs';

const secret = process.env.WEBHOOK_SECRET;
const receiverId = process.env.WEBHOOK_RECEIVER_ID;
if (!secret || !receiverId) throw new Error('Missing webhook configuration');
const db = new pg.Pool();

createServer(async (request, response) => {
  function finish(status) {
    response.writeHead(status).end();
  }

  if (request.method !== 'POST') return finish(405);
  try {
    const chunks = [];
    let bytes = 0;
    for await (const chunk of request) {
      bytes += chunk.length;
      if (bytes > 1024 * 1024) return finish(413);
      chunks.push(chunk);
    }

    const raw = Buffer.concat(chunks);
    const headers = new Headers();
    for (let index = 0; index < request.rawHeaders.length; index += 2) {
      headers.append(request.rawHeaders[index], request.rawHeaders[index + 1]);
    }
    const event = verifyWebhook(raw, headers, secret);
    if (!event) return finish(401);

    await db.query(
      'INSERT INTO webhook_inbox (receiver_id, event_id, payload) VALUES ($1, $2, $3) '
        + 'ON CONFLICT (receiver_id, event_id) DO NOTHING',
      [receiverId, event.id, raw.toString('utf8')],
    );
    finish(204);
  } catch {
    finish(503);
  }
}).listen(Number(process.env.PORT ?? 3000), '127.0.0.1');
```

## Event types

Read the installation's catalog in `result.events` from `GET /api/v3/private/webhooks`.

| Event | Trigger | Example `data.resource` | Receiver action |
| - | - | - | - |
| `api.test` | The API sent a subscription test. | `{"type":"api_test","id":null}` | Record the test separately. |
| `order.created` | An exchange order was created. | `{"type":"order","id":"TRK218"}` | Fetch and associate the order. |
| `order.preflight` | An order preflight ran. The resource identifies the exchange route. | `{"type":"route","id":"42"}` | Associate the preflight with the exchange route. |
| `order.status_changed` | The order changed status. `data.from_status` and `data.to_status`, when present, are numbers. | `{"type":"order","id":"TRK218"}` | Refresh the stored order status. |
| `order.payment_received` | Payment receipt was confirmed. Check the resource and the payment transaction if a status was set manually. | `{"type":"order","id":"TRK218"}` | Reconcile the payment against the order. |
| `verification.identity.created` | An identity verification was created. | `{"type":"identity_verification","id":"89"}` | Record the verification ID. |
| `verification.identity.status_changed` | An identity verification changed status. | `{"type":"identity_verification","id":"89"}` | Read the current decision. |
| `verification.card.created` | A card verification was created. | `{"type":"card_verification","id":"91"}` | Record the card verification ID. |
| `verification.card.status_changed` | A card verification changed status. | `{"type":"card_verification","id":"91"}` | Read the current card verification decision. |
| `file.uploaded` | A file upload through the API completed. | `{"type":"file","id":"22222222-2222-4222-8222-222222222222"}` | Match the upload against the saved file ID. |
| `api.sandbox.simulated` | An operation ran in the API sandbox. | `{"type":"sandbox","id":"33333333-3333-4333-8333-333333333333"}` | Update the test run. |
| `review.created` | A review was created. | `{"type":"review","id":"52"}` | Refresh the list of reviews. |
| `partner.payout.paid` | A partner payout was marked as paid. | `{"type":"partner_payout","id":"73"}` | Reconcile the existing payout. |

## Change or revoke a subscription

Use `public-api:webhooks:read` for GET and `public-api:webhooks:write` for changes.

| Method and path | Use |
| - | - |
| `GET /api/v3/private/webhooks` | Read subscriptions, event types, and the account's subscription limit. |
| `GET /api/v3/private/webhooks/{webhook}` | Check settings and last delivery for one subscription. |
| `PATCH /api/v3/private/webhooks/{webhook}` | Change the name, URL, events, or `active`, `paused`, or `disabled` status. Pausing stops new deliveries for ordinary events and holds queued ones for resumption. Changing the URL retires the route for existing deliveries. Send a new test to the new URL. |
| `POST /api/v3/private/webhooks/{webhook}/rotate-secret` | Save the new `result.endpoint.secret` and install it in the receiver. |
| `DELETE /api/v3/private/webhooks/{webhook}` | Revoke the subscription and its secret. Delivery history remains through its retention window. |

Use an [idempotency key](https://exchanger-api.iexexchanger.com/en/guides/reliability/idempotency.md) for creation or rotation. Within the response retention window, a replay can recover that operation's secret. If the response can no longer be replayed, check for the existing subscription and rotate its secret if you need to recover access to delivery verification.

> [accordion] Prompt for building a receiver
>
> ```text theme={null}
> Implement an Exchanger API webhook receiver in [STACK]. Inspect the project's HTTP routing, storage and tests. Use direct HTTP and a local fixture secret.
>
> Capture the original POST bytes before parsing JSON. Verify HMAC v2 with the subscription secret and the documented test vector. Match the signed event ID and type to the body. Persist verified events in a durable inbox with a unique key for source, receiver and event ID. Return 2xx after commit. A verified duplicate should return 2xx without a second insert. Handle api.test separately. Fetch the resource for the current payment state because deliveries can arrive out of order.
>
> Test a valid delivery, a retry with the same ID and a fresh signature, a changed byte, an expired signature and a storage outage. Finish when the first two requests create one record, the other cases receive no successful acknowledgment, and all tests run without contacting an exchange. Show the changes and test results.
>
> Documentation
> https://exchanger-api.iexexchanger.com/en/guides/reliability/webhooks
> https://exchanger-api.iexexchanger.com/en/guides/reliability/webhook-deliveries
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.