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