Skip to content

工作與 Webhook

媒體生成是非同步工作:建立後取得 job ID,再以輪詢查詢,或提供 callback_url 接收完成通知。Webhook 可用簽名驗證來源。

  • 狀態依序為 queued、processing,最後為 completed 或 failed。
  • 輪詢實作最簡單;Webhook 更適合大量工作,但接收端必須公開使用 HTTPS。
  • 處理重複投遞、驗證簽名並以 job ID 做冪等;逾時後仍可主動查詢狀態。

完整範例

原始指南中的可執行範例完整保留如下。請只執行適用於您所用工具和作業系統的區塊。

POST /media/generate  →  status: processing  ──►  done   (result_url ready)
        │                                     └─►  failed (error, funds refunded)
        └── (optional) callback_url → push webhook on done/failed
json
{ "id": "beefb531-…", "model": "image/nano-banana-2", "status": "processing",
  "poll": "https://nordrouter.com/media/job/beefb531-…" }
json
{ "id": "beefb531-…", "status": "done",
  "result_url": "https://nordrouter.com/media/file/beefb531-…",
  "cost_usd": 0.052, "error": null }
bash
curl https://nordrouter.com/media/job/beefb531-…
bash
curl https://nordrouter.com/media/generate \
  -H "Authorization: Bearer sk-nr-YOUR-KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "image/nano-banana-2",
    "input": { "prompt": "…" },
    "callback_url": "https://your-server.com/webhooks/nordrouter",
    "callback_secret": "any-string-of-yours"
  }'
json
{ "event": "media.completed", "id": "beefb531-…", "status": "done",
  "result_url": "https://nordrouter.com/media/file/beefb531-…",
  "cost_usd": 0.052, "error": null }
python
import hmac, hashlib

def verify(raw_body: bytes, header: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(secret.encode(), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, header)  # constant-time compare
javascript
import crypto from "node:crypto";
function verify(rawBody, header, secret) {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("hex");
  return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(header));
}
javascript
import express from "express";
import crypto from "node:crypto";

const SECRET = "any-string-of-yours";          // = your callback_secret
const app = express();

app.post("/webhooks/nordrouter",
  express.raw({ type: "application/json" }),    // raw body — required for the signature
  (req, res) => {
    const expected = "sha256=" + crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
    const got = req.headers["x-nr-signature"] || "";
    if (expected.length !== got.length || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(got)))
      return res.sendStatus(401);              // signature mismatch — not from us
    const job = JSON.parse(req.body);
    if (job.event === "media.completed") console.log("done:", job.result_url, "$" + job.cost_usd);
    res.sendStatus(200);                        // reply 2xx or we retry
  });

app.listen(3000);
python
import hmac, hashlib
from fastapi import FastAPI, Request, Response

SECRET = b"any-string-of-yours"                # = your callback_secret
app = FastAPI()

@app.post("/webhooks/nordrouter")
async def hook(request: Request):
    raw = await request.body()                 # raw bytes — required for the signature
    expected = "sha256=" + hmac.new(SECRET, raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, request.headers.get("X-NR-Signature", "")):
        return Response(status_code=401)       # signature mismatch — not from us
    job = await request.json()
    if job["event"] == "media.completed":
        print("done:", job["result_url"], "$", job["cost_usd"])
    return Response(status_code=200)           # reply 2xx or we retry

官方資料與相關連結

PollingWebhook
Public https addressnot neededrequired
Latencyup to poll intervalnear-instant
Guaranteeyou control itbest-effort + polling backup
Best forscripts, CI, laptopservers, production backends

先以最小文字請求驗證連線,再加入串流、工具呼叫、圖片或其他進階功能。請勿把 API 金鑰寫入公開程式碼或瀏覽器前端。

疑難排解