# Webhook

> Máy chủ của bạn sẽ nhận tác vụ đã hoàn tất qua Webhook: truyền webhook_url khi gửi tác vụ, nhận một yêu cầu POST và phản hồi 2xx. Chữ ký tuân theo Standard Webhooks.

<a id="setup"></a>

## Thiết lập trong ba bước
> **URL Webhook được đặt trong yêu cầu, không phải trong bảng điều khiển**
>
> Bạn đặt địa chỉ cho từng tác vụ, dưới dạng `webhook_url` trong phần thân của `POST /v1/tasks`. Bảng điều khiển không có chỗ để thiết lập URL Webhook: [Console → API → Webhook](https://kerox.ai/vi/console/webhooks) chỉ lưu khóa bí mật dùng để ký và các lượt gửi gần đây.

<a id="url"></a>

### 1. Lấy một URL HTTPS công khai
Kerox chỉ gửi đến các địa chỉ `https://` truy cập được từ internet (không phải `localhost` hay IP riêng). Trong môi trường vận hành thực tế, đó là một đường dẫn trên máy chủ của bạn, chẳng hạn `https://your-app.example.com/webhooks/kerox`. Để thử từ máy tính của bạn, hãy dùng một công cụ kiểm tra tạm thời như [webhook.site](https://webhook.site) để xem nội dung nhận được, hoặc một đường hầm (Cloudflare Tunnel, ngrok) trỏ tới bộ nhận ở bước 3.

<a id="submit"></a>

### 2. Truyền `webhook_url` khi gửi yêu cầu
Trước khi gửi yêu cầu, hãy đặt `KEROX_WEBHOOK_URL` bằng URL HTTPS công khai của bộ nhận ở bước 1 (ví dụ chạy trên shell cũng cần cài jq). Lưu lại ID tác vụ được trả về. Nếu callback đến muộn, hãy đọc `GET /v1/tasks/{id}` bằng ID đó.


```bash
API_ORIGIN=${KEROX_API_ORIGIN:-https://api.kerox.ai}
set -euo pipefail
case "${KEROX_WEBHOOK_URL:-}" in
  https://?*) ;;
  *) echo "Set KEROX_WEBHOOK_URL to your public HTTPS receiver" >&2; exit 1 ;;
esac
curl -fsS -X POST "$API_ORIGIN/v1/tasks" \
  -H "Authorization: Bearer $KEROX_API_KEY" \
  -H "Content-Type: application/json" \
  -d "$(jq -n --arg url "$KEROX_WEBHOOK_URL" '{
    "model": "bytedance/seedream-5.5",
    "input": {
      "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
      "resolution": "2K"
    },
    "webhook_url": $url,
    "metadata": { "order_id": "A1001" }
  }')"
```
```python
import os
import requests

api = os.environ.get("KEROX_API_ORIGIN", "https://api.kerox.ai")

url = os.environ.get("KEROX_WEBHOOK_URL", "")
if not url.startswith("https://") or not url[8:]:
    raise SystemExit("Set KEROX_WEBHOOK_URL to your public HTTPS receiver")
resp = requests.post(
    f"{api}/v1/tasks",
    headers={
        "Authorization": f"Bearer {os.environ['KEROX_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "bytedance/seedream-5.5",
        "input": {
            "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
            "resolution": "2K",
        },
        "webhook_url": url,
        "metadata": {"order_id": "A1001"},
    },
    timeout=60,
)
resp.raise_for_status()
print(resp.json()["id"])
```
```javascript
const api = process.env.KEROX_API_ORIGIN || 'https://api.kerox.ai';
const url = process.env.KEROX_WEBHOOK_URL;
if (!url || new URL(url).protocol !== 'https:') {
  throw new Error('Set KEROX_WEBHOOK_URL to your public HTTPS receiver');
}
const res = await fetch(`${api}/v1/tasks`, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.KEROX_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'bytedance/seedream-5.5',
    input: {
      prompt: 'editorial portrait of a ceramicist in morning sunlight, 35mm film',
      resolution: '2K',
    },
    webhook_url: url,
    metadata: { order_id: 'A1001' },
  }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}: ${await res.text()}`);
const task = await res.json();
console.log(task.id);
```


<a id="receive"></a>

### 3. Nhận và phản hồi 2xx
Khi tác vụ kết thúc ở trạng thái `succeeded` hoặc `failed`, Kerox gửi một yêu cầu `POST` đến URL với `Content-Type: application/json`. Endpoint của bạn:

1. đọc phần thân yêu cầu thô;
2. xác minh chữ ký (tùy chọn, [xem bên dưới](#verification));
3. kiểm tra đó là một tác vụ đã hoàn tất (`status` là `succeeded` kèm `outputs`, hoặc `failed` kèm `error`) và phản hồi `400` cho mọi trường hợp khác, để một yêu cầu sai định dạng không làm endpoint gặp lỗi;
4. bỏ qua `webhook-id` đã được xử lý trước đó (lượt thử lại mang cùng giá trị này);
5. phản hồi bất kỳ `2xx` nào trong vòng 10 giây, rồi mới thực hiện các xử lý tốn thời gian (như tải tệp xuống).

Mọi phản hồi khác, hoặc không có phản hồi trong 10 giây, đều bị coi là thất bại và sẽ được thử lại ([Thử lại](#retries)). Một bộ nhận tối giản, lắng nghe trên `PORT` (mặc định là 8787) tại `/webhooks/kerox`:


```javascript
// npm install standardwebhooks
import http from 'node:http';
import { Webhook } from 'standardwebhooks';

// Optional: verify signatures with the secret from Console → API → Webhook.
const secret = process.env.KEROX_WEBHOOK_SECRET;
const wh = secret ? new Webhook(secret) : null;
const handled = new Set(); // use your database in production

const server = http.createServer(async (req, res) => {
  if (req.method !== 'POST' || req.url !== '/webhooks/kerox') {
    res.writeHead(404).end();
    return;
  }
  // 1. The raw body, exactly as received.
  const chunks = [];
  for await (const chunk of req) chunks.push(chunk);
  const rawBody = Buffer.concat(chunks).toString('utf8');

  // 2. Verify the signature (optional).
  let task;
  try {
    task = wh ? wh.verify(rawBody, req.headers) : JSON.parse(rawBody);
  } catch {
    res.writeHead(400).end();
    return;
  }

  // 3. Only a finished task with a delivery ID: anything else gets 400.
  const id = req.headers['webhook-id'];
  const finished =
    (task?.status === 'succeeded' && Array.isArray(task.outputs)) ||
    (task?.status === 'failed' && typeof task.error?.code === 'string');
  if (!id || !finished) {
    res.writeHead(400).end();
    return;
  }

  // 4. A retry has the same webhook-id: handle each one once.
  if (!handled.has(id)) {
    if (task.status === 'succeeded') {
      console.log(task.id, 'succeeded', task.outputs[0]?.url);
    } else {
      console.log(task.id, 'failed', task.error.code);
    }
    handled.add(id);
  }

  // 5. Answer 2xx within 10 seconds.
  res.writeHead(200).end();
});

server.listen(Number(process.env.PORT ?? 8787));
```
```python
# pip install standardwebhooks
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from standardwebhooks.webhooks import Webhook

# Optional: verify signatures with the secret from Console → API → Webhook.
secret = os.environ.get("KEROX_WEBHOOK_SECRET")
wh = Webhook(secret) if secret else None
handled = set()  # use your database in production


class KeroxWebhook(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/webhooks/kerox":
            self.send_response(404)
            self.end_headers()
            return
        # 1. The raw body, exactly as received.
        raw_body = self.rfile.read(int(self.headers.get("Content-Length", 0)))

        # 2. Verify the signature (optional).
        try:
            task = wh.verify(raw_body, dict(self.headers)) if wh else json.loads(raw_body)
        except Exception:
            self.send_response(400)
            self.end_headers()
            return

        # 3. Only a finished task with a delivery ID: anything else gets 400.
        msg_id = self.headers.get("webhook-id")
        status = task.get("status") if isinstance(task, dict) else None
        outputs = task.get("outputs") if status == "succeeded" else None
        finished = (
            isinstance(outputs, list) and all(isinstance(item, dict) for item in outputs)
        ) or (status == "failed" and isinstance(task.get("error"), dict))
        if not (msg_id and finished):
            self.send_response(400)
            self.end_headers()
            return

        # 4. A retry has the same webhook-id: handle each one once.
        if msg_id not in handled:
            if status == "succeeded":
                urls = [item.get("url") for item in task["outputs"]]
                print(task.get("id"), "succeeded", urls, flush=True)
            else:
                print(task.get("id"), "failed", task["error"].get("code"), flush=True)
            handled.add(msg_id)

        # 5. Answer 2xx within 10 seconds.
        self.send_response(200)
        self.end_headers()


HTTPServer(("", int(os.environ.get("PORT", "8787"))), KeroxWebhook).serve_forever()
```


<a id="events"></a>

## Những gì chúng tôi gửi
Phần thân chính là đối tượng tác vụ, giống hệt những gì `GET /v1/tasks/{id}` trả về ([các trường](https://kerox.ai/vi/docs/tasks.md#submit-response)). Phân biệt thành công với thất bại qua `status`: khi thành công, các tệp nằm trong `outputs`; khi thất bại, lý do nằm trong `error` và khoản tạm giữ được hoàn lại (`cost.status: "refunded"`). Kerox chỉ gửi thông báo khi tác vụ đạt một trong hai trạng thái cuối, và chỉ gửi một lần; tác vụ được gửi mà không có `webhook_url` sẽ không bao giờ nhận được thông báo.


```json
{
  "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "succeeded",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [
    {
      "type": "image",
      "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
      "content_type": "image/png",
      "width": 2048,
      "height": 2048
    }
  ],
  "outputs_deleted": false,
  "error": null,
  "cost": { "amount": "0.0280", "currency": "USD", "status": "settled" },
  "metadata": { "order_id": "A1001" },
  "warnings": [],
  "created_at": "2026-11-20T08:01:02Z",
  "started_at": "2026-11-20T08:01:02Z",
  "completed_at": "2026-11-20T08:01:10Z",
  "expires_at": "2026-11-27T08:01:10Z"
}
```
```json
{
  "id": "task_01JD8XC7M2N4P6Q8R0S2T4V6W8",
  "object": "task",
  "model": "bytedance/seedream-5.5",
  "status": "failed",
  "source": "api",
  "format": "unified",
  "input": {
    "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
    "size": "2K"
  },
  "outputs": [],
  "outputs_deleted": false,
  "error": {
    "code": "content_violation",
    "message": "The prompt, an input file or the result did not pass content moderation. Change the content and try again."
  },
  "cost": { "amount": "0.0000", "currency": "USD", "status": "refunded" },
  "metadata": { "order_id": "A1001" },
  "warnings": [],
  "created_at": "2026-11-20T08:02:15Z",
  "started_at": "2026-11-20T08:02:15Z",
  "completed_at": "2026-11-20T08:02:19Z",
  "expires_at": null
}
```


Mỗi lượt gửi cũng kèm theo các header `webhook-id`, `webhook-timestamp` và `webhook-signature`, được mô tả bên dưới.

<a id="verification"></a>

## Xác minh chữ ký (Standard Webhooks)
Mỗi lượt gửi đều được ký theo đặc tả [Standard Webhooks](https://www.standardwebhooks.com/) và kèm theo ba header. Việc xác minh chữ ký là tùy chọn nhưng nên thực hiện, vì đây là cách xác nhận lượt gửi thực sự đến từ Kerox.

| Header | Giá trị |
| --- | --- |
| `webhook-id` | ID duy nhất của lượt gửi (`msg_...`), không thay đổi giữa các lần thử lại — dùng ID này để tránh xử lý lại cùng một lượt gửi |
| `webhook-timestamp` | Dấu thời gian Unix (tính bằng giây) tại thời điểm tạo chữ ký |
| `webhook-signature` | Một hoặc nhiều chữ ký `v1,<base64>`, phân tách bằng dấu cách (trong 24 giờ chuyển tiếp khi thay khóa, mỗi lượt gửi sẽ có hai chữ ký) |

Chuỗi được ký là `{webhook-id}.{webhook-timestamp}.{raw_body}`. Bỏ tiền tố `whsec_` khỏi khóa bí mật ký (hiển thị trong [Console → API → Webhook](https://kerox.ai/vi/console/webhooks)), giải mã base64 phần còn lại, rồi dùng các byte đã giải mã để ký chuỗi bằng **HMAC-SHA256**.

> **Xác minh phần thân yêu cầu thô**
>
> Tính HMAC trên chính xác các byte UTF-8 nhận được trên đường truyền, trước khi phân tích cú pháp hoặc tuần tự hóa lại JSON. Từ chối các dấu thời gian lệch quá 5 phút so với thời điểm hiện tại để chống tấn công phát lại.

<a id="sdk-verify"></a>

### Xác minh bằng Standard Webhooks SDK
```javascript
import { Webhook } from 'standardwebhooks';

const wh = new Webhook(process.env.KEROX_WEBHOOK_SECRET);

export async function handleKeroxWebhook(rawBody, headers) {
  // Throws if the signature is invalid or the timestamp is outside the 5-minute window.
  const task = wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
  console.log(task.id, task.status);
}
```
```python
import os
from standardwebhooks.webhooks import Webhook

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

def handle_kerox_webhook(raw_body: bytes, headers: dict[str, str]):
    task = wh.verify(raw_body, headers)
    print(task["id"], task["status"])
```


<a id="manual-verify"></a>

### Xác minh thủ công bằng các hàm mã hóa tích hợp sẵn
```javascript
import crypto from 'node:crypto';

export function verifyKeroxSignature(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatureHeader = headers['webhook-signature'];
  if (!id || !timestamp || !signatureHeader) {
    throw new Error('Missing webhook signature headers');
  }

  const ageSeconds = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
  if (!Number.isFinite(ageSeconds) || ageSeconds > 300) {
    throw new Error('Webhook timestamp outside tolerance');
  }

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.${rawBody}`)
    .digest();

  const valid = signatureHeader.split(' ').some((entry) => {
    const [version, sig] = entry.split(',');
    if (version !== 'v1' || !sig) return false;
    const actual = Buffer.from(sig, 'base64');
    return actual.length === expected.length && crypto.timingSafeEqual(actual, expected);
  });

  if (!valid) throw new Error('Invalid webhook signature');
  return JSON.parse(rawBody);
}
```
```python
import base64
import hashlib
import hmac
import json
import time

def verify_kerox_signature(raw_body: str, headers: dict[str, str], secret: str):
    msg_id = headers.get("webhook-id", "")
    timestamp = headers.get("webhook-timestamp", "")
    sig_header = headers.get("webhook-signature", "")
    if not (msg_id and timestamp and sig_header):
        raise ValueError("Missing webhook signature headers")

    if abs(int(time.time()) - int(timestamp)) > 300:
        raise ValueError("Webhook timestamp outside tolerance")

    key = base64.b64decode(secret.removeprefix("whsec_"))
    expected = hmac.new(
        key,
        f"{msg_id}.{timestamp}.{raw_body}".encode("utf-8"),
        hashlib.sha256,
    ).digest()

    for entry in sig_header.split(" "):
        parts = entry.split(",", 1)
        if len(parts) != 2 or parts[0] != "v1":
            continue
        if hmac.compare_digest(base64.b64decode(parts[1]), expected):
            return json.loads(raw_body)

    raise ValueError("Invalid webhook signature")
```


<a id="retries"></a>

## Thử lại, xoay vòng khóa &#38; thực hành tốt nhất
- **Tiêu chí thành công**: Trả về bất kỳ mã HTTP `2xx` nào trong vòng **10 giây**. Mọi phản hồi không phải 2xx hoặc hết thời gian chờ đều bị tính là thất bại.
- **Lịch thử lại**: Khoảng thời gian chờ tăng dần là `1m, 5m, 15m, 30m, 1h, 2h, 3h, 4h, 4h, 4h, 4h`, tối đa **12 lần thử** trong khoảng 24 giờ. Các lần chuyển phát được lưu trong 7 ngày và bạn có thể gửi lại một lần chuyển phát thất bại từ [Console → API → Webhook](https://kerox.ai/vi/console/webhooks).
- **Xoay vòng khóa bí mật**: Khi bạn xoay vòng khóa bí mật ký trong console, khóa bí mật cũ vẫn còn hiệu lực trong **24 giờ**. Trong thời gian đó, `webhook-signature` chứa cả hai chữ ký `v1,...`, được phân tách bằng một dấu cách.
- **Tính lũy đẳng**: Loại bỏ trùng lặp dựa trên `webhook-id`, phản hồi nhanh bằng `200` và xử lý việc tải xuống bất đồng bộ. Bạn luôn có thể dùng `GET /v1/tasks/{id}` làm phương án dự phòng.
