# Webhooks

A webhook is how your server learns that something happened: an order was paid, a refund issued, a subscription renewed or fell past due. Regoria sends a signed `POST` to each endpoint you registered for that event.

## Endpoints

Register up to **5 endpoints** per merchant account, each with an `https` URL on a public host and the events it wants. The dashboard (**Developers → Webhooks**) or the API:

```bash
curl -X POST https://api.sandbox.staging.regoria.com/v1/webhook-endpoints \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://shop.example.com/webhooks", "events": ["order.paid", "refund.issued", "subscription.past_due"], "description": "Production server"}'
```

The answer carries `secret` (`whsec_…`) **once**. Store it beside the endpoint; it signs every delivery. An endpoint belongs to the key's store, or to the `store_id` you pass; an endpoint without a store receives the events of every store.

## The delivery

```http
POST /webhooks HTTP/1.1
Content-Type: application/json
X-Webhook-Signature: t=1761055500,v1=5d41402abc4b2a76b9719d911017c592…
X-Webhook-Event: order.paid
X-Webhook-Delivery: evt_01HZX5Y3V8N2K7QJ4R9T6B3M1C

{"id": "evt_01HZX5Y3V8N2K7QJ4R9T6B3M1C", "type": "order.paid", "version": 1, "occurred_at": "2026-10-21T14:05:00.000Z", "merchant_id": "mer_…", "data": {"order_id": "ord_…", "session_id": "cks_…", "customer_id": "cus_…", "subscription_id": null, "charge_id": "chg_…", "lines": [{"price_id": "prc_…", "product_id": "prd_…", "quantity": 1}], …}}
```

| Header | Meaning |
|---|---|
| `X-Webhook-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` of `"<t>.<raw body>"` with your endpoint secret |
| `X-Webhook-Event` | the event type, the same as `type` in the body |
| `X-Webhook-Delivery` | the event id, **the same across every retry and replay** of that event |

The body is the envelope: `id`, `type`, `version` (the payload version), `occurred_at`, `merchant_id` and `data`, the event payload. Ids in `data` are named as the API names them: `order_id`, `customer_id`, `subscription_id`, and a list of ids such as `acceptance_ids`, at any depth; `metadata` is yours and arrives as you set it. Each event's `data` is documented in the [event catalogue](http://docs.staging.regoria.com/events) with a real example.

## Verifying

Recompute the signature over the **raw** request body (not a re-serialised JSON), compare in constant time, and reject a timestamp more than **300 seconds** from now. Then deduplicate on `X-Webhook-Delivery`: a retry or a replay carries the same id, so a handler that already processed it answers `200` and does nothing.

