# Fulfil orders with webhooks (/docs/webhooks)

RunePay tells your server about payments, refunds, disputes and payouts by sending signed events to your webhook endpoints. Fulfil orders from the **`checkout.session.completed`** event, not from the buyer landing on your `success_url`: the buyer can close the tab before the redirect, and anyone can open the success URL.

## Create an endpoint [#create-an-endpoint]

Endpoints are per mode: a test endpoint only receives test events. Create one in the dashboard (**Developers → Webhooks**) or with the API:

```bash
curl https://runepay.co/api/v1/webhook_endpoints \
  -H "Authorization: Bearer $RUNEPAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "url": "https://merchant.example/runepay/webhooks", "enabled_events": ["checkout.session.completed", "refund.succeeded"] }'
```

- `url` must be a public HTTPS URL. Private addresses, IP literals and redirects are refused.
- `api_version` defaults to `2026-12-15`. You can also set `description` and string `metadata`.
- `enabled_events` lists [event types](/docs/webhooks/events), or `["*"]` for all of them.
- The response includes `secret` (`whsec_…`) **once**. It is never shown again, and a retry with the same `Idempotency-Key` returns `409 secret_not_replayable` with the endpoint id instead of the secret. If you lose it, [rotate](/docs/api/webhook-endpoints/rotate-webhook-endpoint-secret) to get a new one.

`DELETE /webhook_endpoints/{id}` soft-deletes an endpoint, hides it from reads and stops pending and future deliveries.

## What a delivery looks like [#what-a-delivery-looks-like]

Each event is a `POST` with a JSON body and these headers:

