> ## 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 任務結果的 Webhook 回呼，並進行可靠性權衡。

根據代碼運行的位置選擇交付方式。本機腳本可送出任務、儲存其 ID 並[輪詢狀態端點](https://apixo.ai/docs/zh-hant/api-reference/status-task.md)。具有公開 HTTPS 端點的服務可[接收回呼](https://apixo.ai/docs/zh-hant/api-reference/webhooks.md) 並與已儲存的 ID 進行對照。無論哪種情況，皆應在讀取結果前檢查任務狀態。

## 快速比較

| 項目 | 輪詢（非同步） | Webhook（回呼） |
| - | - | - |
| **設定** | 簡單的 | 需要公共端點 |
| **實時** | 近實時 | 即時 |
| **API 呼叫** | 每個任務可有多個 | 每個任務一個 |
| **最佳適用情境** | 開發、用戶端應用程式 | 生產伺服器 |
| **基礎設施** | 無 | HTTPS 端點 |

## 何時使用輪詢

**在下列情況下選擇輪詢：**

* 建立用戶端應用程式
* 原型設計或測試
* 您沒有公共伺服器
* 處理少量任務

### 基本輪詢實現

```javascript theme={null}
async function pollForResult(model, taskId, apiKey) {
  const interval = 3000; // 3 seconds
  const maxAttempts = 60;
  
  for (let i = 0; i < maxAttempts; i++) {
    const response = await fetch(
      `https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
      { headers: { 'Authorization': `Bearer ${apiKey}` } }
    );
    
    const { data } = await response.json();
    
    if (data.state === 'success') {
      return JSON.parse(data.resultJson).resultUrls;
    }
    if (data.state === 'failed') {
      throw new Error(data.failMsg);
    }
    
    await new Promise(r => setTimeout(r, interval));
  }
  
  throw new Error('Timeout');
}
```

### 指數退避

為提升效率，建議使用指數退避：

```javascript theme={null}
async function pollWithBackoff(model, taskId, apiKey) {
  let interval = 3000; // Start at 3s
  const maxInterval = 30000; // Max 30s
  const maxTime = 300000; // 5 min timeout
  let elapsed = 0;
  
  while (elapsed < maxTime) {
    const response = await fetch(
      `https://api.apixo.ai/api/v1/statusTask/${model}?taskId=${taskId}`,
      { headers: { 'Authorization': `Bearer ${apiKey}` } }
    );
    
    const { data } = await response.json();
    
    if (data.state === 'success') {
      return JSON.parse(data.resultJson).resultUrls;
    }
    if (data.state === 'failed') {
      throw new Error(data.failMsg);
    }
    
    await new Promise(r => setTimeout(r, interval));
    elapsed += interval;
    interval = Math.min(interval * 1.5, maxInterval);
  }
  
  throw new Error('Timeout');
}
```

### 依模型類型建議的間隔時間

| 型號類型 | 初始等待 | 輪詢間隔 | 最大等待時間 |
| - | - | - | - |
| 影像（快速） | 5s | 3s | 2 分鐘 |
| 影像（品質） | 10s | 5s | 3 分鐘 |
| 影片 | 60s | 15s | 10 分鐘 |
| 音訊 | 30s | 10s | 5 分鐘 |

## 何時使用 Webhook

**在下列情況下選擇 Webhook：**

* 運行生產伺服器
* 處理大量任務
* 需要即時通知
* 想盡量減少 API 通話

### Webhook 設定

**1。建立端點：**

> [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);
>     // Process your images/videos
>   } else if (state === 'failed') {
>     console.error(`Task ${taskId} failed: ${failCode}`);
>   }
>
>   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']}")
>
>     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 } = 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}`);
>   }
>
>   return NextResponse.json({ status: 'ok' });
> }
> ```

**2。提交帶有回呼的任務：**

```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',
    },
  }),
});
```

### Webhook 要求

* 必須可透過 HTTPS 公開存取
* 必須回應 HTTP 200 之內 30 秒
* 應處理重複交付（使用 `taskId` 實現冪等性）

### 重試政策

如果您的 webhook 失敗：

| 試圖 | 延遲 |
| - | - |
| 第一次重試 | 30秒 |
| 第二次重試 | 2 分鐘 |
| 第三次重試 | 10 分鐘 |

如果 3 次投遞均失敗，系統會停止傳送該 Webhook。仍可透過狀態介面查詢任務。

## 混合方法

為了獲得最大的可靠性，請結合這兩種方法：

```javascript theme={null}
class TaskManager {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.pendingTasks = new Map();
  }
  
  async submit(model, input, callbackUrl = null) {
    const response = await fetch(
      `https://api.apixo.ai/api/v1/generateTask/${model}`,
      {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${this.apiKey}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          request_type: callbackUrl ? 'callback' : 'async',
          callback_url: callbackUrl,
          input,
        }),
      }
    );
    
    const { data } = await response.json();
    
    if (!callbackUrl) {
      // Fallback to polling if no webhook
      return this.poll(model, data.taskId);
    }
    
    // Track task for webhook
    this.pendingTasks.set(data.taskId, { model, status: 'pending' });
    return data.taskId;
  }
  
  handleWebhook(body) {
    const { taskId, state, resultJson, failMsg } = body.data;
    
    if (state === 'success') {
      this.pendingTasks.delete(taskId);
      return JSON.parse(resultJson).resultUrls;
    }
    
    if (state === 'failed') {
      this.pendingTasks.delete(taskId);
      throw new Error(failMsg);
    }
  }
  
  async poll(model, taskId) {
    // Fallback polling implementation
    return pollWithBackoff(model, taskId, this.apiKey);
  }
}
```

## 使用 ngrok 進行本地開發

對於本地測試 webhook：

```bash theme={null}
# Install ngrok
npm install -g ngrok

# Start your local server
node server.js  # runs on port 3000

# Tunnel to local server
ngrok http 3000
# Returns: https://abc123.ngrok.io

# Use ngrok URL as callback_url
```

## 摘要

| 情境設定 | 建議 |
| - | - |
| 開發/測試 | 輪詢 |
| 用戶端應用程式 | 輪詢 |
| 生產後台 | Webhook |
| 高流量 | Webhook |
| 最高可靠性 | 混合（webhooks + 輪詢後備） |

> [!NOTE]
>
> 為了簡單起見，從輪詢開始，然後隨著應用程式的擴展遷移到 Webhooks。


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