# Webhooks

Signed job callbacks: verify them, retries, the delivery log and redelivery.

Pass `webhook_url` (a public `https://` address) when you start a video, audio or 3D job. When the job ends we POST the finished job to it: the same JSON as `GET /v1/jobs/{id}`, with `status` `succeeded` or `failed`. Every delivery is signed by the [Standard Webhooks](https://www.standardwebhooks.com) rules, so any of its libraries can verify it too.

## Your signing secret

`GET /v1/webhooks/secret` with any API key of your organization created in the console (not a playground key or a key of a connected app) returns `{"object": "webhook_secret", "secret": "whsec_…", "created_at", "previous_secret_expires_at"}`. The secret is made on first use and is the same for every key of the organization. Keep it like an API key: it is shown only in this answer.

`POST /v1/webhooks/secret` rotates it and returns the new one. Any API key of your organization created in the console can rotate it, and the secret is shared by the whole organization, so a rotation affects every receiver. For 24 hours after a rotation, deliveries carry two signatures (new and old), so receivers still holding the old secret keep working while you update them.

## Verify a delivery

- `webhook-id`: the delivery's id (`msg_…`). It is the same on every retry of that delivery.
- `webhook-timestamp`: when this attempt was sent, in Unix seconds.
- `webhook-signature`: one or more `v1,<signature>` values separated by spaces. Each is the base64 HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the base64-decoded part of your secret after `whsec_`.

Sign the raw body exactly as received, before parsing it. Accept the delivery when any `v1` signature matches, compare in constant time, and refuse timestamps more than 5 minutes from your clock (this stops replays).

JavaScript (Node):

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

// secret: "whsec_..." from GET /v1/webhooks/secret. headers: the request's headers (lower-case names).
// body: the raw request body as a string, exactly as received (before JSON.parse).
export function verifyWebhook(secret, headers, body, toleranceSeconds = 300) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  const signatures = headers["webhook-signature"];
  if (!id || !timestamp || !signatures) throw new Error("missing webhook headers");
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) throw new Error("timestamp too old or too new");
  const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
  const expected = Buffer.from(createHmac("sha256", key).update(`${id}.${timestamp}.${body}`).digest("base64"));
  for (const part of signatures.split(" ")) {
    const [version, signature = ""] = part.split(",");
    const given = Buffer.from(signature);
    if (version === "v1" && given.length === expected.length && timingSafeEqual(given, expected)) {
      return JSON.parse(body); // the job; skip it if you have already handled this webhook-id
    }
  }
  throw new Error("no valid signature");
}

```

Python:

```python
import base64, hashlib, hmac, json, time

# secret: "whsec_..." from GET /v1/webhooks/secret. headers: the request's headers (lower-case names).
# body: the raw request body as bytes, exactly as received (before json.loads).
def verify_webhook(secret: str, headers: dict, body: bytes, tolerance_seconds: int = 300):
    msg_id = headers["webhook-id"]
    timestamp = headers["webhook-timestamp"]
    signatures = headers["webhook-signature"]
    if abs(time.time() - int(timestamp)) > tolerance_seconds:
        raise ValueError("timestamp too old or too new")
    key = base64.b64decode(secret.removeprefix("whsec_"))
    signed = f"{msg_id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for part in signatures.split(" "):
        version, _, signature = part.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return json.loads(body)  # the job; skip it if you have already handled this webhook-id
    raise ValueError("no valid signature")

```

## Retries

Answer with any `2xx` within 10 seconds, and do slow work after answering. Anything else (another status, a timeout, a refused connection) is retried on this schedule, about 27.6 hours in all:

| Attempt | Sent after the previous one |
| --- | --- |
| 1 | at once |
| 2 | 5 seconds |
| 3 | 5 minutes |
| 4 | 30 minutes |
| 5 | 2 hours |
| 6 | 5 hours |
| 7 | 10 hours |
| 8 | 10 hours |

Answer `410 Gone` to stop the retries of a delivery. Redirects are not followed, and the address is checked again before every attempt: it must stay a public `https://` address.

## Duplicates

A delivery can arrive more than once (for example when your answer was lost). Store the `webhook-id` of each delivery you handled and skip ids you have already seen. A redelivery you ask for has a new `webhook-id`; the job's `id` in the body stays the same.

## Delivery log and redelivery

`GET /v1/jobs/{id}/webhooks` lists a job's deliveries, newest first: `id` (the `webhook-id`), `event` (`job.succeeded` or `job.failed`), `status` (`pending`, `succeeded`, `failed` when you answered `410`, `gave_up` after the last attempt), `attempts`, `response_status` and `response_body` (the first 1 KB of your last answer), `last_attempt_at`, `next_attempt_at` and `created_at`. Deliveries are kept for 30 days.

`POST /v1/jobs/{id}/webhooks/redeliver` sends the finished job again as a new delivery and returns it with `202`. It answers `409 job_not_finished` while the job runs, `400 no_webhook_url` for a job started without one, and `409 too_many_deliveries` after 10 deliveries of one job. Both routes see only jobs of the API key that started them; any other job is a `404`.

Source: https://ewest.ai/docs/webhooks
