Skip to Content
ログイン

Webhook

タスクの送信時に webhook_url を指定すると、タスクの完了時にサーバーへ POST が 1 回送信されます。2xx で応答してください。署名は Standard Webhooks に準拠しています。

3 つのステップで設定

1. 公開 HTTPS URL を用意する

Kerox は、インターネットからアクセスできる https:// アドレスにのみ送信します(localhost やプライベート IP は不可)。本番環境では、https://your-app.example.com/webhooks/kerox のようなサーバー上のルートを使います。手元のコンピューターで試す場合は、受信した Webhook を一時的に確認できるサービス(webhook.site など)で届いた内容を確認するか、トンネル(Cloudflare Tunnel、ngrok)を使ってステップ 3 の受信側に転送します。

2. 送信時に webhook_url を渡す

タスクを送信する前に、KEROX_WEBHOOK_URL にステップ 1 の公開 HTTPS 受信先を設定します(シェルの例では 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 は Content-Type: application/json を付けた POST を URL に 1 回送信します。エンドポイントでは次の処理を行います。

  1. 生のリクエストボディを読み取ります。
  2. 署名を検証します(任意、後述)。
  3. 完了したタスクであること(status が「succeeded かつ outputs」または「failed かつ error」であること)を確認し、それ以外のリクエストには 400 を返します。これにより、形式に不備のあるリクエストが 1 件届いても処理が止まりません。
  4. 処理済みの webhook-id はスキップします(リトライでは同じ値が送られます)。
  5. 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")。配信されるのは 2 つの最終状態のみで、それぞれ 1 回だけです。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 仕様に従って署名され、3 つのヘッダーが付与されます。署名の検証は任意ですが、推奨します。配信が Kerox から送られたものであることを確認できます。

ヘッダー値
webhook-id一意の配信 ID(msg_...)。再試行しても変わらないため、重複排除に使用します
webhook-timestamp署名が生成された時刻の Unix タイムスタンプ(秒)
webhook-signatureスペース区切りの 1 つ以上の v1,<base64> 署名(鍵のローテーション時、旧鍵と新鍵が併用される 24 時間は 2 つ含まれます)

署名対象の文字列は {webhook-id}.{webhook-timestamp}.{raw_body} です。whsec_ プレフィックスを取り除いた署名シークレット(Console → API → Webhook に表示)を base64 デコードしたバイト列を使い、HMAC-SHA256 で署名されます。

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);
}

組み込みの crypto で手動検証する

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 秒以内に任意の HTTP 2xx を返してください。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} にフォールバックできます。