↓
Rivya AI 文件

API Webhooks

設定 Rivya API 生成事件 Webhook,驗證 HMAC 簽章,查詢投遞紀錄,傳送測試事件並處理重試。

最近審閱於 2026年11月5日

API Webhook 會針對 Public API 生成任務向伺服器傳送已簽章通知。註冊端點、選擇事件,並在處理前驗證每次投遞。

也可輪詢 GET /api/v1/generations/{taskId} 核查任務。保留輪詢,以核對遺漏或延遲的事件。

所需 Scope

Webhook 管理需要啟用且未過期的 Bearer API 金鑰,並具有:

webhooks:manage

設定中新建的金鑰預設包含此權限。端點、事件與投遞紀錄歸帳號所有;同帳號具有此權限的其他金鑰也可管理。

管理路由要求部署同時啟用 Public API 與 Webhook;服務關閉時傳回 503 public_api_disabled。

建立 Endpoint

POST /api/v1/webhooks
curl https://rivya.ai/api/v1/webhooks \
  -H "Authorization: Bearer rvya_sk_..." \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production webhook",
    "url": "https://example.com/rivya/webhook",
    "event_types": ["generation.succeeded", "generation.failed"]
  }'

傳送前替換範例金鑰與 URL。此呼叫僅註冊端點,不測試投遞。

name 必填,去除首尾空白後為 1–120 字元。url 必填且須符合下文規則。可省略 event_types 訂閱兩種生成事件,或傳最多兩個受支援事件類型的非空陣列。

建立成功傳回 HTTP 201。以下 ID、密鑰與時間均為佔位範例。完整 signing_secret 只在建立或密鑰輪換回應出現,不在清單、查詢、更新或停用回應中出現:

{
  "id": "whend_...",
  "object": "webhook_endpoint",
  "name": "Production webhook",
  "url": "https://example.com/rivya/webhook",
  "event_types": ["generation.succeeded", "generation.failed"],
  "status": "active",
  "secret_preview": "whsec_12...abc123",
  "signing_secret": "whsec_...",
  "last_success_at": null,
  "last_failure_at": null,
  "failure_count": 0,
  "created_at": "2026-05-11T00:00:00.000Z",
  "updated_at": "2026-05-11T00:00:00.000Z",
  "disabled_at": null,
  "revoked_at": null
}

在伺服器端安全儲存完整密鑰。遺失時需輪換並更新接收端;輪換會取代後續投遞使用的密鑰,不保留舊密鑰寬限期。

建立或輪換未收到確認回應時,操作可能已完成。重複建立前先查端點清單;已有完整密鑰無法重新查詢,無法找回回應時需輪換。

URL 規則

使用公開可達的 HTTPS 接收 URL,最多 2,048 字元,不含使用者名稱密碼或 fragment。不使用環回、私網或保留位址。

檢查拒絕 localhost 名稱、以 .localhost 或 .local 結尾的名稱及遭禁止的 IPv4 字面位址。註冊時不解析主機名稱檢查目標位址。

每次投遞使用 POST、Content-Type: application/json 與 Rivya 投遞標頭,不接受端點擁有者的自訂標頭,不自動跟隨重新導向,逾時為 10 秒。

Events

支援以下生成事件:

  • generation.succeeded:任務成功且 settlement_status 為 SETTLED。

  • generation.failed:任務失敗;查看 settlement_status 與 final_credits 判斷點數結果,事件本身不能確認退款。

只有 Public API 生成任務產生事件,Studio 任務與 Chat 回覆不產生。帳號存在啟用端點時才排入佇列,並僅投遞至啟用且訂閱該類型的端點。

本文是狀態介面公共生成欄位的快照;成功但待點數對帳的任務暫不產生成功事件。下例為已結算成功,ID、日期、URL 與點數僅為範例,不是目前模型價格。api_version 標識本文版本。