| Header | |
| --- | --- |
| `Content-Type` | `application/json` |
| `RunePay-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |
| `RunePay-Event-Id` | The event id (`evt_…`), unchanged on retries. |
| `RunePay-Event-Type` | The event type, for example `checkout.session.completed`. |

```json
{
  "id": "evt_01KA8E5F7G9H1J3K5M7N9P1Q3R",
  "object": "event",
  "type": "checkout.session.completed",
  "api_version": "2026-12-15",
  "livemode": false,
  "created": 1767225600,
  "data": {
    "object": {
      "id": "cs_01KA4XZY8T2R5M7P1Q4W6E8R0T",
      "object": "checkout_session",
      "livemode": false,
      "status": "complete",
      "currency": "USD",
      "description": "Pro plan, 1 month",
      "customer_email": null,
      "payment": "pay_01KA4Y0Z9V3T6N8Q2W5E7R1T3Y",
      "payment_link": null,
      "success_url": "https://merchant.example/thanks",
      "cancel_url": null,
      "metadata": {
        "order_id": "1042"
      },
      "url": "https://runepay.co/pay/cs_01KA4XZY8T2R5M7P1Q4W6E8R0T",
      "expires_at": 1767312000,
      "created": 1767225600,
      "amount_subtotal": 1999,
      "amount_tax": 0,
      "amount_total": 1999,
      "tax_behavior": "exclusive",
      "payment_status": "paid",
      "line_items": {
        "object": "list",
        "url": "/api/v1/checkout_sessions/cs_01KA4XZY8T2R5M7P1Q4W6E8R0T/line_items",
        "data": [
          {
            "id": "li_01KA4XZY8T2R5M7P1Q4W6E8R0T",
            "object": "item",
            "currency": "USD",
            "quantity": 1,
            "price_data": {
              "currency": "USD",
              "unit_amount": 1999,
              "product_data": {
                "name": "Pro plan, 1 month"
              },
              "tax_code": "saas",
              "tax_behavior": "exclusive"
            },
            "amount_subtotal": 1999,
            "amount_tax": 0,
            "amount_total": 1999
          }
        ],
        "has_more": false
      },
      "client_reference_id": "order_1042",
      "customer": null,
      "locale": "auto",
      "expired_at": null
    }
  },
  "request": null
}
```

The [event reference](/docs/webhooks/events) lists what `data` holds for each type.

The object is a snapshot taken when the event happened. `request` is the originating API request (`id` and `idempotency_key`), or null for processor, cron and dashboard events. Only `*.updated` events include `data.previous_attributes`. Verify the signature before trusting routing headers or body fields.

## Verify the signature [#verify-the-signature]

The signature is an HMAC-SHA256, keyed with your endpoint secret, over the timestamp, a period, and the **raw request body**: `"{t}.{body}"`. Compute it over the bytes you received, before parsing the JSON; re-serialising changes them.

1. Split the header on `,` and read `t` and every `v1`.
2. Reject the event if `t` is more than 5 minutes from your clock (replay protection).
3. Compute the HMAC and compare it with each `v1` in constant time. Accept if any matches: while a secret [rotation](/docs/api/webhook-endpoints/rotate-webhook-endpoint-secret) overlaps, the header carries one `v1` per active secret.

<Tabs items={["Node","PHP","Python"]}>
<Tab value="Node">
The [Node.js SDK](/docs/sdk#verify-webhooks) provides `constructEvent` for verification and parsing. It is available from source and is not published to npm yet. The manual verifier below works without the SDK.

```mjs
import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody: the request body exactly as received (a string, before JSON.parse).
// header: the RunePay-Signature header. secret: the endpoint's whsec_… secret.
export function verifyRunePaySignature(rawBody, header, secret, toleranceSeconds = 300, now = Date.now() / 1000) {
  const parts = header.split(",").map((part) => part.trim().split("="));
  const t = Number(parts.find(([key]) => key === "t")?.[1]);
  if (!Number.isInteger(t) || Math.abs(now - t) > toleranceSeconds) return false;

  const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
  // During a secret rotation the header carries one v1 per active secret.
  return parts.some(
    ([key, value]) => key === "v1" && /^[0-9a-f]{64}$/i.test(value ?? "") && timingSafeEqual(expected, Buffer.from(value, "hex")),
  );
}
```

With Express, read the raw body for this route only:

```js
app.post("/runepay/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verifyRunePaySignature(raw, req.get("RunePay-Signature") ?? "", process.env.RUNEPAY_WEBHOOK_SECRET)) {
    return res.sendStatus(400);
  }
  const event = JSON.parse(raw);
  // dedupe on event.id, queue the work, then:
  res.sendStatus(200);
});
```
</Tab>

<Tab value="PHP">
```php
<?php
// $rawBody: the request body exactly as received, e.g. file_get_contents('php://input').
// $header: $_SERVER['HTTP_RUNEPAY_SIGNATURE']. $secret: the endpoint's whsec_… secret.
function verify_runepay_signature(string $rawBody, string $header, string $secret, int $tolerance = 300, ?int $now = null): bool
{
    $t = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        [$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
        if ($key === 't' && ctype_digit($value)) {
            $t = (int) $value;
        } elseif ($key === 'v1') {
            // During a secret rotation the header carries one v1 per active secret.
            $signatures[] = $value;
        }
    }
    if ($t === null || abs(($now ?? time()) - $t) > $tolerance) {
        return false;
    }

    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}
```

```php
$raw = file_get_contents('php://input');
if (!verify_runepay_signature($raw, $_SERVER['HTTP_RUNEPAY_SIGNATURE'] ?? '', getenv('RUNEPAY_WEBHOOK_SECRET'))) {
    http_response_code(400);
    exit;
}
$event = json_decode($raw, true);
```
</Tab>

<Tab value="Python">
```py
import hashlib
import hmac
import time

# raw_body: the request body exactly as received (bytes, before json.loads).
# header: the RunePay-Signature header. secret: the endpoint's whsec_… secret.
def verify_runepay_signature(raw_body: bytes, header: str, secret: str, tolerance: int = 300, now: float | None = None) -> bool:
    t, signatures = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t" and value.isdigit():
            t = int(value)
        elif key == "v1":
            # During a secret rotation the header carries one v1 per active secret.
            signatures.append(value)
    if t is None or abs((time.time() if now is None else now) - t) > tolerance:
        return False

    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, signature) for signature in signatures)