TypeScript (Node 20+, no dependencies; the SDK's `verifySignature` does the same):

```typescript
import { createHmac, timingSafeEqual } from 'node:crypto';

export function verify(rawBody: string, header: string, secret: string, toleranceSeconds = 300): boolean {
    const parts = Object.fromEntries(header.split(',').map((p) => p.split('=', 2) as [string, string]));
    const t = Number(parts.t);
    if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
    const expected = createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
    const given = Buffer.from(parts.v1 ?? '', 'hex');
    return given.length === 32 && timingSafeEqual(given, Buffer.from(expected, 'hex'));
}
```

PHP 8 (the SDK's `Webhooks::verify()` does the same):

```php
function verify(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
    parse_str(str_replace(',', '&', $header), $parts);
    $t = (int) ($parts['t'] ?? 0);
    if ($t === 0 || abs(time() - $t) > $tolerance) {
        return false;
    }
    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);

    return hash_equals($expected, (string) ($parts['v1'] ?? ''));
}
```

Answer `2xx` only after you have **durably recorded** the event (a queue, a database row). Do the work after the acknowledgement; a handler that fulfils an order inline and times out gets the event again.

## Retries and backoff

Your endpoint has **10 seconds** to answer `2xx`. Anything else (a `3xx`, `4xx`, `5xx`, a timeout) is a failed attempt. Retries double from **10 seconds** up to **1 hour** apart and continue for **72 hours** after the first attempt; after that the delivery is `dead`. An endpoint is **never disabled automatically**: when every delivery has failed for an hour, the merchant's users are told once (dashboard and email) and the endpoint shows `failing_since`, `last_http_status` and `last_excerpt`; the next successful delivery ends the episode and you are told it recovered.

Dead deliveries stay replayable. `POST /v1/webhook-endpoints/{endpoint}/deliveries/{delivery}/replay` re-sends one; `POST /v1/webhook-endpoints/{endpoint}/deliveries/replay` with `from`, `to` and optional `event_types` re-queues every dead or failed delivery of that window, oldest first, up to 10,000 per call (`truncated: true` means there were more). A replay carries the original `X-Webhook-Delivery` id, so your deduplication still applies.

A redirect is a failure: the endpoint URL must answer directly.

## Ordering

Deliveries are not ordered. A `subscription.renewed` can arrive before the `order.paid` of the same renewal. Treat each event as a fact with a timestamp (`occurred_at`) and read the current record with the API when the order matters.

## The delivery log, replay and ping

- `GET /v1/webhook-endpoints/{endpoint}/deliveries` lists the attempts with their status, HTTP status and the response excerpt.
- `POST /v1/webhook-endpoints/{endpoint}/deliveries/{delivery}/replay` sends a delivery again, with the same `X-Webhook-Delivery`.
- `POST /v1/webhook-endpoints/{endpoint}/ping` sends a `ping` event to check your wiring.
- `PATCH /v1/webhook-endpoints/{endpoint}` changes the events, description or URL; `DELETE` removes the endpoint.

## Events

| Event | Sent when |
|---|---|
| `order.paid` | an order was paid; fulfil it |
| `order.in_review`, `order.review_closed` | an order was held for review, and the review closed |
| `order.access_revoked` | access to a paid order was revoked after a refund or dispute |
| `refund.issued` | a refund went out |
| `dispute.opened`, `dispute.closed` | a chargeback opened, and closed |
| `charge.declined` | a card payment was declined |
| `subscription.started`, `subscription.renewed` | the first and each later paid period |
| `subscription.past_due` | a renewal failed; dunning runs |
| `subscription.pause_scheduled` | a pause was scheduled for the end of the current period; it sends `pause_at` and `scheduled_by` (`buyer` from the customer portal, `merchant` from you). A second pause while one is scheduled sends nothing |
| `subscription.pause_cancelled` | a scheduled pause was cleared before it took effect; the subscription keeps renewing and nothing is charged now |
| `subscription.paused`, `subscription.cancelled` | the subscription paused (when the scheduled pause takes effect) or ended |
| `subscription.plan_change_scheduled`, `subscription.plan_changed` | a plan change was confirmed for the next period, and took effect. Both name prices: `old_price_id` and `new_price_id`, and the subscription's `price_id`; `plan_changed` also sends `cause` (`plan_change` for a buyer-confirmed change, `price_change` when a successor price moved the subscription) |
| `subscription.payment_method_changed` | the card a subscription renews on changed |
| `subscription.resumed` | a paused subscription was resumed and paid; it comes with `subscription.renewed` for the paid period |
| `subscription.trial_ending` | a trial ends within your trial-ending lead days (7 to 21, default 8); sent once, when the buyer's reminder email goes out |
| `subscription.updated` | the subscription changed: past due, paused, resumed, canceled or cancel scheduled for the period end, plan or price changed or scheduled, card changed, or a renewal ended a past due. It carries the whole subscription, not the changed fields, and comes beside the specific event; a paid resume sends exactly one |
| `payment_method.created`, `payment_method.updated` | a card was saved or updated |
| `payout.sent` | a payout left for your bank |
| `checkout.abandoned` | a checkout session expired unpaid |
| `checkout.completed` | a checkout session was paid; it names the session, the order, the subscription it starts (`null` without a recurring price) and the customer, and comes before `subscription.started` |

Each has a page with its payload fields and an example: [event catalogue](http://docs.staging.regoria.com/events), also as [JSON Schema](http://docs.staging.regoria.com/downloads/events.schema.json).
