如何使用 Webhook
任务完成时接收一次 HTTP 回调,而不用轮询查询。
概览
提交任务时传入回调地址,任务到达终态(completed 或 failed)后 Get3W 会把结果 POST 到该地址。对于视频生成这类耗时较长的任务,轮询会浪费大量请求,Webhook 是更好的选择。
推送在工作节点的后台线程中进行,因此永远不会阻塞任务执行。
配置方式
回调地址放在 webhook 查询参数里,而不是请求体中:
bash
curl -X POST "https://api.get3w.com/v1/google/nano-banana-pro/text-to-image?webhook=https://your-server.com/callback" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"prompt": "A cat in space",
"aspect_ratio": "16:9"
}'如果回调地址自身带有查询参数,记得先做 URL 编码。
提交调用会立即返回:
json
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"status": "created",
"estimated_duration": 52
}Webhook 请求体
任务完成时,Get3W 会把这样的 JSON 体 POST 到你的地址:
json
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"model": "google/nano-banana-pro/text-to-image",
"status": "completed",
"code": 0,
"created_at": "2026-03-28T07:50:42",
"input": {
"prompt": "A cat in space",
"aspect_ratio": "16:9"
},
"outputs": ["https://storage.example.com/output.png"],
"error": null
}| 字段 | 类型 | 说明 |
|---|---|---|
id | string | 任务 ID,与提交响应中的一致 |
model | string | 模型 slug |
status | string | completed 或 failed |
code | int | 成功为 0;失败时参见错误码 |
created_at | string | 任务创建时间 |
input | object | 你提交的参数 |
outputs | string[] | 输出 URL;任务失败时为空 |
error | string | 错误信息;任务成功时为 null |
失败时结构完全相同,只是 outputs 为空且 error 有内容:
json
{
"id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
"model": "google/nano-banana-pro/text-to-image",
"status": "failed",
"code": 1200,
"created_at": "2026-03-28T07:50:42",
"input": { "prompt": "..." },
"outputs": [],
"error": "Content moderation: prompt contains prohibited content"
}由于每次推送都带有相同的字段,你可以直接按 status 分支处理,不需要判断字段是否缺失。
处理 Webhook
Python(Flask)
python
from flask import Flask, request
app = Flask(__name__)
@app.route("/callback", methods=["POST"])
def handle_webhook():
data = request.json
if data["status"] == "completed":
print(f"Task {data['id']} completed: {data['outputs']}")
elif data["status"] == "failed":
print(f"Task {data['id']} failed ({data['code']}): {data['error']}")
return "", 200Node.js(Express)
javascript
const express = require("express");
const app = express();
app.use(express.json());
app.post("/callback", (req, res) => {
const { id, status, outputs, code, error } = req.body;
if (status === "completed") {
console.log(`Task ${id} completed:`, outputs);
} else if (status === "failed") {
console.log(`Task ${id} failed (${code}):`, error);
}
res.sendStatus(200);
});
app.listen(3000);要求
- 你的接口必须可以从公网访问
- 必须接受带 JSON 请求体的 POST 请求
- 必须在 30 秒内返回 2xx,否则本次推送算作失败
- 建议使用 HTTPS
本地开发时,可以用 ngrok 这类内网穿透工具把服务暴露出去。
重试策略
如果你的接口返回非 2xx 状态或无法访问,Get3W 会按指数退避重试:
| 尝试次数 | 本次尝试前的等待 |
|---|---|
| 第 1 次 | 立即 |
| 第 2 次 | 2 秒 |
| 第 3 次 | 4 秒 |
3 次尝试都失败后就放弃推送。结果不会丢失 —— 只要任务记录还在保留期内,你都可以通过 GET /v1/requests/{request_id} 获取。
提示
把 Webhook 当作快车道,而不是唯一通道。对没收到回调的任务做一次简短的对账轮询,能让集成在你自己服务宕机时依然可靠。
处理重复推送
重试可能在你的服务器已经处理完第一次推送、只是没能及时响应之后到达。请以任务 id 为键做幂等处理,忽略已经处理过的推送。
下一步
- Webhook 模式 —— 带代码示例的完整教程
- 异步模式 —— 轮询方案
- 错误码 ——
code字段的含义