```

```python
# Flask
@app.post("/runepay/webhooks")
def runepay_webhook():
    raw = request.get_data()
    if not verify_runepay_signature(raw, request.headers.get("RunePay-Signature", ""), os.environ["RUNEPAY_WEBHOOK_SECRET"]):
        abort(400)
    event = json.loads(raw)
    return "", 200
```
</Tab>
</Tabs>

### Test vector [#test-vector]

Check your implementation against this vector. With your clock set to `timestamp` (or the tolerance check disabled), the header must verify, and changing any byte of the body must make it fail. RunePay's test suite checks all three snippets above against it.

```json
{
  "secret": "whsec_docs_test_vector_do_not_use",
  "timestamp": 1767225600,
  "body": "{\"id\":\"evt_01KA8E5F7G9H1J3K5M7N9P1Q3R\",\"object\":\"event\",\"type\":\"checkout.session.completed\",\"api_version\":\"2026-12-15\",\"livemode\":false,\"created\":1767225600,\"data\":{\"object\":{\"id\":\"cs_01KA4XZY8T2R5M7P1Q4W6E8R0T\",\"object\":\"checkout_session\",\"livemode\":false,\"status\":\"complete\",\"amount\":1999,\"currency\":\"USD\",\"description\":\"Pro plan, 1 month\",\"customer_email\":null,\"payment\":\"pay_01KA4Y0Z9V3T6N8Q2W5E7R1T3Y\",\"payment_link\":null,\"success_url\":\"https://merchant.example/thanks\",\"cancel_url\":null,\"metadata\":{\"order_id\":\"1042\"},\"url\":\"https://runepay.co/pay/cs_01KA4XZY8T2R5M7P1Q4W6E8R0T\",\"expires_at\":1767312000,\"created\":1767225600}},\"request\":null}",
  "signature_header": "t=1767225600,v1=8c406ba8c6c6606433c80ec471a3a04e5fca2811471598dd4a32f7b4e8d97bb1"
}
```

## Handle events safely [#handle-events-safely]

- **Deduplicate on `event.id`.** Delivery is at least once: the same event can arrive more than once, including after a [replay](#replay-an-event). Record the ids you have processed and skip repeats.
- **Respond 2xx fast.** RunePay waits up to 10 seconds. Store the event, return `200`, and do slow work (emails, licence generation) in a background job. Anything other than 2xx, including a redirect, counts as a failure.
- **Don't rely on order.** Events can arrive out of order. Treat each one as a snapshot and retrieve the object (for example `GET /payments/{id}`) when you need its current state.
- **Check the mode.** `livemode` is `false` for test events.

## Retries and failures [#retries-and-failures]

A failed delivery is retried with jittered exponential backoff, starting at about a minute and capped at 4 hours between attempts, for up to 72 hours. If an endpoint keeps failing with no success for 72 hours, RunePay disables it, fails its pending deliveries and emails the account owner. Fix the endpoint, re-enable it, and replay what you missed.

`GET /webhook_endpoints/{id}/deliveries` and the endpoint's page in the dashboard show each delivery's status, attempts and last response code.

## Replay an event [#replay-an-event]

To send an event again, for example after fixing a bug in your handler:

```bash
curl https://runepay.co/api/v1/webhook_endpoints/we_01KA9F6G8H0J2K4M6N8P0Q2R4S/replay \
  -H "Authorization: Bearer $RUNEPAY_KEY" \
  -H "Content-Type: application/json" \
  -d '{ "event_id": "evt_01KA8E5F7G9H1J3K5M7N9P1Q3R" }'
```

The replay has the same event id, body and `created`; only the signature timestamp is new. `GET /events` lists the last 30 days of events; filter by `type=payment.*` or creation time. `GET /events/{id}` retrieves the original snapshot within that window. Delivery history is pruned after 30 days, while event rows remain for audit. The dashboard can replay from a delivery row too.

## Rotate the secret [#rotate-the-secret]

`POST /webhook_endpoints/{id}/rotate` returns a new secret once and keeps signing with the old one too for an overlap window (24 hours by default), so you can deploy the new secret without dropping events. After a leak, pass `{ "immediate": true }` to retire the old secret at once. `DELETE /webhook_endpoints/{id}/previous_secret` ends an overlap early.