> ## Documentation Index
> Fetch the complete documentation index at: https://docs.omniakey.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 웹훅

> 미디어 작업이 끝나면 서명된 POST를 받습니다. 폴링할 필요가 없고, 서명 시크릿으로 검증합니다.

미디어 작업을 만들 때 `callback_url`을 넣으세요. 작업이 끝나면 OmniaKey가 끝난 작업을
서명된 `POST` 한 번으로 그 URL에 보냅니다. `GET /v1/media/tasks/{id}` 폴링도 그대로
쓸 수 있으니 둘을 함께 써도 됩니다.

## 콜백 URL 추가

생성 요청 본문의 최상위에 `callback_url`을 넣습니다.

```bash theme={null}
curl --fail-with-body https://api.omniakey.com/v1/media/tasks \
  -H "Authorization: Bearer your-omniakey-api-key" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: boat-with-callback-001" \
  -d '{
    "model": "gpt-image-2.6-flare",
    "type": "image",
    "operation": "generate",
    "input": {"prompt": "a paper boat on a quiet lake"},
    "parameters": {"size": "1024x1024", "quality": "medium"},
    "callback_url": "https://example.com/webhooks/omniakey"
  }'
```

URL 조건:

* `https://`로 시작해야 합니다. 포트는 상관없습니다.
* 공개 호스트를 가리켜야 합니다. 사설 주소와 루프백 주소, `localhost`, `*.local`이나
  `*.internal` 같은 이름은 `400 invalid_request`로 거부되며 요금은 부과되지 않습니다.
* 2,048자 이하여야 하며 사용자 이름이나 비밀번호를 넣을 수 없습니다.

`callback_url`은 멱등성 검사에 포함됩니다. 같은 `Idempotency-Key`에 다른 `callback_url`을
보내면 `409 idempotency_key_reused`가 반환됩니다.

## 전달 상태

`callback_url`을 넣어 만든 작업은 생성 응답과 `GET /v1/media/tasks/{id}`에 `callback`
객체가 포함됩니다.

```json theme={null}
"callback": {
  "url": "https://example.com/webhooks/omniakey",
  "status": "delivered",
  "attempts": 1,
  "event_id": "msg_2c1f0e9a7b4d4a6c8e3b5d7f9a1c3e5b",
  "event_type": "media_task.succeeded",
  "last_attempt_at": "2026-11-18T09:12:41Z",
  "last_status_code": 200,
  "delivered_at": "2026-11-18T09:12:41Z"
}
```

| `status` | 의미 |
| - | - |
| `waiting` | 작업이 아직 끝나지 않았습니다 |
| `pending` | 다음 시도가 `next_attempt_at`에 예정되어 있습니다 |
| `delivered` | 엔드포인트가 `2xx`로 응답했습니다 |
| `failed` | 모든 시도가 실패했습니다. 마지막 상황은 `last_error`에 있습니다 |

