Skip to Content

Webhook 回调

在任务进入终态时接收主动推送,并按 Standard Webhooks 规范校验 HMAC-SHA256 签名。

事件类型与请求体

当任务进入终态时,Kerox 会向该任务的 webhook_url(任务没带时用你在控制台 → API → Webhook里设置的默认接收地址)发送 POST 请求,Content-Type: application/json。接收地址只接受 https://。data 是完整的任务对象,和 GET /v1/tasks/{id} 返回的一样:

  • task.succeeded
  • task.failed
  • task.canceled
{
  "type": "task.succeeded",
  "created_at": "2026-11-20T08:01:10Z",
  "data": {
    "id": "task_01JD8X9B4Q2M7T8N3K5P6R1S0V",
    "object": "task",
    "model": "bytedance/seedream-5.5",
    "status": "succeeded",
    "source": "api",
    "format": "native",
    "input": {
      "prompt": "editorial portrait of a ceramicist in morning sunlight, 35mm film",
      "size": "2K"
    },
    "output": {
      "images": [
        {
          "url": "https://cdn.kerox.ai/t/task_01JD8X9B4Q2M7T8N3K5P6R1S0V/5f2b8c1e9d3a4f6b8a7c0d1e2f3a4b5c/0.png",
          "content_type": "image/png",
          "width": 2048,
          "height": 2048
        }
      ]
    },
    "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"
  }
}

签名校验(Standard Webhooks)

每次投递都按 Standard Webhooks 规范签名,并附带三个请求头。验签是可选的,但推荐做:它能确认推送来自 Kerox。

请求头说明
webhook-id投递唯一 ID(msg_...),重试时保持不变,可直接用于幂等去重
webhook-timestamp签发时的 Unix 秒级时间戳
webhook-signature一个或多个以空格分隔的 v1,<base64> 签名(轮换密钥后的 24 小时重叠期内会同时携带两个)

签名原文为 {webhook-id}.{webhook-timestamp}.{raw_body},使用 HMAC-SHA256 计算,密钥是你的签名密钥(在控制台 → API → Webhook里查看)去掉 whsec_ 前缀后 base64 解码得到的字节。

使用 Standard Webhooks 官方库验签

import { Webhook } from 'standardwebhooks';

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

export async function handleKeroxWebhook(rawBody, headers) {
  // 签名无效或时间戳超出 5 分钟窗口时会自动抛出异常
  const event = wh.verify(rawBody, {
    'webhook-id': headers['webhook-id'],
    'webhook-timestamp': headers['webhook-timestamp'],
    'webhook-signature': headers['webhook-signature'],
  });
  console.log(event.type, event.data.id, event.data.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);
}

重试策略、密钥轮换与建议

  • 成功判定:10 秒内返回任意 2xx 状态码视为投递成功,其他状态码或超时均计为失败。
  • 退避重试:依次间隔 1 分、5 分、15 分、30 分、1 时、2 时、3 时、4 时、4 时、4 时、4 时,最多 12 次(约 24 小时)。投递记录保留 7 天,失败的投递可以在控制台 → API → Webhook里重新发送。
  • 密钥轮换:在控制台轮换签名密钥后,旧密钥会继续有效 24 小时,期间 webhook-signature 会以空格分隔同时附带新旧两个 v1,... 签名。
  • 工程建议:按 webhook-id 做幂等去重;收到后尽快返回 200,再异步下载结果文件;即使偶发漏收,也可以随时通过 GET /v1/tasks/{id} 兜底查询。