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

# 批量任务 Webhook：接收带签名的任务完成通知

> 为批处理任务配置签名的 Webhook，并安全地接收每个已接受项目成功或失败的终端事件。

每当接受的批处理项目达到成功或失败的最终状态时，批量 Webhook 都会发送一个 HTTP `POST` 到您的根级别 `webhook_url`。

> [!NOTE]
>
> 批量任务 Webhook 有独立于单个任务 `callback_url` 的接收流程。使用账户级签名密钥验证 `X-Apixo-Signature`。

## 生命周期

```text theme={null}
Get the account-level secret with your API key
        ↓
Store the secret in your server-side secret manager
        ↓
Submit a batch with webhook_url
        ↓
An accepted item succeeds or fails
        ↓
APIXO signs and sends the webhook
        ↓
Verify, deduplicate, and process the event
```

无需另建 Webhook 账户。签名密钥属于当前 API 密钥所在的账户，该账户下的 API 密钥共用同一把签名密钥。

## 步骤 1：获取签名密钥

```http theme={null}
GET https://api.apixo.ai/api/v1/webhooks/secret
```

```bash theme={null}
curl "https://api.apixo.ai/api/v1/webhooks/secret" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "version": 1,
    "secret": "YOUR_WEBHOOK_SIGNING_SECRET"
  }
}
```

`secret` 是共享的 **签名密钥**：

* APIXO 使用它来计算每个 Webhook 请求的 HMAC-SHA256 签名。
* 您的服务使用它来验证请求是否来自 APIXO 并且其正文未被修改。
* 不要在批量请求或 Webhook 响应中返回密钥。
* Webhook 消息体本身未加密。HTTPS 负责传输加密，签名密钥用于验证发送方身份并确保消息未被篡改。
* 签名密钥只应保存在服务端的 KMS、Secret Manager 或受保护的环境变量中。不要将它暴露在客户端应用、源码仓库或日志中。

## 步骤 2：提交包含 webhook\_url 的批次

将 `webhook_url` 设置为批处理请求的根字段：

```bash theme={null}
curl -X POST "https://api.apixo.ai/api/v1/generateTask/seedream-4-5/batches" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Idempotency-Key: batch-20260915-002" \
  -H "Content-Type: application/json" \
  -d '{
    "webhook_url": "https://merchant.example.com/webhooks/apixo",
    "items": [
      {
        "client_item_id": "order-1003",
        "idempotency_key": "order-1003-v1",
        "input": {
          "mode": "text-to-image",
          "prompt": "A minimalist mountain coffee shop"
        }
      }
    ]
  }'
```

`webhook_url` 必须是可公开访问的 HTTPS 地址。每个批次都保留其签名密钥版本，因此密钥轮换不会影响已接收批次的验证。

## 步骤 3：接收 Webhook

APIXO 发送以下标头：

```http theme={null}
POST https://merchant.example.com/webhooks/apixo
Content-Type: application/json
X-Apixo-Event-Id: evt_123
X-Apixo-Timestamp: 1789459200
X-Apixo-Signature: v1,2b1c...
```

| 标头 | 说明 |
| - | - |
| `X-Apixo-Event-Id` | 唯一的交付事件 ID，用于接收端去重。 |
| `X-Apixo-Timestamp` | Unix 时间戳（以秒为单位），用于限制重放窗口。 |
| `X-Apixo-Signature` | `v1,` 后跟十六进制 HMAC-SHA256 签名。 |

### 任务成功时的通知内容

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_123",
    "state": "success",
    "resultJson": "{\"resultUrls\":[\"https://cdn.example.com/output.jpg\"]}"
  },
  "batch": {
    "batchId": "batch_123",
    "clientItemId": "order-1003"
  }
}
```

### 任务失败时的通知内容

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_987",
    "state": "failed",
    "failCode": "CONTENT_VIOLATION",
    "failMsg": "Content violates usage policy"
  },
  "batch": {
    "batchId": "batch_123",
    "clientItemId": "order-1004"
  }
}
```

### Webhook 通知字段

| 字段 | 类型 | 说明 |
| - | - | - |
| `code` | integer | Webhook 信封代码。`200`并不代表生成成功；需检查`data.state`。 |
| `message` | string | Webhook 信封消息。`success`用于正常终端有效负载。 |
| `data.taskId` | string | 平台上已完成任务的 ID。可在「单个任务」下的「查询任务状态」中使用。 |
| `data.state` | string | 终端业务状态。`success`表示生成成功；`failed`表示失败。 |
| `data.resultJson` | string | 通常在成功时出现。包含公共模型输出的JSON字符串，例如`resultUrls`。 |
| `data.failCode` | string | 通常在失败时出现。编程失败代码。 |
| `data.failMsg` | string | 通常出现在失败时。面向开发人员的失败解释。 |
| `batch.batchId` | string | 包含此任务的批次。 |
| `batch.clientItemId` | string | 调用者提供的项目定位器。使用它将事件与您的订单或工作关联起来。 |

