事件回调
这是什么 / 何时用
Webhooks 服务用于将项目内的领域事件(如数据库表/行增删改、存储桶文件上传、用户注册与会话登录、团队变更、函数部署执行等)以异步 HTTP POST 请求实时推送到外部业务系统的回调端点。它与平台内部的 Function 事件触发器相互独立,适合对接企业内部工单中心、审计归档服务、CRM/ERP 系统或计费对账流水线。
在企业智能客服与知识中台(如演示项目 enterprise-ai-hub-210)中,当 enterprise_biz_db.customer_tickets 表产生新工单(如 TK-20261022-001)或状态更新时,平台可通过配置的 Webhook 将事件载荷连同 HMAC 签名头(X-Agentbase-Webhook-Signature)投递给企业内部告警网关。
前置
客户端初始化与认证:
仅服务端与 Console 侧可用:需使用 Server SDK
Client(setEndpoint、setProject、setKey,API Key 需具备webhooks.read与webhooks.writescope)或 Console SDK(管理面 Session / 短期 JWT)。Client / Web SDK 不可用:浏览器端无权管理项目级 Webhook。
回调端点网络要求:使用实例可访问的 HTTP/HTTPS URL;创建和更新接口校验格式与域名。字面回环和私网 IP 在当前校验中会被拒绝;域名解析与出站边界需结合部署网络策略确认。接收端应及时返回
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,不要写入日志。对配置 URL 经rawurldecode后的字节和原始请求体字节计算 HMAC-SHA1,并与X-Agentbase-Webhook-Signature比较。日常巡检与密钥轮换(
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(默认 false;设为 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(省略时写回 true 并重置失败次数)、security(省略时写回 false)、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-Agentbase-Webhook-Signature。 |
返回模型 Webhook | attempts / logs | integer / string | 连续投递失败次数与最近一次投递失败的响应诊断日志。 |
| 回调 HTTP 请求头 | X-Agentbase-Webhook-Id | string | 触发本次投递的 Webhook ID。 |
| 回调 HTTP 请求头 | X-Agentbase-Webhook-Events | string | 本次匹配的事件名称列表(逗号分隔)。 |
| 回调 HTTP 请求头 | X-Agentbase-Webhook-Project-Id | string | 所属项目 ID(如 enterprise-ai-hub-210)。 |
| 回调 HTTP 请求头 | X-Agentbase-Webhook-User-Id | string | 触发事件的操纵者用户 ID(服务端 API Key 触发时为空)。 |
| 回调 HTTP 请求头 | X-Agentbase-Webhook-Signature | string | base64(hmac_sha1(rawurldecode(configuredUrl) + rawBody, signatureKey)) 签名值。 |
错误与边界
事件模式校验失败(
400 general_argument_invalid):events数组中的每条字符串必须匹配平台合法事件命名空间(如users.*、databases.*.tables.*.rows.*、buckets.*.files.*、functions.*),且单 Webhook 最多绑定 100 条事件规则。URL 校验失败(
400):检查 HTTP/HTTPS 格式和域名是否符合接口校验。不要把域名校验视为 DNS 解析或出站网络策略的替代。投递失败与消费端幂等:Worker 在 cURL 出错或 HTTP 状态码不小于
400时记录失败;3xx不会仅因非2xx被记为失败。连续失败达到系统上限后会禁用 Webhook 并记录logs;队列重试策略以部署配置为准。接收端应及时返回2xx,并按业务事件设计幂等处理。
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!)
.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);
}import io.agentbase.Client;
import io.agentbase.services.Webhooks;
import io.agentbase.exceptions.AgentbaseException;
import java.util.List;
Client client = new Client()
.setEndpoint(System.getenv("APPBASE_ENDPOINT"))
.setProject(System.getenv("APPBASE_PROJECT_ID"))
.setKey(System.getenv("APPBASE_API_KEY"));
client.setHttpClient(new okhttp3.OkHttpClient.Builder()
.followRedirects(false).followSslRedirects(false).build());
Webhooks webhooks = new Webhooks(client);
try {
var hook = webhooks.create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", List.of("databases.enterprise_biz_db.tables.customer_tickets.rows.*.create", "databases.enterprise_biz_db.tables.customer_tickets.rows.*.update"),
true, true, null, null);
// Store hook.getSignatureKey() securely; never log it.
System.out.println("Webhook created: " + hook.getId());
} catch (AgentbaseException e) {
System.err.println("Webhook request failed: " + e.getCode() + " " + e.getType());
}Python Server SDK 2.12.0 的默认请求可能在跳转时转发项目 API Key,暂不提供本段的 SDK 调用代码。使用本节的 REST 页签。
package main
import (
"errors"
"net/http"
"fmt"
"os"
"agentbase-go-sdk/agentbase"
)
func main() {
cl := agentbase.NewClient(
agentbase.WithEndpoint(os.Getenv("APPBASE_ENDPOINT")),
agentbase.WithProject(os.Getenv("APPBASE_PROJECT_ID")),
agentbase.WithKey(os.Getenv("APPBASE_API_KEY")),
)
cl.Client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error {
return errors.New("refuse redirects")
}
webhooks := agentbase.NewWebhooks(cl)
hook, err := webhooks.Create("wh_billing_events", "https://example.com/hooks/agentbase",
"计费事件回调", []string{"databases.enterprise_biz_db.tables.customer_tickets.rows.*.create", "databases.enterprise_biz_db.tables.customer_tickets.rows.*.update"},
webhooks.WithCreateEnabled(true), webhooks.WithCreateSecurity(true))
if err != nil {
fmt.Fprintln(os.Stderr, "Webhook request failed")
return
}
// Store hook.SignatureKey securely; never log it.
fmt.Println("Webhook created:", hook.Id)
}(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
umask 077
response_file=$(mktemp)
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS -X POST "$APPBASE_ENDPOINT/webhooks" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"webhookId":"wh_billing_events","name":"计费事件回调","url":"https://example.com/hooks/agentbase","events":["databases.enterprise_biz_db.tables.customer_tickets.rows.*.create"],"enabled":true,"security":true}' \
-o "$response_file"
# The response contains a signing key. Transfer it to secure storage and remove the temporary file.
)示例指引
JavaScript / TypeScript 全量示例:../examples/javascript.md
Python 全量示例:../examples/python.md
Java 全量示例:../examples/java.md
Go 全量示例:../examples/go.md