# Webhook

不使用輪詢，而是為執行作業提供 `webhook_url`。當請求達到最終狀態（`succeeded`、`failed` 或
`canceled`）時，我們會向該 URL 傳送經簽署的 `POST`。

```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]
> URL 必須是公開的 `https://`。私人、區域及非 HTTPS 位址會在任何費用產生前遭拒，並回傳
> `422 invalid_webhook_url`。

## 事件

```http 請求標頭
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 請求本文
{
  "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` 為 `request.succeeded`、`request.failed` 或 `request.canceled`。
- `data` 是完整的請求物件，內容與 `GET /requests/{id}` 回傳的完全相同。
- `id` 對同一個請求及其最終狀態保持不變。請使用它忽略已處理過的傳送事件。

## 傳送與重試

請在 10 秒內以任意 `2xx` 狀態回應。其他任何情況（或逾時）都會重試：總計最多 6 次，
分別在 30 秒、2 分鐘、10 分鐘、1 小時及 6 小時後重試。請在回應後再執行耗時工作，不要之前就執行。

## 驗證簽章

每個金鑰都有自己的簽署密鑰。透過 `GET https://api.doitong.com/v1/account`（`webhook_signing_secret`）讀取一次
（其開頭為 `whsec_`），並將其與金鑰一同儲存。

`Doitong-Signature` 標頭格式為 `t=<unix time>,v1=<signature>`，其中簽章是以密鑰計算
`"<t>.<raw request body>"` 的十六進位 HMAC-SHA256。驗證方式如下：

1. 完整取得實際收到的本文原始位元組（在任何 JSON 剖析之前）。
2. 使用密鑰計算 `t + "." + body` 的 HMAC-SHA256，並輸出小寫十六進位格式。
3. 以固定時間比較方式與其中的 `v1` 比對。
4. 當 `t` 與你的時鐘相差超過 5 分鐘時拒絕事件（防止重放）。

以下是以 Node.js（Express）及 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
```

## 提示

> [!TIP]
> Webhook 是便利功能，不是真實來源：如果遺漏一個事件，`GET /requests/{id}` 仍一律會提供最終
> 狀態。

- 快速回應，並將自己的處理工作加入佇列。
- 密鑰隸屬於啟動執行作業的 API 金鑰。不同服務中的金鑰具有不同的密鑰。
