Skip to Content
로그인

Webhook

완료된 작업 결과를 서버에서 바로 받을 수 있습니다. 제출 시 webhook_url을 전달하면 POST 요청을 한 번 받게 되며, 2xx로 응답하면 됩니다. 서명은 Standard Webhooks를 따릅니다.

3단계로 설정하기

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 URL로 설정합니다(셸 예제에는 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와 함께 해당 URL로 POST를 한 번 전송합니다. 엔드포인트는 다음을 수행합니다.

  1. 원본 요청 본문을 읽습니다.
  2. 서명을 검증합니다(선택 사항, 아래 참조).
  3. 완료된 작업인지 확인하고(status가 succeeded이면서 outputs가 있거나, failed이면서 error가 있는 경우), 그 밖의 요청에는 400로 응답하여 잘못된 요청 하나로 인해 중단되지 않도록 합니다.
  4. 이미 처리한 webhook-id는 건너뜁니다(재시도 시 동일한 값이 전달됩니다).
  5. 2xx 응답은 10초 이내에 반환하고, 시간이 오래 걸리는 작업(파일 다운로드)은 그 이후에 처리합니다.

그 외의 응답이나 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}이며, 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}로 대체할 수 있습니다.