Webhook 验证
概述
当用户回复消息时,BotBell 会通过 HTTP POST 将回复发送到你的 reply_url。验证签名以确保请求是真实的。
| 签名 Header | X-Webhook-Signature: sha256=... |
| 时间戳 Header | X-Webhook-Timestamp: 1234567890 |
工作原理
- 从 Header 中提取 X-Webhook-Timestamp 和 X-Webhook-Signature
- 检查时间戳是否在 5 分钟内(防止重放攻击)
- 用 webhook_secret 计算 {timestamp}.{body} 的 HMAC-SHA256
- 与签名进行比较(常量时间比较)
signature = HMAC-SHA256(
key: webhook_secret,
message: "{timestamp}.{request_body}"
)Python
from botbell import verify_webhook, WebhookVerificationError
try:
verify_webhook(
body=request.body,
signature_header=request.headers["X-Webhook-Signature"],
timestamp_header=request.headers["X-Webhook-Timestamp"],
secret="your_webhook_secret",
)
except WebhookVerificationError:
return {"error": "Invalid signature"}, 401
# Signature valid — process the reply
data = json.loads(request.body)JavaScript
import { verifyWebhook, WebhookVerificationError } from "@botbell/sdk";
try {
verifyWebhook({
body: req.body,
signature: req.headers["x-webhook-signature"],
timestamp: req.headers["x-webhook-timestamp"],
secret: "your_webhook_secret",
});
} catch (e) {
if (e instanceof WebhookVerificationError) {
return res.status(401).json({ error: e.message });
}
throw e;
}
// Signature valid — process the reply
const data = JSON.parse(req.body);