事件回调
这是什么 / 何时用
Webhooks 服务用于将项目内的领域事件(如数据库表/行增删改、存储桶文件上传、用户注册与会话登录、团队变更、函数部署执行等)以异步 HTTP POST 请求实时推送到外部业务系统的回调端点。它与平台内部的 Function 事件触发器相互独立,适合对接企业内部工单中心、审计归档服务、CRM/ERP 系统或计费对账流水线。
在企业智能客服与知识中台(如演示项目 enterprise-ai-hub-210)中,当 enterprise_biz_db.customer_tickets 表产生新工单(如 TK-20261022-001)或状态更新时,平台可通过配置的 Webhook 将事件载荷连同 HMAC 签名头(X-Appwrite-Webhook-Signature)投递给企业内部告警网关。
前置
客户端初始化与认证:
仅服务端与 Console 侧可用:需使用 Server SDK
Client(setEndpoint、setProject、setKey,API Key 需具备webhooks.read与webhooks.writescope)或 Console SDK(管理面 Session / 短期 JWT)。Client / Web SDK 不可用:浏览器端无权管理项目级 Webhook。
回调端点网络要求:目标
url必须是公网或实例网络可达的 HTTP/HTTPS 地址(且受 2.6.0+ SSRF 防护约束,拒绝回环地址127.0.0.1、私网网段与云厂商元数据地址),并应在数秒内返回2xx状态码。
使用骨架
初始化客户端与
Webhooks服务:装载APPBASE_ENDPOINT、APPBASE_PROJECT_ID与具备webhooks.writescope 的APPBASE_API_KEY。创建 Webhook(
webhooks.create):指定唯一标识webhookId、名称name、回调地址url、监听事件模式数组events(最多 100 条,如databases.*.tables.*.rows.create)、启用状态enabled: true、TLS 证书校验security: true及可选的 HTTP Basic Auth 凭据(httpUser/httpPass)。保存签名密钥并验签:从创建或详情响应中读取
signatureKey,在接收端 HTTP 服务中结合请求头X-Appwrite-Webhook-Signature对原始请求体做 HMAC-SHA1 签名比对,拒绝伪造请求。日常巡检与密钥轮换(
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/webhooks | webhookId、url、name(≤128 字符)、events(1–100 条事件串) | enabled(默认 true)、security(默认 true,校验远端 TLS 证书)、httpUser、httpPass | Webhook |
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、events | enabled、security、httpUser、httpPass | Webhook |
updateSignature({ webhookId }) | update_signature(...) | UpdateSignature(...) | PATCH /v1/webhooks/{webhookId}/signature | webhookId | 无 | Webhook(含新 signatureKey) |
delete({ webhookId }) | delete(...) | Delete(...) | DELETE /v1/webhooks/{webhookId} | webhookId | 无 | 空(204) |
Webhook 返回模型字段与回调请求头
| 类别 | 字段 / 请求头 | 类型 | 说明 |
|---|---|---|---|
返回模型 Webhook | $id / name / url | string | Webhook ID、名称与目标回调 URL。 |
返回模型 Webhook | events | string[] | 订阅的平台事件通配符列表(如 ["databases.enterprise_biz_db.tables.customer_tickets.rows.*"])。 |
返回模型 Webhook | security / enabled | boolean | 是否校验证书(true 强制校验证书有效性)与是否启用投递。 |
返回模型 Webhook | signatureKey | string | 平台生成的签名密钥,用于校验回调请求头 X-Appwrite-Webhook-Signature。 |
返回模型 Webhook | attempts / logs | integer / string | 连续投递失败次数与最近一次投递失败的响应诊断日志。 |
| 回调 HTTP 请求头 | X-Appwrite-Webhook-Id | string | 触发本次投递的 Webhook ID。 |
| 回调 HTTP 请求头 | X-Appwrite-Webhook-Events | string | 本次匹配的事件名称列表(逗号分隔)。 |
| 回调 HTTP 请求头 | X-Appwrite-Webhook-Project-Id | string | 所属项目 ID(如 enterprise-ai-hub-210)。 |
| 回调 HTTP 请求头 | X-Appwrite-Webhook-User-Id | string | 触发事件的操纵者用户 ID(服务端 API Key 触发时为空)。 |
| 回调 HTTP 请求头 | X-Appwrite-Webhook-Signature | string | base64(hmac_sha1(url + rawBody, signatureKey)) 签名值。 |
错误与边界
事件模式校验失败(
400 general_argument_invalid):events数组中的每条字符串必须匹配平台合法事件命名空间(如users.*、databases.*.tables.*.rows.*、buckets.*.files.*、functions.*),且单 Webhook 最多绑定 100 条事件规则。外部 URL SSRF 拦截(
400):2.6.0+ 默认开启 SSRF 防护,url若指向localhost、127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16或169.254.169.254将被拒绝。投递重试、自动熔断与消费端幂等:当回调端点返回非
2xx或超时,后台webhooks队列 Worker 会按指数退避重试;若连续失败次数(attempts)达到系统上限,该 Webhook 将被自动置为enabled: false并记录logs。接收端应先将请求入本地队列并立即返回200 OK,同时按事件载荷中的资源$id+$updatedAt做幂等去重。
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 页签。
- Node.js(Server)
- Java
- Python
- Go
- REST(curl)
import { Client, Webhooks, AgentbaseException } from 'agentbase-node-sdk';
import { createHmac, timingSafeEqual } from 'node:crypto';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT ?? 'https://appbuild-sit.oceanbase.com/v1')
.setProject(process.env.APPBASE_PROJECT_ID ?? 'enterprise-ai-hub-210')
.setKey(process.env.APPBASE_API_KEY!);
const webhooks = new Webhooks(client);
try {
// 1. 创建工单与计费事件回调
const hook = await webhooks.create({
webhookId: 'wh_billing_events',
url: 'https://example.com/hooks/agentbase',
name: '计费与工单事件回调',
events: ['databases.tables.update', 'databases.collections.update'],
enabled: true,
security: true, // 强制校验目标 HTTPS 证书并用返回的 signatureKey 校验签名
});
console.log('Webhook 创建成功, signatureKey:', hook.signatureKey);
// 2. 列出并轮换签名密钥(REST 对应 PATCH /v1/webhooks/{webhookId}/signature)
const list = await webhooks.list();
const rotated = await webhooks.updateSignature({ webhookId: 'wh_billing_events' });
console.log('当前 Webhook 总数:', list.total, '轮换后新密钥长度:', rotated.signatureKey.length);
} catch (err) {
if (err instanceof AgentbaseException) {
console.error(`Webhooks 调用失败 [${err.code} ${err.type}]: ${err.message}`);
}
throw err;
}
// 附:接收端校验 X-Appwrite-Webhook-Signature 的工具函数
export function verifyWebhookSignature(webhookUrl: string, rawBody: string, signatureHeader: string, signatureKey: string): boolean {
const expected = createHmac('sha1', signatureKey).update(webhookUrl + rawBody).digest('base64');
return expected.length === signatureHeader.length &&
timingSafeEqual(Buffer.from(expected), Buffer.from(signatureHeader));
}import io.agentbase.Client;
import io.agentbase.services.Webhooks;
import io.agentbase.exceptions.AppBaseException;
import java.util.List;
Client client = new Client()
.setEndpoint("https://appbuild-sit.oceanbase.com/v1")
.setProject("enterprise-ai-hub-210")
.setKey(System.getenv("APPBASE_API_KEY"));
Webhooks webhooks = new Webhooks(client);
try {
var hook = webhooks.create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", List.of("databases.tables.update", "databases.collections.update"),
true, true, null, null); // enabled / security;可选 httpUser / httpPass
var list = webhooks.list(null, true); // get / update / delete 维护同一个 webhook
var rotated = webhooks.updateSignature("wh_billing_events"); // 轮换签名密钥
System.out.println("Total=" + list.getTotal() + ", sigKey=" + rotated.getSignatureKey());
} catch (AppBaseException e) {
System.err.println("HTTP " + e.getCode() + " type=" + e.getType() + ": " + e.getMessage());
}import os
from agentbase.client import Client
from agentbase.services.webhooks import Webhooks
from agentbase.exception import AgentbaseException
client = (
Client()
.set_endpoint(os.environ.get('APPBASE_ENDPOINT', 'https://appbuild-sit.oceanbase.com/v1'))
.set_project(os.environ.get('APPBASE_PROJECT_ID', 'enterprise-ai-hub-210'))
.set_key(os.environ['APPBASE_API_KEY'])
)
webhooks = Webhooks(client)
try:
hook = webhooks.create(
webhook_id='wh_billing_events',
url='https://example.com/hooks/agentbase',
name='计费事件回调',
events=['databases.tables.update', 'databases.collections.update'],
enabled=True,
security=True,
)
listed = webhooks.list()
rotated = webhooks.update_signature(webhook_id='wh_billing_events')
print(listed.total, rotated.signature_key)
except AgentbaseException as exc:
print(f"Webhooks error {exc.code} ({exc.type}): {exc.message}")package main
import (
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint("https://appbuild-sit.oceanbase.com/v1"),
agentbase.WithProject("enterprise-ai-hub-210"),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
)
webhooks := agentbase.NewWebhooks(cl)
hook, _ := webhooks.Create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", []string{"databases.tables.update", "databases.collections.update"},
webhooks.WithCreateEnabled(true),
webhooks.WithCreateSecurity(true), // 平台推送带签名头,用返回的 signatureKey 校验来源
)
list, _ := webhooks.List() // Get / Update / Delete 维护同一个 webhook
rotated, _ := webhooks.UpdateSignature("wh_billing_events")
fmt.Println(hook.Id, list.Total, rotated.SignatureKey)
}# 1. 创建 Webhook(POST /v1/webhooks)
curl -sS -X POST "$APPBASE_ENDPOINT/webhooks" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"webhookId": "wh_billing_events",
"name": "计费事件回调",
"url": "https://example.com/hooks/agentbase",
"events": ["databases.tables.update", "databases.collections.update"],
"enabled": true,
"security": true,
"httpUser": "hook-user",
"httpPass": "hook-pass"
}'
# 2. 查询 Webhook 列表与详情(GET /v1/webhooks、GET /v1/webhooks/{webhookId})
curl -sS "$APPBASE_ENDPOINT/webhooks/wh_billing_events" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY"
# 3. 轮换 Webhook 签名密钥(PATCH /v1/webhooks/{webhookId}/signature)
curl -sS -X PATCH "$APPBASE_ENDPOINT/webhooks/wh_billing_events/signature" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY"示例指引
JavaScript / TypeScript 全量示例:../examples/javascript.md
Python 全量示例:../examples/python.md
Java 全量示例:../examples/java.md
Go 全量示例:../examples/go.md