작업과 웹훅
미디어 생성은 비동기입니다. job ID로 폴링하거나 callback_url로 알림을 받고 웹훅 서명으로 발신자를 확인합니다.
- 상태는 queued, processing 후 completed 또는 failed가 됩니다.
- 폴링은 단순하고 웹훅은 공개 HTTPS 수신기가 필요합니다.
- 중복 전달을 허용하고 서명을 검증하며 job ID로 멱등 처리하세요.
전체 예제
원본 가이드의 실행 가능한 예제를 모두 아래에 보존했습니다. 사용 중인 도구와 운영체제에 해당하는 블록만 실행하세요.
POST /media/generate → status: processing ──► done (result_url ready)
│ └─► failed (error, funds refunded)
└── (optional) callback_url → push webhook on done/failedjson
{ "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 comparejavascript
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공식 문서 및 관련 링크
| Polling | Webhook | |
|---|---|---|
Public https address | not needed | required |
| Latency | up to poll interval | near-instant |
| Guarantee | you control it | best-effort + polling backup |
| Best for | scripts, CI, laptop | servers, production backends |
먼저 최소 텍스트 요청으로 연결을 확인한 다음 스트리밍, 도구 호출, 이미지와 같은 고급 기능을 추가하세요. API 키를 공개 코드나 브라우저 프런트엔드에 넣지 마세요.