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

# Webhooks

> Get notified when a chapter changes status, and verify every delivery.

Instead of polling, register an HTTPS endpoint and Relettr will `POST` events to it.

## Register an endpoint

```bash theme={null}
curl https://api.relettr.com/v1/webhook_endpoints \
  -H "Authorization: Bearer $RELETTR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://you.example/hooks/ct",
       "events": ["chapter.ready", "chapter.needs_review", "chapter.succeeded", "chapter.failed"]}'
```

The response includes the endpoint's signing secret (`whsec_…`). **It is shown only once**; store it securely.

* URLs must be `https` on port 443 or 8443. Redirects are not followed.
* Live and test endpoints are separate. An endpoint registered with a test key gets only test events.
* If you leave out `events`, the endpoint gets every type except `chapter.step_completed`, which is opt-in.
* Send a signed `ping` with `POST /v1/webhook_endpoints/{id}/test`.

## Event types

| Type | When |
| - | - |
| `chapter.ready` | Validated and quoted (useful without `auto_start`) |
| `chapter.queued` | Started; credits held |
| `chapter.processing` | The GPU picked it up |
| `chapter.step_completed` | Each of `read`, `translate`, `render`, `stitch`. Opt-in. |
| `chapter.needs_review` | Finished with zones to review; exports locked |
| `chapter.succeeded` | Results downloadable |
| `chapter.failed` | `error` set; refund done |
| `chapter.canceled` | Canceled by you or by a GPU timeout |
| `chapter.expired` | Never completed or started in time |
| `chapter.deleted` | Deleted |
| `balance.low` | Available credits fell below your threshold |
| `api_key.spend_limit_reached` | A key hit its monthly limit |
| `ping` | Sent by the test endpoint |

New event types may be added; ignore types you don't handle.

## Payload

Events are deliberately thin. `data.object` is a snapshot of the chapter's status, progress, quote, credits, warnings, review and your `metadata`. It **never contains translated text or image URLs**: fetch `/result` and `/regions` for those.

```http theme={null}
POST /hooks/ct HTTP/1.1
webhook-id: evt_5LwQ2rS3tU4vW5xY6zA7bC
webhook-timestamp: 1795615020
webhook-signature: v1,K5o0Zt3qYvRZ1pAaDq9Sx0tJ6Wf2nYcV7bA4lE8hG1M=
Content-Type: application/json

{"id": "evt_5LwQ2rS3tU4vW5xY6zA7bC", "object": "event", "type": "chapter.needs_review",
 "created": 1795615020, "livemode": true, "api_version": "v1",
 "data": {"object": {"id": "ch_7Kq2mXaB3cD4eF5gH6iJ7k", "status": "needs_review",
   "review": {"open": 1, "accepted": 0, "zones": [{"id": "p11r004", "page": 11, "box": [40, 1210, 610, 1490], "reason": "mask_failed"}]},
   "credits": {"held": 0, "charged": 462, "refunded": 0},
   "metadata": {"source_ref": "tower-42"}}}}
```

## Verify the signature

Deliveries are signed with the [Standard Webhooks](https://www.standardwebhooks.com/) scheme:

* `webhook-id`: the event id
* `webhook-timestamp`: Unix seconds
* `webhook-signature`: `v1,<base64 HMAC-SHA256>` of `"{webhook-id}.{webhook-timestamp}.{raw body}"`, keyed with the base64-decoded part of your secret after `whsec_`. While a secret is being rotated there are several space-separated signatures; accept the delivery if any one matches.

Always verify against the **raw request body**, before parsing JSON, and reject deliveries whose timestamp is more than 5 minutes from your clock.

```python Python theme={null}
import base64, hashlib, hmac, time

TOLERANCE_S = 5 * 60

def verify(secret: str, headers: dict, body: bytes) -> bool:
    msg_id = headers["webhook-id"]
    ts = headers["webhook-timestamp"]
    if abs(time.time() - int(ts)) > TOLERANCE_S:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{ts}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for sig in headers["webhook-signature"].split(" "):
        version, _, value = sig.partition(",")
        if version == "v1" and hmac.compare_digest(value, expected):
            return True
    return False
```

```javascript Node.js theme={null}
import crypto from "node:crypto";

const TOLERANCE_S = 5 * 60;

export function verify(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const ts = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(ts)) > TOLERANCE_S) return false;
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = crypto
    .createHmac("sha256", key)
    .update(`${id}.${ts}.`)
    .update(rawBody)
    .digest("base64");
  return headers["webhook-signature"].split(" ").some((sig) => {
    const [version, value] = sig.split(",");
    return (
      version === "v1" &&
      value.length === expected.length &&
      crypto.timingSafeEqual(Buffer.from(value), Buffer.from(expected))
    );
  });
}
```

The official `standardwebhooks` libraries work as they are:

```python theme={null}
from standardwebhooks.webhooks import Webhook

wh = Webhook(secret)          # "whsec_..."
event = wh.verify(raw_body, request.headers)   # raises on a bad signature
```

## Delivery and retries

* Respond with any `2xx` within **10 seconds**. Do slow work after responding.
* Anything else (non-2xx, redirects, timeouts, TLS errors) is retried with exponential backoff and jitter for **up to 3 days**: roughly 1 min, 5 min, 30 min, 2 h, 5 h, then every 10 h.
* After 3 days of consecutive failures the endpoint is disabled and you're emailed. Re-enable it with `PATCH /v1/webhook_endpoints/{id}` (`"enabled": true`).
* Delivery is **at least once** and **unordered**. Deduplicate on `webhook-id`, and use the chapter's `status` in the payload (or a fresh `GET`) rather than the order events arrive in.

## Catching up

Missed some deliveries? `GET /v1/events` lists recent events, newest first, filterable by `type` and `chapter_id`. Page through it with the usual [cursor](https://docs.relettr.com/pagination.md).

## Rotating the secret

`POST /v1/webhook_endpoints/{id}/rotate_secret` returns a new secret (shown once). The old secret keeps working for 24 hours, and deliveries during that time carry one signature per active secret, so you can deploy the new secret without dropping events.


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