Webhooks 通过 HTTP POST 请求向您的应用程序发送实时事件通知。使用它们来响应支付、策略违规、代理状态变更和 x402 会话事件。
设置 Webhooks
通过 SDK
const webhook = await aw.webhooks.create({
url: "https://your-app.com/webhooks/agentwallex",
events: [
"payment.completed",
"payment.failed",
"agent.frozen",
"policy.violated",
],
secret: "whsec_your_signing_secret",
});
通过 API
curl -X POST https://api.agentwallex.com/api/v1/webhooks \
-H "X-API-Key: awx_your_api_key" \
-H "Content-Type: application/json" \
-d '{
"url": "https://your-app.com/webhooks/agentwallex",
"events": ["payment.completed", "payment.failed", "agent.frozen", "policy.violated"],
"secret": "whsec_your_signing_secret"
}'
事件类型
| 事件 | 说明 |
|---|
payment.completed | 交易已在链上确认 |
payment.failed | 交易失败或已回滚 |
payment.pending | 交易已提交,等待确认 |
agent.frozen | 代理钱包已被冻结 |
agent.unfrozen | 代理钱包已被解冻 |
policy.violated | 交易被策略引擎拒绝 |
x402.session.expired | x402 会话预算或 TTL 已超限 |
approval.requested | 高价值交易等待人工审批 |
Webhook 载荷
每次 Webhook 投递都包含以下结构的 JSON 载荷:
{
"id": "evt_abc123",
"type": "payment.completed",
"created_at": "2025-06-15T14:30:00Z",
"data": {
"transaction_id": "tx_xyz789",
"agent_id": "agent_abc123",
"amount": "50.00",
"token": "USDC",
"chain": "eip155:8453",
"hash": "0xabc...def",
"status": "confirmed"
}
}
签名验证
每次 Webhook 投递都包含用于验证的签名头部。在处理 Webhook 事件之前,请务必验证签名。
工作原理
AgentWallex 使用您在注册时提供的密钥对每个 Webhook 载荷进行签名。签名通过 X-AgentWallex-Signature 头部发送。
验证示例
import crypto from "crypto";
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expected = crypto
.createHmac("sha256", secret)
.update(payload)
.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
// In your webhook handler
app.post("/webhooks/agentwallex", (req, res) => {
const signature = req.headers["x-agentwallex-signature"] as string;
const isValid = verifyWebhookSignature(
JSON.stringify(req.body),
signature,
"whsec_your_signing_secret"
);
if (!isValid) {
return res.status(401).send("Invalid signature");
}
// Process the event
const event = req.body;
console.log(`Received ${event.type} event`);
res.status(200).send("OK");
});
验证签名时请始终使用常量时间比较(例如 timingSafeEqual 或 hmac.compare_digest),以防止时序攻击。
测试 Webhooks
向您的 Webhook 端点发送测试事件:
curl -X POST https://api.agentwallex.com/api/v1/webhooks/whk_abc123/test \
-H "X-API-Key: awx_your_api_key"
查看投递记录
检查 Webhook 的投递历史:
curl -X GET https://api.agentwallex.com/api/v1/webhooks/whk_abc123/deliveries \
-H "X-API-Key: awx_your_api_key"
管理 Webhooks
# List all webhooks
GET /webhooks
# Get a specific webhook
GET /webhooks/:id
# Update a webhook
PUT /webhooks/:id
# Delete a webhook
DELETE /webhooks/:id
最佳实践
在 5 秒内以 2xx 状态码响应 Webhook 投递。如果您的处理程序需要进行较重的处理,请立即确认 Webhook 并异步处理。
- 始终验证签名 — 在处理事件之前验证签名。
- 处理重复投递 — Webhook 投递可能会被重试。使用
id 字段实现幂等性。
- 快速返回 200 — 在进行较重处理之前确认接收。
- 监控投递失败 — 检查投递端点以了解失败的投递。
- 使用特定的事件过滤器 — 仅订阅您需要的事件,而非接收所有事件。