[미디어 라이브러리](https://omniakey.com/dashboard/media)의 작업 상세에서도 같은 상태를
볼 수 있습니다. 전달됐거나 실패한 이벤트는 **다시 보내기**로 한 번 더 보낼 수 있으며,
`webhook-id`는 그대로입니다.

## 이벤트

```http theme={null}
POST /webhooks/omniakey HTTP/1.1
Content-Type: application/json
User-Agent: OmniaKey-Webhooks/1.0
webhook-id: msg_2c1f0e9a7b4d4a6c8e3b5d7f9a1c3e5b
webhook-timestamp: 1763457161
webhook-signature: v1,<base64 HMAC-SHA256 signature>

{"type":"media_task.succeeded","timestamp":"2026-11-18T09:12:40Z","data":{...}}
```

`data`는 `GET /v1/media/tasks/{id}`가 반환하는 객체와 같습니다. 그래서 성공한 작업에는
새로 서명된 URL이 담긴 `assets[]`가 들어 있습니다. `timestamp`는 이벤트가 만들어진
시각이며 시도마다 바뀌지 않습니다.

| `type` | 보내는 때 |
| - | - |
| `media_task.succeeded` | 작업이 완료됐습니다. `expires_at` 전에 `data.assets[]`를 내려받으세요 |
| `media_task.failed` | 작업이 실패했거나 만료됐습니다. 이유는 `data.error`에 있습니다 |
| `media_task.canceled` | 작업이 취소됐습니다 |
| `webhook.test` | 대시보드에서 테스트 이벤트를 보냈습니다 |

OmniaKey는 작업의 과금이 확정된 뒤에 이벤트를 보냅니다. 그래서 실패하거나 취소된 작업은
보통 그때 이미 환불돼 있습니다. 대부분의 이벤트는 작업이 끝나고 몇 초 안에 전송됩니다.

## 서명 검증

이벤트는 [Standard Webhooks](https://www.standardwebhooks.com/) 사양을 따르므로 해당
라이브러리로 검증할 수 있습니다. 서명 시크릿(`whsec_...`)은
[설정](https://omniakey.com/dashboard/settings#webhooks)의 **작업 콜백**에 있습니다.
계정마다 시크릿이 하나 있으며, API 키로는 읽을 수 없습니다.

```python Python theme={null}
# pip install standardwebhooks flask
from flask import Flask, request
from standardwebhooks.webhooks import Webhook

app = Flask(__name__)
webhook = Webhook("whsec_...")


@app.post("/webhooks/omniakey")
def omniakey_webhook():
    # Raises WebhookVerificationError for a bad signature or an old timestamp.
    event = webhook.verify(request.get_data(), dict(request.headers))
    if event["type"] == "media_task.succeeded":
        save_assets(event["data"]["assets"])
    return "", 204
```

```javascript Node.js theme={null}
// npm install standardwebhooks express
import express from "express";
import { Webhook } from "standardwebhooks";

const app = express();
const webhook = new Webhook("whsec_...");

app.post("/webhooks/omniakey", express.raw({ type: "application/json" }), (req, res) => {
  let event;
  try {
    event = webhook.verify(req.body, req.headers);
  } catch {
    return res.status(400).end();
  }
  if (event.type === "media_task.succeeded") saveAssets(event.data.assets);
  res.status(204).end();
});
```

### 라이브러리 없이 검증하기

1. 시크릿에서 `whsec_` 뒤의 부분을 Base64로 디코딩합니다. 이것이 HMAC 키입니다.
2. `{webhook-id}.{webhook-timestamp}.{원본 본문}`을 만듭니다.
3. 그 키로 HMAC-SHA256을 계산합니다.
4. 결과를 `webhook-signature`의 각 `v1,<base64>` 항목과 상수 시간으로 비교합니다.
   항목은 공백으로 구분됩니다.
5. `webhook-timestamp`가 서버 시계와 5분 넘게 차이 나면 거부합니다.

```javascript theme={null}
import crypto from "node:crypto";

export function verifyOmniaKeyWebhook(secret, headers, rawBody) {
  const id = headers["webhook-id"];
  const timestamp = headers["webhook-timestamp"];
  if (!id || !timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const key = Buffer.from(secret.slice("whsec_".length), "base64");
  const expected = crypto.createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
  return String(headers["webhook-signature"] ?? "")
    .split(" ")
    .some((entry) => {
      const [version, signature] = entry.split(",");
      if (version !== "v1" || !signature) return false;
      const given = Buffer.from(signature, "base64");
      return given.length === expected.length && crypto.timingSafeEqual(given, expected);
    });
}
```

> [!WARNING]
>
> 파싱하기 전에 원본 요청 본문으로 검증하세요. JSON을 파싱했다가 다시 직렬화하면 바이트가
> 바뀌어 서명이 맞지 않습니다.

설정에서 시크릿을 교체하면 이후 24시간 동안 모든 이벤트에 서명이 두 개 붙습니다. 하나는 새
시크릿, 하나는 이전 시크릿으로 만든 서명입니다. 그동안 서버를 새 시크릿으로 바꾸면 이벤트를
놓치지 않습니다.

## 재시도

| 엔드포인트 응답 | OmniaKey 동작 |
| - | - |
| 15초 안에 `2xx`로 응답 | 전달 완료로 표시 |
| `410 Gone`으로 응답 | 이 이벤트 전송을 중단 |
| 그 밖의 경우: 다른 상태 코드, 리디렉션, 15초 안에 응답 없음, TLS 또는 연결 오류 | 다시 시도 |

첫 시도 후 5초, 5분, 30분, 2시간, 5시간, 10시간, 10시간 간격으로 다시 시도합니다.
모두 8번, 약 27.6시간입니다. 마지막 시도까지 실패하면 콜백은 `failed`가 됩니다.

* 빨리 응답하고 오래 걸리는 작업은 나중에 하세요. 15초가 지난 응답은 실패로 처리됩니다.
* 리디렉션은 따라가지 않으므로 최종 URL을 쓰세요.
* 전달은 최소 한 번(at-least-once) 보장입니다. 같은 이벤트의 모든 시도에는 같은
  `webhook-id`가 붙으므로, 이미 처리한 `webhook-id`는 건너뛰세요.
* 받는 호스트마다 동시에 진행되는 시도는 최대 두 개입니다.
* 실패한 작업을 대시보드에서 재시도하면, 새 실행이 끝날 때 새 `webhook-id`로 이벤트가 하나
  더 전송됩니다.

## 엔드포인트 테스트

[설정](https://omniakey.com/dashboard/settings#webhooks)의 **작업 콜백**에서 URL을 입력하고
**테스트 보내기**를 누르세요. OmniaKey가 서명된 `webhook.test` 이벤트를 바로 보내고,
엔드포인트의 상태 코드와 응답 시간을 보여 줍니다. 미디어 작업이 없어도 되므로 첫 작업 전에
수신 측을 확인할 수 있습니다.

## 네트워크

* 요청은 프록시를 거치지 않고 OmniaKey 서버에서 직접 보냅니다. OmniaKey는 고정된 출발지
  IP 목록을 공개하지 않으므로 IP 허용 목록 대신 서명으로 확인하세요.
* 호스트 이름은 시도할 때마다 다시 조회합니다. 사설 주소나 루프백 주소로 조회되는 이름으로의
  시도는 거부되며, 그 이벤트는 다시 시도하지 않습니다.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.