Docs
文档目录

事件回调

这是什么 / 何时用

Webhooks 服务用于将项目内的领域事件(如数据库表/行增删改、存储桶文件上传、用户注册与会话登录、团队变更、函数部署执行等)以异步 HTTP POST 请求实时推送到外部业务系统的回调端点。它与平台内部的 Function 事件触发器相互独立,适合对接企业内部工单中心、审计归档服务、CRM/ERP 系统或计费对账流水线。

在企业智能客服与知识中台(如演示项目 enterprise-ai-hub-210)中,当 enterprise_biz_db.customer_tickets 表产生新工单(如 TK-20261022-001)或状态更新时,平台可通过配置的 Webhook 将事件载荷连同 HMAC 签名头(X-Agentbase-Webhook-Signature)投递给企业内部告警网关。

前置

使用骨架

  1. 初始化客户端与 Webhooks 服务:装载 APPBASE_ENDPOINT、APPBASE_PROJECT_ID 与具备 webhooks.write scope 的 APPBASE_API_KEY。

  2. 创建 Webhook(webhooks.create):指定唯一标识 webhookId、名称 name、回调地址 url、监听事件模式数组 events(最多 100 条,如 databases.*.tables.*.rows.*.create)、启用状态 enabled: true、TLS 证书校验 security: true 及可选的 HTTP Basic Auth 凭据(httpUser / httpPass)。

  3. 保存签名密钥并验签:通过受控渠道保存 signatureKey,不要写入日志。对配置 URL 经 rawurldecode 后的字节和原始请求体字节计算 HMAC-SHA1,并与 X-Agentbase-Webhook-Signature 比较。

  4. 日常巡检与密钥轮换(list / get / update / updateSignature / delete):通过 get 检查投递失败次数 attempts 与最近错误日志 logs;定期或怀疑泄露时调用 updateSignature 原子轮换 signatureKey。

关键参数与返回

方法全集与参数矩阵

SDK 方法(Node / Java)Python 方法Go 方法REST 端点必填参数可选参数返回模型
create({ webhookId, url, name, events, ... })create(...)Create(...)POST /v1/webhookswebhookId、url、name(≤128 字符)、events(1–100 条事件串)enabled(默认 true)、security(默认 false;设为 true 启用 TLS 校验)、httpUser、httpPassWebhook
list({ queries, total })(queries、total 均可选)list(...)List(...)GET /v1/webhooks无queries(分页/过滤)、total(默认 true)WebhookList
get({ webhookId })get(...)Get(...)GET /v1/webhooks/{webhookId}webhookId无Webhook
update({ webhookId, name, url, events, ... })update(...)Update(...)PUT /v1/webhooks/{webhookId}webhookId、name、url、eventsenabled(省略时写回 true 并重置失败次数)、security(省略时写回 false)、httpUser、httpPass(省略时分别写为空字符串)Webhook
updateSignature({ webhookId })update_signature(...)UpdateSignature(...)PATCH /v1/webhooks/{webhookId}/signaturewebhookId无Webhook(含新 signatureKey)
delete({ webhookId })delete(...)Delete(...)DELETE /v1/webhooks/{webhookId}webhookId无空(204)

Webhook 返回模型字段与回调请求头

类别字段 / 请求头类型说明
返回模型 Webhook$id / name / urlstringWebhook ID、名称与目标回调 URL。
返回模型 Webhookeventsstring[]订阅的平台事件通配符列表(如 ["databases.enterprise_biz_db.tables.customer_tickets.rows.*"])。
返回模型 Webhooksecurity / enabledboolean是否校验证书(true 强制校验证书有效性)与是否启用投递。
返回模型 WebhooksignatureKeystring平台生成的签名密钥,用于校验回调请求头 X-Agentbase-Webhook-Signature。
返回模型 Webhookattempts / logsinteger / string连续投递失败次数与最近一次投递失败的响应诊断日志。
回调 HTTP 请求头X-Agentbase-Webhook-Idstring触发本次投递的 Webhook ID。
回调 HTTP 请求头X-Agentbase-Webhook-Eventsstring本次匹配的事件名称列表(逗号分隔)。
回调 HTTP 请求头X-Agentbase-Webhook-Project-Idstring所属项目 ID(如 enterprise-ai-hub-210)。
回调 HTTP 请求头X-Agentbase-Webhook-User-Idstring触发事件的操纵者用户 ID(服务端 API Key 触发时为空)。
回调 HTTP 请求头X-Agentbase-Webhook-Signaturestringbase64(hmac_sha1(rawurldecode(configuredUrl) + rawBody, signatureKey)) 签名值。

错误与边界

SDK 类别差异

SDK 类别支持范围鉴权方式典型场景
Server SDK(Node.js / Java / Python / Go)全量 CRUD 与 updateSignature项目 API Key(webhooks.read / webhooks.write)后端服务自动注册回调、定期轮换签名密钥、巡检失败 Webhook
Console SDK(Node.js / Java / Python / Go)全量 CRUD 与 updateSignature管理面 Session / 短期 JWT控制台 Webhook 管理页面与运维脚本
Client / Web SDK(Web)无 Webhooks 服务—浏览器不可管理 Webhook

各语言调用示例

凭据:项目 API Key(webhooks.* scope)或 Console Session;浏览器不可用,无 Web 页签。

import { Client, Webhooks, AgentbaseException } from 'agentbase-node-sdk';
import { createHmac, timingSafeEqual } from 'node:crypto';

const client = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setKey(process.env.APPBASE_API_KEY!);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const webhooks = new Webhooks(client);

try {
    const hook = await webhooks.create({
        webhookId: 'wh_billing_events',
        url: 'https://example.com/hooks/agentbase',
        name: '计费与工单事件回调',
        events: ['databases.enterprise_biz_db.tables.customer_tickets.rows.*.create', 'databases.enterprise_biz_db.tables.customer_tickets.rows.*.update'],
        enabled: true,
        security: true,
    });
    // Store hook.signatureKey securely; never log it.
    console.log('Webhook created:', hook.$id);
} catch (err) {
    if (err instanceof AgentbaseException) {
        console.error(`Webhook request failed [${err.code} ${err.type}]`);
    }
    throw err;
}

// configuredUrl must be the exact saved URL; rawBody must be the original request bytes.
export function verifyWebhookSignature(configuredUrl: string, rawBody: Buffer, signatureHeader: string, signatureKey: string): boolean {
    const urlBytes = Buffer.from(configuredUrl, 'utf8');
    const decoded: number[] = [];
    for (let i = 0; i < urlBytes.length; i++) {
        if (urlBytes[i] === 37 && i + 2 < urlBytes.length) {
            const hex = urlBytes.subarray(i + 1, i + 3).toString('ascii');
            if (/^[0-9a-f]{2}$/i.test(hex)) {
                decoded.push(Number.parseInt(hex, 16));
                i += 2;
                continue;
            }
        }
        decoded.push(urlBytes[i]);
    }
    const expected = Buffer.from(createHmac('sha1', signatureKey)
        .update(Buffer.from(decoded)).update(rawBody).digest('base64'), 'ascii');
    const received = Buffer.from(signatureHeader, 'utf8');
    return expected.length === received.length && timingSafeEqual(expected, received);
}

示例指引