# Webhooks

Instead of polling, give a run a `webhook_url`. When the request reaches a final status (`succeeded`, `failed` or
`canceled`), we send a signed `POST` to that URL.

```bash
curl -X POST "https://api.doitong.com/v1/run/{model_id}?webhook_url=https://example.com/hooks/doitong" \
  -H "Authorization: Bearer $DOITONG_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "..."}'
```

> [!NOTE]
> The URL must be public `https://`. Private, local and non-HTTPS addresses are refused with
> `422 invalid_webhook_url` before anything is charged.

## The event

```http Request headers
POST /hooks/doitong HTTP/1.1
Content-Type: application/json
User-Agent: Doitong-Webhooks/1
Doitong-Request-Id: req_8k2m4q7x1z9c3v5b6n0p2r4t
Doitong-Signature: t=1760961609,v1=5f1c0d6e2b…
```

```json Request body
{
  "id": "evt_8k2m4q7x1z9c3v5b6n0p2r4t_succeeded",
  "object": "event",
  "type": "request.succeeded",
  "created_at": "2026-10-20T12:00:09Z",
  "data": {
    "id": "req_8k2m4q7x1z9c3v5b6n0p2r4t",
    "object": "request",
    "status": "succeeded",
    "outputs": [ { "type": "video", "url": "https://content.doitong.com/dev-api/…/0-output.mp4" } ]
  }
}
```

- `type` is `request.succeeded`, `request.failed` or `request.canceled`.
- `data` is the full request object, exactly what `GET /requests/{id}` returns.
- `id` is stable for a request and its final status. Use it to ignore a delivery you already processed.

## Deliveries and retries

Answer with any `2xx` status within 10 seconds. Anything else (or a timeout) is retried: up to 6 attempts in total,
after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours. Do slow work after you answer, not before.

## Verify the signature

Every key has its own signing secret. Read it once from `GET https://api.doitong.com/v1/account` (`webhook_signing_secret`,
it starts with `whsec_`) and store it next to the key.

The `Doitong-Signature` header is `t=<unix time>,v1=<signature>`, where the signature is the hex
HMAC-SHA256 of `"<t>.<raw request body>"` with your secret as the key. To verify:

1. Take the raw body bytes exactly as received (before any JSON parsing).
2. Compute HMAC-SHA256 of `t + "." + body` with your secret, as lowercase hex.
3. Compare it with `v1` in constant time.
4. Reject the event when `t` is more than 5 minutes away from your clock (replay protection).

A complete receiver in Node.js (Express) and Python (Flask):

```javascript Node.js · Express
import crypto from "node:crypto";
import express from "express";

const SECRET = process.env.DOITONG_WEBHOOK_SECRET; // whsec_...
const app = express();

app.post("/hooks/doitong", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("Doitong-Signature") || "";
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  const expected = crypto.createHmac("sha256", SECRET).update(t + "." + req.body).digest("hex");
  const given = Buffer.from(parts.v1 || "", "utf8");
  const valid =
    given.length === expected.length &&
    crypto.timingSafeEqual(given, Buffer.from(expected, "utf8")) &&
    Math.abs(Date.now() / 1000 - t) < 300;
  if (!valid) return res.status(400).send("bad signature");

  const event = JSON.parse(req.body);
  if (event.type === "request.succeeded") {
    console.log(event.data.id, event.data.outputs.map((o) => o.url));
  }
  res.sendStatus(204);
});
```
```python Python · Flask
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["DOITONG_WEBHOOK_SECRET"].encode()  # whsec_...
app = Flask(__name__)


@app.post("/hooks/doitong")
def doitong_hook():
    body = request.get_data()  # raw bytes
    parts = dict(p.split("=", 1) for p in request.headers.get("Doitong-Signature", "").split(",") if "=" in p)
    t = parts.get("t", "0")
    expected = hmac.new(SECRET, t.encode() + b"." + body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, parts.get("v1", "")) or abs(time.time() - int(t)) > 300:
        abort(400)

    event = json.loads(body)
    if event["type"] == "request.succeeded":
        print(event["data"]["id"], [o["url"] for o in event["data"]["outputs"]])
    return "", 204
```

## Tips

> [!TIP]
> Webhooks are a convenience, not the source of truth: if you miss one, `GET /requests/{id}` always has the final
> state.

- Respond quickly and queue your own processing.
- The secret belongs to the API key that started the run. Keys in different services have different secrets.
