# Webhooks

A webhook POSTs to your address when a generation finishes. No need to poll `GET /v1/generations/{id}`: the result comes to you.

## Setup

Endpoints are managed only in your account: [Settings → API → Webhooks](/settings?p=api). The API cannot create them, so a leaked key cannot make a foreign address receive your results.

- Up to 5 endpoints per account, after the first payment.
- Each endpoint has its own events. The `whsec_...` secret is shown once, at creation.
- The address is `https://` on the default port, with no user or password in it, and not an IP address. Every address it resolves to must be public; this is checked at save time and on every delivery. Unitool's own addresses (unitool.ai and its subdomains, our API and servers) are refused.
- The "Test" button queues a `webhook.test` event, which goes out within a few seconds; the result shows in the endpoint's deliveries. At most one test per endpoint per 10 seconds and 50 tests per account per day, otherwise the account answers with the `too_many_tests` error.
- The account shows the last 10 deliveries of each endpoint.

## Events

| Event | When |
|---|---|
| `generation.succeeded` | The generation is ready, results in `data.outputs` |
| `generation.failed` | The generation failed, the reason in `data.error` |
| `generation.canceled` | The generation was canceled |
| `webhook.test` | A test from the account |

The body is JSON; `data` is the same generation object `GET /v1/generations/{id}` returns:

```json
{
  "type": "generation.succeeded",
  "timestamp": "2026-11-29T12:00:18.000Z",
  "data": { "id": "gen_...", "object": "generation", "status": "succeeded", "outputs": [ { "url": "https://...", "expires_at": "..." } ], "metadata": { "order_id": "A-1009" } }
}
```

Match events to your records by `data.id` or by the `data.metadata` you sent at creation.

If a `generation.failed` event has `error.refund: "pending"`, the tokens were charged: the model delivered the result but it could not be saved. Support decides on the refund, and no new webhook is sent for it. Read the current state from `GET /v1/generations/{id}`: `cost.refunded_tokens` and `error.refund`.

## Headers and signature

Signatures follow [Standard Webhooks](https://www.standardwebhooks.com/):

| Header | Meaning |
|---|---|
| `webhook-id` | Message id `msg_...`, the same on every retry. Use it to drop duplicates |
| `webhook-timestamp` | Send time, Unix seconds |
| `webhook-signature` | `v1,<base64 HMAC-SHA256>`, sometimes two values separated by a space (secret rotation) |

The signed string is `{webhook-id}.{webhook-timestamp}.{body}`, the key is the base64-decoded part of the secret after `whsec_`. Verify against the **raw body**, before parsing JSON, and reject timestamps older than 5 minutes.

The easiest way is the official `standardwebhooks` package (Node, Python, Go and more):

```js
import { Webhook } from "standardwebhooks";

const wh = new Webhook(process.env.UNITOOL_WEBHOOK_SECRET); // whsec_...
app.post("/unitool", express.raw({ type: "application/json" }), (req, res) => {
  const event = wh.verify(req.body, req.headers); // throws on a wrong signature or timestamp
  res.sendStatus(204);
  handle(event); // heavy work after the answer
});
```

```python
from standardwebhooks.webhooks import Webhook

wh = Webhook(os.environ["UNITOOL_WEBHOOK_SECRET"])

@app.post("/unitool")
def unitool(request):
    event = wh.verify(request.body, dict(request.headers))  # raw bytes, not parsed JSON
    queue.put(event)
    return "", 204
```

Without the package:

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

function verify(rawBody, headers, secret) {
  const id = headers["webhook-id"], ts = headers["webhook-timestamp"];
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const key = Buffer.from(secret.slice("whsec_".length), "base64");
  const expected = createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest();
  return headers["webhook-signature"].split(" ").some((part) => {
    const given = Buffer.from(part.split(",")[1] ?? "", "base64");
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
}
```

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

def verify(raw_body: bytes, headers, secret: str) -> bool:
    msg_id, ts = headers["webhook-id"], headers["webhook-timestamp"]
    if abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(key, f"{msg_id}.{ts}.".encode() + raw_body, hashlib.sha256).digest()
    return any(hmac.compare_digest(base64.b64decode(part.split(",", 1)[1]), expected)
               for part in headers["webhook-signature"].split(" ") if "," in part)
```

## Delivery

- Success is a 2xx answer within 10 seconds. Answer right away and do the work in the background.
- Redirects are not followed: a 3xx counts as a failure.
- Retries after a failure: in 5 s, 30 s, 2 min, 10 min, 30 min, 1 h, 2 h, 4 h, 6 h, 8 h, 12 h, 16 h, 20 h, 24 h, 15 attempts in total, about 4 days. A `Retry-After` in your answer can only push a retry later.
- Delivery is at least once: one event can arrive twice, drop repeats by `webhook-id`. Order is not guaranteed: `generation.succeeded` can arrive before you have processed the creation.
- A `410 Gone` answer disables the endpoint at once. An endpoint that has accepted nothing through 3 days of failures is disabled too. You get a notification in your account and can enable the endpoint there again.
- The test event is one attempt and does not count towards failures.
- File links in `data.outputs` are valid for one hour from the event. Later, read `GET /v1/generations/{id}` for fresh ones.

## Secret rotation

"Rotate secret" in your account shows a new secret once. For the next 24 hours messages are signed with both secrets: `webhook-signature` has two values. Update the secret on your side within that time; verification passes when any signature matches.

## Instead of polling

Polling `GET /v1/generations/{id}` keeps working: a webhook can be late or lost if your server was down for more than 4 days. For important orders, poll the generations whose event has not arrived. See [Media generations](/developers/generations).
