> ## 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 · 接收任務完成回呼

> 透過回呼接收 APIXO 生成任務完成的通知，處理成功、失敗與重試，無需輪詢。

生成任務結束時，可在公開的 HTTPS 端點接收結果。如果應用不能接收入站請求，請[比較輪詢和 Webhook](https://apixo.ai/docs/zh-hant/guides/polling-vs-webhooks.md)，再選擇取得結果的方式。

## 概覽

使用 `callback` 模式時，任務完成後 APIXO 會向指定 URL 傳送 POST 請求。這樣無需持續輪詢即可立即收到通知，適合任務量較大的正式環境。

## 設定步驟

**1. 建立 Webhook 端點**

端點必須能接收 POST 請求，在 30 秒內傳回 HTTP 200，並可透過 HTTPS 公開存取。

> [!WARNING]
>
> 如果端點未在 30 秒內傳回 HTTP 200，APIXO 最多會重試 3 次，並逐步延長重試間隔。

> [tab] Express.js
>
> ```javascript theme={null}
> const express = require('express');
> const app = express();
>
> app.use(express.json());
>
> app.post('/webhook/apixo', (req, res) => {
>   const { taskId, state, resultJson, failCode, failMsg } = req.body.data;
>
>   if (state === 'success') {
>     const urls = JSON.parse(resultJson).resultUrls;
>     console.log('Generated:', urls);
>   } else if (state === 'failed') {
>     console.error(`Task ${taskId} failed: ${failCode} - ${failMsg}`);
>   }
>
>   res.status(200).send('OK');
> });
>
> app.listen(3000);
> ```

> [tab] FastAPI
>
> ```python theme={null}
> from fastapi import FastAPI, Request
> import json
>
> app = FastAPI()
>
> @app.post('/webhook/apixo')
> async def handle_webhook(request: Request):
>     body = await request.json()
>     data = body['data']
>
>     if data['state'] == 'success':
>         urls = json.loads(data['resultJson'])['resultUrls']
>         print(f"Generated: {urls}")
>     elif data['state'] == 'failed':
>         print(f"Task {data['taskId']} failed: {data['failCode']} - {data['failMsg']}")
>
>     return {'status': 'ok'}
> ```

> [tab] Next.js
>
> ```typescript theme={null}
> // app/api/webhook/apixo/route.ts
> import { NextRequest, NextResponse } from 'next/server';
>
> export async function POST(request: NextRequest) {
>   const body = await request.json();
>   const { taskId, state, resultJson, failCode, failMsg } = body.data;
>
>   if (state === 'success') {
>     const urls = JSON.parse(resultJson).resultUrls;
>     console.log('Generated:', urls);
>   } else if (state === 'failed') {
>     console.error(`Task ${taskId} failed: ${failCode} - ${failMsg}`);
>   }
>
>   return NextResponse.json({ status: 'ok' });
> }
> ```

**2. 送出使用回呼的任務**

在請求中加入 `request_type: "callback"` 和你的 `callback_url`。

> [tab] cURL
>
> ```bash theme={null}
> curl -X POST https://api.apixo.ai/api/v1/generateTask/nano-banana \
>   -H "Authorization: Bearer YOUR_API_KEY" \
>   -H "Content-Type: application/json" \
>   -d '{
>     "request_type": "callback",
>     "callback_url": "https://your-domain.com/webhook/apixo",
>     "input": {
>       "mode": "text-to-image",
>       "prompt": "A beautiful landscape",
>       "aspect_ratio": "16:9"
>     }
>   }'
> ```

> [tab] JavaScript
>
> ```javascript theme={null}
> const response = await fetch('https://api.apixo.ai/api/v1/generateTask/nano-banana', {
>   method: 'POST',
>   headers: {
>     'Authorization': 'Bearer YOUR_API_KEY',
>     'Content-Type': 'application/json',
>   },
>   body: JSON.stringify({
>     request_type: 'callback',
>     callback_url: 'https://your-domain.com/webhook/apixo',
>     input: {
>       mode: 'text-to-image',
>       prompt: 'A beautiful landscape',
>       aspect_ratio: '16:9',
>     },
>   }),
> });
> ```

> [tab] Python
>
> ```python theme={null}
> import requests
>
> response = requests.post(
>     'https://api.apixo.ai/api/v1/generateTask/nano-banana',
>     headers={
>         'Authorization': 'Bearer YOUR_API_KEY',
>         'Content-Type': 'application/json',
>     },
>     json={
>         'request_type': 'callback',
>         'callback_url': 'https://your-domain.com/webhook/apixo',
>         'input': {
>             'mode': 'text-to-image',
>             'prompt': 'A beautiful landscape',
>             'aspect_ratio': '16:9',
>         },
>     }
> )
> ```

## Webhook 請求主體

### 成功

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz",
    "state": "success",
    "resultJson": "{\"resultUrls\":[\"https://cdn.apixo.ai/output/abc.jpg\"]}",
    "costTime": 12500,
    "createTime": 1704067200000,
    "completeTime": 1704067212500
  }
}
```

### 失敗

```json theme={null}
{
  "code": 200,
  "message": "success",
  "data": {
    "taskId": "task_abc123xyz",
    "state": "failed",
    "failCode": "CONTENT_VIOLATION",
    "failMsg": "Content violates usage policy",
    "createTime": 1704067200000,
    "completeTime": 1704067205000
  }
}
```

### 請求主體欄位

**taskId** `string`

任務的唯一識別碼。

**state** `string`

任務的最終狀態為 `success` 或 `failed`。

**resultJson** `string`

包含 `resultUrls` 陣列的 JSON 字串，僅在任務成功時傳回。

**costTime** `integer`

處理耗時，單位為毫秒。

**failCode** `string`

錯誤碼，僅在任務失敗時傳回。

**failMsg** `string`

便於閱讀的錯誤訊息，僅在任務失敗時傳回。

## 重試策略

Webhook 端點未能傳回 HTTP 200 時，將依下列間隔重試。

| 重試次數 | 等待時間 |
| - | - |
| 第 1 次重試 | 30 秒 |
| 第 2 次重試 | 2 分鐘 |
| 第 3 次重試 | 10 分鐘 |

如果 3 次投遞均失敗，系統會停止傳送該 Webhook。仍可透過[查詢任務狀態](https://apixo.ai/docs/zh-hant/api-reference/status-task.md)介面取得任務狀態。

## 安全建議

### 實現冪等處理

> [!NOTE]
>
> 同一條 Webhook 可能重複送達。請使用 `taskId` 去重，避免重複處理同一個結果。

```javascript theme={null}
const processedTasks = new Set();

app.post('/webhook/apixo', (req, res) => {
  const { taskId } = req.body.data;
  
  if (processedTasks.has(taskId)) {
    return res.status(200).send('Already processed');
  }
  
  processedTasks.add(taskId);
  // Process the task...
  
  res.status(200).send('OK');
});
```

### 僅使用 HTTPS

Webhook 端點應始終使用 HTTPS，確保資料在傳輸過程中加密。

## 測試 Webhook

開發時可使用 [ngrok](https://ngrok.com) 讓外部訪問本地伺服器。

```bash theme={null}
ngrok http 3000
# Returns: https://abc123.ngrok.io — use this as your callback_url
```

> [!TIP]
>
> 使用回呼模式時，也可以透過 API 查詢任務狀態，方便除錯。


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