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 秒內回應 webhook 傳送並回傳 2xx 狀態碼。如果您的處理程式需要進行繁重處理,請立即確認 webhook 並非同步處理。
- 始終驗證簽名 — 在處理事件前驗證簽名。
- 處理重複事件 — Webhook 傳送可能會重試。使用
id 欄位確保冪等性。
- 快速回傳 200 — 在進行繁重處理前先確認接收。
- 監控傳送失敗 — 檢查傳送端點以了解失敗的傳送。
- 使用特定事件過濾器 — 僅訂閱您需要的事件,而非接收所有事件。