Webhook
將完成的任務推送到你的伺服器:送出時傳入 webhook_url,接收一次 POST,回應 2xx。簽章遵循 Standard Webhooks。
三個步驟完成設定
1. 取得公開的 HTTPS URL
Kerox 只會推送到可從網際網路存取的 https:// 位址(不可為 localhost 或私有 IP)。在正式環境中,這會是你伺服器上的一個路由,例如 https://your-app.example.com/webhooks/kerox。若要在自己的電腦上試用,可使用 webhook.site 等臨時檢查工具查看收到的內容,或使用通道服務(Cloudflare Tunnel、ngrok)將流量轉送到步驟 3 的本機接收端。
2. 送出時傳入 webhook_url
送出任務前,先將 KEROX_WEBHOOK_URL 設為步驟 1 的公開 HTTPS 接收端(shell 範例另需 jq)。請儲存回傳的任務 ID。若回呼延遲,可使用該 ID 讀取 GET /v1/tasks/{id}。
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" }
}')"3. 接收並回應 2xx
當任務以 succeeded 或 failed 結束時,Kerox 會向該 URL 傳送一次 POST,並附帶 Content-Type: application/json。你的端點應:
- 讀取原始請求內文;
- 驗證簽章(選用,見下文);
- 確認這是已結束的任務(
status為succeeded並附有outputs,或為failed並附有error),其他情況一律回應400,避免單一格式錯誤的請求造成中斷; - 略過已處理過的
webhook-id(重試時會帶有相同的值); - 在 10 秒內回應任一
2xx,之後再進行耗時作業(下載檔案)。
其他回應,或 10 秒內未回應,都會視為失敗並重試(重試)。以下是一個最簡接收端,監聽 PORT 指定的連接埠(預設為 8787),接收路徑為 /webhooks/kerox:
// 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));我們傳送的內容
請求主體就是任務物件本身,與 GET /v1/tasks/{id} 回傳的內容完全相同(欄位)。透過 status 區分成功或失敗:成功時檔案位於 outputs;失敗時原因位於 error,且預扣金額會退還(cost.status: "refunded")。只有兩種最終狀態會被推送,各推送一次;送出時未帶 webhook_url 的任務永遠不會推送。
{
"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"
}每次傳送也會附帶 webhook-id、webhook-timestamp 與 webhook-signature 標頭,說明如下。
簽章驗證(Standard Webhooks)
每次傳送都會依據 Standard Webhooks 規範簽署,並附帶三個標頭。驗證簽章是選用步驟,但建議執行,因為可以證明這次傳送確實來自 Kerox。
| 標頭 | 值 |
|---|---|
webhook-id | 唯一的傳送 ID(msg_...),重試時保持不變,可用來辨識重試送達的同一則通知,避免重複處理 |
webhook-timestamp | 產生簽章時的 Unix 時間戳記,以秒為單位 |
webhook-signature | 一個或多個 v1,<base64> 簽章,以空格分隔(金鑰輪替的 24 小時重疊期間會出現兩個) |
簽署的字串為 {webhook-id}.{webhook-timestamp}.{raw_body},Kerox 會以 HMAC-SHA256 對其簽署以產生簽章。HMAC 使用的金鑰位元組,是將你的簽章密鑰(顯示於 Console → API → Webhook)移除 whsec_ 前綴後,再經 base64 解碼所得。
使用 Standard Webhooks SDK 驗證
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);
}使用內建密碼學功能手動驗證
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);
}重試、輪替與最佳做法
- 成功條件:回傳任一 HTTP
2xx,且須在 10 秒內完成。任何非 2xx 回應或逾時都會視為失敗。 - 重試排程:退避間隔為
1m, 5m, 15m, 30m, 1h, 2h, 3h, 4h, 4h, 4h, 4h,在約 24 小時內最多嘗試 12 次。傳送紀錄會保留 7 天,失敗的傳送可以在 Console → API → Webhook 重新傳送。 - 簽署金鑰輪替:在主控台輪替簽署金鑰後,舊金鑰仍會在 24 小時內有效,期間
webhook-signature會同時包含兩個v1,...簽章,以空格分隔。 - 冪等性:以
webhook-id去除重複,盡快以200確認收到,並以非同步方式處理下載。你也隨時可以改用GET /v1/tasks/{id}。