{
  "id": "evt_...",
  "type": "generation.succeeded",
  "api_version": "2026-05-11",
  "created_at": "2026-05-11T00:01:00.000Z",
  "data": {
    "generation": {
      "id": "task_public_id",
      "status": "succeeded",
      "model": "z-image",
      "reserved_credits": 1,
      "final_credits": 1,
      "settlement_status": "SETTLED",
      "created_at": "2026-05-11T00:00:00.000Z",
      "updated_at": "2026-05-11T00:01:00.000Z",
      "result": {
        "primary_url": "https://...",
        "urls": ["https://..."]
      },
      "error": null
    }
  }
}

Delivery Headers

每次投遞包含以下標頭,時間戳記為 Unix 秒,數值僅作範例:

Rivya-Webhook-Id: evt_...
Rivya-Webhook-Timestamp: 1778467200
Rivya-Webhook-Signature: v1=<hex-hmac-sha256>
Rivya-Webhook-Attempt: 1
Rivya-Webhook-Endpoint-Id: whend_...
Rivya-Request-Id: req_...

簽章輸入:

${timestamp}.${rawBody}

演算法:

使用端點簽章密鑰執行 HMAC-SHA256

按原樣使用時間戳記標頭,加上一個句點與未修改本文。先以 UTF-8 文字讀取,驗證簽章後再解析 JSON;不要用 JSON.stringify 重建、格式化或正規化字元。

拒絕比本機時鐘早或晚超過五分鐘的時間戳記。下例容差為 300 秒並以固定時間比較摘要;標頭名稱使用小寫、值為字串。

JavaScript Verification

import crypto from "node:crypto";

function verifyRivyaWebhook({ rawBody, headers, signingSecret }) {
  const timestamp = headers["rivya-webhook-timestamp"] || "";
  const signature = headers["rivya-webhook-signature"] || "";
  if (!/^[0-9]+$/.test(timestamp)) return false;

  const timestampSeconds = Number(timestamp);
  if (!Number.isSafeInteger(timestampSeconds)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - timestampSeconds) > 300) {
    return false;
  }

  const actual = signature
    .split(",")
    .map((part) => part.trim())
    .find((part) => part.startsWith("v1="))
    ?.slice(3);
  if (!actual || !/^[a-f0-9]{64}$/i.test(actual)) return false;

  const expected = crypto
    .createHmac("sha256", signingSecret)
    .update(`${timestamp}.${rawBody}`)
    .digest("hex");

  return crypto.timingSafeEqual(
    Buffer.from(actual, "hex"),
    Buffer.from(expected, "hex")
  );
}

Python Verification

import hashlib
import hmac
import re
import time

