> ## 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.

# Webhook 回调

> 媒体任务结束时收到一条签名的 POST，不必再轮询，并用签名密钥验证它。

创建媒体任务时加上 `callback_url`。任务结束后，OmniaKey 会把结束的任务放在一条签名的 `POST` 里发到这个地址。轮询 `GET /v1/media/tasks/{id}` 照常可用，两种方式可以同时用。

## 设置回调地址

把 `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"
  }'
```

地址要求：

* 以 `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}` 返回的对象，所以成功的任务带有 `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 秒才响应算失败。
* 不跟随重定向，请填写最终地址。
* 投递至少一次。同一事件的每次尝试都带相同的 `webhook-id`，处理过的 `webhook-id` 直接跳过即可。
* 同一个接收主机最多同时进行两次投递。
* 在控制台重试失败的任务后，新的这次运行结束时会再发一个事件，`webhook-id` 是新的。

## 测试接口

在[设置](https://omniakey.com/dashboard/settings#webhooks)的**任务回调**里填入你的地址，点**发送测试**。OmniaKey 会立刻发一个签名的 `webhook.test` 事件，并显示你的接口返回的状态码和响应时间。不需要媒体任务，第一个任务之前就能检查接收端。

## 网络

* 请求直接从 OmniaKey 的服务器发出，不经过代理。OmniaKey 不公布固定的来源 IP 列表，请靠验证签名来确认来源，不要按 IP 放行。
* 每次尝试前都会重新解析你的主机名。解析到内网或回环地址的尝试会被拒绝，这个事件也不再重试。


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