# Webhooks

> Signed deliveries of the changes in your org, with retries, replays and the rules for reading them

Source: https://rcms-tickets-test.web.app/docs/webhooks

Nearly every state change in your org is a row of the **event log**: `order.paid`, `ticket.checked_in`, `hold.expired` and the rest. For a sale, listen to `order.paid`: `payment.succeeded` and `payment.failed` come only from a provider's own webhook, for a payment that was held or finished late. A few changes write no row, so read the thing itself if you rely on them: deleting a ticket type or an add-on, and changing a tracking or checkout link. A webhook endpoint is an https address that receives the rows of the types it asks for. The full list of types is on [the event types page](https://rcms-tickets-test.web.app/docs/events.md).

## Make an endpoint

```ts
import { signWebhook, verifyWebhook } from '@rcmstickets/sdk';

const endpoint = await tickets.webhookEndpoints.create({
  url: 'https://example.com/webhooks/rcms-tickets',
  events: ['order.paid', 'order.tickets_issued', 'hold.expired'],
});

// The signing secret is in this answer, once. Keep it in your server's environment.
console.log(endpoint.secret.startsWith('whsec_')); // true
```

- The url must be https, on the public internet. `POST /v1/webhook_endpoints/check_url` calls a url before you save it and says what it answered.
- An org keeps at most 16 endpoints per mode. An endpoint belongs to one mode and receives that mode's rows.
- Roll a secret with `POST /v1/webhook_endpoints/{id}/roll_secret`: the old one signs too until `expires_in_hours`, and each delivery carries two signatures meanwhile.

## What a delivery is

A row's `data.object.answers` never holds a date of birth: read it from the order. Other answers are there until the event's retention period ends.

A `POST` with a JSON body, which is one event log row, and three headers (the [Standard Webhooks](https://www.standardwebhooks.com/) way):

| Header | Value |
| --- | --- |
| `webhook-id` | The row's id (`log_…`). The same id on every attempt and on a replay: **deduplicate on it**. |
| `webhook-timestamp` | Seconds since the epoch when this attempt was signed. |
| `webhook-signature` | `v1,` and the base64 of an HMAC-SHA256 of `webhook-id.webhook-timestamp.body`, keyed by the secret's bytes (the base64 after `whsec_`). Two, space separated, while a secret is rolling. |

Answer with any 2xx, quickly. Do the work afterwards.

## Verify it

Verify the **raw** body, exactly as it arrived. A body that was parsed and written out again no longer matches its signature. In Express that means reading the body with `express.raw` before any JSON middleware.

```ts
// What your receiver does. Here the delivery is made by hand so this runs without a server.
const entry = (await tickets.eventLog.list({ type: 'order.paid' })).data[0]!;
const payload = JSON.stringify(entry);
const timestamp = Math.floor(Date.now() / 1000);

const headers = {
  'webhook-id': entry.id,
  'webhook-timestamp': String(timestamp),
  'webhook-signature': await signWebhook({ secret: endpoint.secret, id: entry.id, timestamp, payload }),
};

const verified = await verifyWebhook({ payload, headers, secret: endpoint.secret });
console.log(verified.type, verified.data.object.object); // order.paid order

try {
  await verifyWebhook({ payload: payload.replace('paid', 'free'), headers, secret: endpoint.secret });
} catch (error) {
  console.log((error as Error).name); // WebhookVerificationError
}
```

`verifyWebhook` rejects a timestamp more than five minutes from your clock, which stops a recorded delivery being sent again.

## Refunds and chargebacks

`order.refunded` means a refund went back, and `related.refund` names it. `order.dispute_updated` means a refund ended (often `refund.failed`) and what a lost chargeback counts on the order moved. No refund went back on that event, so never treat it as one: read the order for its status and totals. A ticket it voids has its own `ticket.voided`.

## Retries and replays

A delivery that does not get a 2xx is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours, 5 hours, 12 hours and 24 hours, then it stops and shows as failed. Every attempt is in `GET /v1/webhook_deliveries`, with the status code and the time. `POST /v1/webhook_deliveries/{id}/replay` sends a delivery again, as a new delivery with the same `webhook-id`.

## Rules for the receiver

Build these in from the start. Each one is a bug someone has already had.

1. **Tolerate fields you do not know.** The event types and the fields in a body only grow. Read what you need; do not reject a body because it has more than your type says. A parser that fails on an unknown field breaks the day a field is added.
2. **Order is not guaranteed.** Deliveries arrive in any order. One that is retrying is overtaken by later ones. A row the running version cannot read yet (during a deploy) is held, up to about two hours, while newer rows go out, and then it arrives behind them. Do not assume `order.paid` arrives before `order.tickets_issued`. Use `created_at` to decide which of two rows is newer, or read the resource itself (`GET /v1/orders/{id}`), which is always current.
3. **Deduplicate on `webhook-id`.** A delivery can arrive more than once.
4. **Treat the body as a hint.** The row shows the resource as it was after the change. For anything that matters, read the resource.
5. **A body can open a ticket, so keep it secret.** A ticket in a body carries `qr_token`, what opens the door, with its `url` and `transfer.url`; an order carries its private `url`. They are there so you can send your own emails when ours are off. Do not write a body to your logs, an error tracker or anywhere people can read it: anyone holding one can get in with that ticket or move it. Only the Wallet links stay null in a body; read the ticket for those.
6. **Answer fast.** A receiver that takes long enough to time out is retried, and may do the work twice.

To catch up after downtime, page through the event log instead of waiting for retries: `GET /v1/event_log?type=order.paid` lists rows newest first.

The log carries the same fields, so the same care applies. With a `full` key a row shows them as they were sent. With a `read` key they are `null`. The copy of a delivery in `GET /v1/webhook_deliveries` has them replaced with `[redacted]` for every reader.
