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