↓
Rivya AI 文档

API Webhooks

配置 Rivya API 生成事件 Webhook,校验 HMAC 签名,查询投递记录,发送测试事件并处理重试。

最近审阅于 2026年11月5日

当你的集成希望在 Public API 生成任务进入终态后由 Rivya 主动通知你的服务端,可以使用 API webhooks。

GET /api/v1/generations/{taskId} 轮询仍然可用。Webhook 适合希望通过事件投递接收结果的生产系统。

所需 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 秒。

事件类型

支持以下生成事件:

  • 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
    }
  }
}

投递 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 验签

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 验签

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 错误与限制。

投递记录

查询账号最近的生成事件:

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。

测试事件

向启用端点的注册 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 不代表接收端接受。

结果直接返回,不写入事件或投递列表;测试更新端点成功/失败统计,不排入自动重试。

重试策略

只有收到 HTTP 2xx 且完成响应片段读取,才算投递成功。网络或响应读取错误、超时、重定向及其他状态都可能导致失败。

每个生成事件最多五轮投递,已记录成功的端点在后续轮次跳过。下一轮资格从上一轮结束后计时:

  • 第一轮:入队时可投递。

  • 第二轮:1 分钟后。

  • 第三轮:5 分钟后。

  • 第四轮:30 分钟后。

  • 第五轮:2 小时后。

这是重试延迟,不是送达时限。队列需要后台投递进程运行,延迟或不可用时会更晚。

当前所有启用且订阅的端点均有成功记录时为 delivered;次数用尽或没有启用订阅端点时为 failed。事件失败不代表每个端点失败,其他端点可能已接受。投递失败不改变生成状态、积分、退款或任务历史。

安全清单

  • 处理前验证 HMAC。

  • 拒绝过期时间戳并按事件 ID 去重。

  • 分开处理测试与生成事件。

  • 不记录完整签名密钥。

  • 接收端接受事件后才返回 2xx。

  • 保留轮询以核查遗漏或延迟。

相关页面