Webhooks
每次变更都会发送带签名、可重试的通知,以及如何正确接收。
添加一个地址并选择它需要的事件。每个事件以 POST 请求发送,正文是一小段 JSON:发生了什么、涉及哪条记录。需要详情时,用您的密钥获取该记录。
POST /webhooks HTTP/1.1
Content-Type: application/json
webhook-id: msg_01JD3XC4Q8F2N6R0T4V8X2Z6B0
webhook-timestamp: 1764576000
webhook-signature: v1,g0hM9SsE+OTPJTGt/tmIKtSyZlE3uFJELVlNIOLJ1OE=校验签名
每个请求都按 Standard Webhooks 方式用该地址的签名密钥签名。如果签名不符,或时间戳超过五分钟,请拒绝该请求。
import crypto from "node:crypto";
export function verify(rawBody, headers, secret, toleranceSec = 300) {
const id = headers["webhook-id"], ts = headers["webhook-timestamp"], sig = headers["webhook-signature"];
if (!id || !ts || !sig || Math.abs(Date.now() / 1000 - Number(ts)) > toleranceSec) return false;
const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
const expected = crypto.createHmac("sha256", key).update(`${id}.${ts}.${rawBody}`).digest("base64");
return sig.split(" ").some((p) => {
const [v, s] = p.split(",");
return v === "v1" && s && s.length === expected.length && crypto.timingSafeEqual(Buffer.from(s), Buffer.from(expected));
});
}<?php
function verify(string $rawBody, array $headers, string $secret, int $toleranceSec = 300): bool
{
$id = $headers['webhook-id'] ?? null;
$ts = $headers['webhook-timestamp'] ?? null;
$sig = $headers['webhook-signature'] ?? null;
if (!$id || !$ts || !$sig || abs(time() - (int) $ts) > $toleranceSec) {
return false;
}
$key = base64_decode(preg_replace('/^whsec_/', '', $secret));
$expected = base64_encode(hash_hmac('sha256', "{$id}.{$ts}.{$rawBody}", $key, true));
foreach (explode(' ', $sig) as $part) {
[$version, $signature] = array_pad(explode(',', $part, 2), 2, '');
if ($version === 'v1' && hash_equals($expected, $signature)) {
return true;
}
}
return false;
}import base64, hashlib, hmac, time
def verify(raw_body: bytes, headers: dict, secret: str, tolerance_sec: int = 300) -> bool:
msg_id = headers.get("webhook-id")
ts = headers.get("webhook-timestamp")
sig = headers.get("webhook-signature")
if not msg_id or not ts or not sig or abs(time.time() - int(ts)) > tolerance_sec:
return False
key = base64.b64decode(secret.removeprefix("whsec_"))
signed = f"{msg_id}.{ts}.".encode() + raw_body
expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
return any(
part.split(",", 1)[0] == "v1" and hmac.compare_digest(part.split(",", 1)[1], expected)
for part in sig.split(" ") if "," in part
)重试与顺序
- 在五秒内返回 2xx,之后再处理。
- 投递失败会在约 32 小时内重试八次。不会跟随重定向。
- 同一事件可能到达两次:跳过已处理过的 webhook-id。
- 事件到达顺序可能错乱:获取记录以得知其当前状态。
- 连续三天失败的地址会被停用;修复后可在后台重放错过的事件。
安全清单
- 使用带有效证书的 https。
- 在解析之前,基于原始请求体校验签名。
- 签名密钥只放在服务器上,泄露时立即轮换。