def verify_rivya_webhook(raw_body: str, headers: dict, signing_secret: str) -> bool:
    timestamp = headers.get("rivya-webhook-timestamp", "")
    signature = headers.get("rivya-webhook-signature", "")
    if not re.fullmatch(r"[0-9]+", timestamp):
        return False
    try:
        timestamp_seconds = int(timestamp)
    except ValueError:
        return False
    if abs(int(time.time()) - timestamp_seconds) > 300:
        return False

    parts = (part.strip() for part in signature.split(","))
    actual = next((part[3:] for part in parts if part.startswith("v1=")), "")
    if not re.fullmatch(r"[a-fA-F0-9]{64}", actual):
        return False

    expected = hmac.new(
        signing_secret.encode("utf-8"),
        f"{timestamp}.{raw_body}".encode("utf-8"),
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(actual.lower(), expected)

驗證簽章後解析本文,業務變更前按事件 id 排除重複。重試沿用事件 ID,但有新時間戳記、簽章與請求 ID;時間檢查不能取代重複偵測。

管理 Endpoints

GET /api/v1/webhooks
GET /api/v1/webhooks/{endpointId}
PATCH /api/v1/webhooks/{endpointId}
DELETE /api/v1/webhooks/{endpointId}
POST /api/v1/webhooks/{endpointId}/rotate-secret
curl https://rivya.ai/api/v1/webhooks \
  -H "Authorization: Bearer rvya_sk_..."

curl https://rivya.ai/api/v1/webhooks/whend_... \
  -H "Authorization: Bearer rvya_sk_..."

curl -X PATCH https://rivya.ai/api/v1/webhooks/whend_... \
  -H "Authorization: Bearer rvya_sk_..." \
  -H "Content-Type: application/json" \
  -d '{"status":"disabled"}'

curl -X POST https://rivya.ai/api/v1/webhooks/whend_.../rotate-secret \
  -H "Authorization: Bearer rvya_sk_..."

PATCH 可改 name、url、event_types、status,至少傳一個受支援欄位;狀態為 active 或 disabled,URL 與事件規則不變。DELETE /api/v1/webhooks/{endpointId} 停用端點,不刪除歷史。

金鑰缺失、無效、停用、過期或帳號無權使用 API 傳回 401;缺權限傳回 403;端點不存在或不屬帳號傳回 404;欄位或 URL 不合法傳回 400。錯誤封裝見API 錯誤與限制。

Delivery Records

查詢帳號最近的生成事件:

GET /api/v1/webhook-events
curl https://rivya.ai/api/v1/webhook-events \
  -H "Authorization: Bearer rvya_sk_..."

查詢端點投遞嘗試:

GET /api/v1/webhooks/{endpointId}/deliveries
curl https://rivya.ai/api/v1/webhooks/whend_.../deliveries \
  -H "Authorization: Bearer rvya_sk_..."

均按最新在前,預設 20 筆,正數 limit 最多 100,無分頁游標。事件紀錄含 status、attempts_count、投遞或重試時間;投遞紀錄含 status、http_status、attempt_number、request_id、duration_ms、截斷的 response_snippet、error_code、error_message。

Test Event

向啟用端點的註冊 URL 傳送一次測試投遞:

POST /api/v1/webhooks/{endpointId}/test
curl -X POST https://rivya.ai/api/v1/webhooks/whend_.../test \
  -H "Authorization: Bearer rvya_sk_..."

事件為 webhook.test,包含 data.ping: true 與端點 ID,沒有生成任務或真實結果 URL,不消耗生成點數。它會嘗試真實簽章 HTTP 投遞,接收端須與生成事件分開處理。

完成的管理呼叫傳回 HTTP 200 與結果;須檢查 status 的 success、failed、timeout 或 skipped,管理 API 的 200 不代表接收端接受。

結果直接傳回,不寫入事件或投遞清單;測試更新端點成功/失敗統計,不排入自動重試。

Retry Policy

只有收到 HTTP 2xx 且完成回應片段讀取,才算投遞成功。網路或回應讀取錯誤、逾時、重新導向及其他狀態都可能導致失敗。

每個生成事件最多五輪投遞,已記錄成功的端點在後續輪次略過。下一輪資格從上一輪結束後計時:

  • 第一輪:排入佇列時可投遞。

  • 第二輪:1 分鐘後。

  • 第三輪:5 分鐘後。

  • 第四輪:30 分鐘後。

  • 第五輪:2 小時後。

這是重試延遲,不是送達期限。佇列需要背景投遞程序執行,延遲或無法使用時會更晚。

目前所有啟用且訂閱的端點均有成功紀錄時為 delivered;次數用盡或沒有啟用訂閱端點時為 failed。事件失敗不代表每個端點失敗,其他端點可能已接受。投遞失敗不改變生成狀態、點數、退款或任務歷史。

安全清單

  • 處理前驗證 HMAC。

  • 拒絕過期時間戳記並按事件 ID 排除重複。

  • 分開處理測試與生成事件。

  • 不記錄完整簽章密鑰。

  • 接收端接受事件後才傳回 2xx。

  • 保留輪詢以核查遺漏或延遲。

相關頁面