## 步骤 4：验证、去重并响应

带符号的字节恰好是：

```text theme={null}
{eventId}.{timestamp}.{rawRequestBody}
```

计算签名为：

```text theme={null}
hex(HMAC-SHA256(secret, signingPayload))
```

`rawRequestBody`是原始的HTTP主体字节。在签名验证之前不要再次解析、格式化或序列化JSON。

### Node.js / Express 验证示例

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

const app = express();
const webhookSecret = process.env.APIXO_WEBHOOK_SECRET;

app.post('/webhooks/apixo', express.raw({ type: 'application/json' }), async (req, res) => {
  const eventId = req.get('X-Apixo-Event-Id');
  const timestamp = req.get('X-Apixo-Timestamp');
  const signatureHeader = req.get('X-Apixo-Signature') || '';
  const signature = signatureHeader.startsWith('v1,') ? signatureHeader.slice(3) : '';
  const nowSeconds = Math.floor(Date.now() / 1000);

  if (!eventId || !timestamp || !signature || Math.abs(nowSeconds - Number(timestamp)) > 300) {
    return res.status(400).send('Invalid webhook headers');
  }

  const signingPayload = Buffer.concat([
    Buffer.from(`${eventId}.${timestamp}.`, 'utf8'),
    req.body,
  ]);
  const expected = crypto
    .createHmac('sha256', webhookSecret)
    .update(signingPayload)
    .digest('hex');

  const receivedBytes = Buffer.from(signature, 'hex');
  const expectedBytes = Buffer.from(expected, 'hex');
  if (receivedBytes.length !== expectedBytes.length
      || !crypto.timingSafeEqual(receivedBytes, expectedBytes)) {
    return res.status(401).send('Invalid signature');
  }

  // Persist and deduplicate eventId with a database uniqueness constraint or a TTL-backed store.
  const payload = JSON.parse(req.body.toString('utf8'));
  if (payload.data.state === 'success') {
    // Find your order by payload.batch.clientItemId, then process the result asynchronously.
  } else {
    // Record payload.data.failCode / failMsg and update your failure state.
  }

  return res.status(204).end();
});
```

按此顺序处理每个事件：

1. 保留原始主体并读取三个 `X-Apixo-*` 请求头。
2. 检查时间戳是否在允许的时间窗口内；此示例使用五分钟。
3. 用账户的签名密钥计算 HMAC，再用恒定时间比较函数校验签名。
4. 持久化并去重 `X-Apixo-Event-Id`。
5. 仅在此之后解析 JSON、更新订单或将下游任务加入队列。
6. 一旦事件安全记录，返回任意 HTTP `2xx` 响应。

> [!WARNING]
>
> 不要验证已解析或重新序列化的 JSON 主体；即使字节级格式变化也会导致签名失效。通过 `X-Apixo-Event-Id` 去重，而不仅通过 `taskId`。

## 重试与恢复

* 任意 HTTP `2xx` 响应即表示成功投递。
* 非 `2xx` 响应、网络错误或超时将触发重试。
* 重试间隔为 **1 分钟 → 5 分钟 → 30 分钟 → 2 小时 → 6 小时**。包含首次交付，最多尝试六次。
* 保留 [批次状态](https://apixo.ai/docs/zh/api-reference/batch-status.md) 和单个任务 > 状态任务作为恢复和对账路径。

## 轮换或撤销密钥

### 轮换

```http theme={null}
POST https://api.apixo.ai/api/v1/webhooks/secret/rotate
```

新提交的批次使用新签名密钥。已受理的批次在七天宽限期内继续使用旧密钥，这段时间内接收端应支持两把密钥。

### 紧急撤销

```http theme={null}
POST https://api.apixo.ai/api/v1/webhooks/secret/revoke
```

撤销将抑制账户所有未完成的交付，并撤销现有密钥。要恢复批量 Webhook，请获取新密钥并使用 `webhook_url` 提交新批次。

## 生产环境检查清单

* 您的端点是公共 HTTPS 接口，并能快速返回 2xx 状态码。
* 签名密钥被安全存储，且不会暴露给客户端代码或日志。
* 接收方在解析 JSON 之前会验证原始请求体。
* 接收方会检查时间戳的新鲜度，并持久去重 `X-Apixo-Event-Id`。
* 将耗时任务放入队列或交给后台进程处理，及时返回 HTTP 响应。
* 支持对遗漏事件进行批次状态或状态任务的协调。


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