驗證 Webhook 簽章
簽章格式遵循 Standard Webhooks 規範。可以用該專案提供的各語言官方套件驗證,也可以照下面的算法自己實作。
標頭
| 標頭 | 值 |
|---|---|
webhook-id | 事件 ID,與內容的 id 相同。同一則事件重試與重新傳送時不變 |
webhook-timestamp | 送出當下的 Unix 秒數。每次嘗試都會更新 |
webhook-signature | v1,<Base64>。密鑰輪替期間是兩個簽章,以空白分隔 |
簽章算法
- 簽章密鑰是端點的
whsec_…字串:去掉whsec_前綴後,以 Base64 解碼成位元組,作為 HMAC 的金鑰。 - 要簽的字串是
{webhook-id}.{webhook-timestamp}.{原始內容}。 - 簽章是這個字串的 HMAC-SHA256,再以 Base64 編碼,前面加上
v1,。
驗證步驟
- 讀取請求的原始位元組。簽章算的是送出的位元組,內容經過 JSON 解析再編碼後可能不同。
- 確認三個標頭都存在。
webhook-timestamp與現在時間相差超過 5 分鐘就拒收。- 依上面的算法算出簽章。
webhook-signature以空白分隔成多個簽章,其中任一個與算出的值相符(建議用固定時間比較)就通過。
密鑰輪替
在後台輪替密鑰後,舊密鑰再有效 24 小時。這段期間 webhook-signature 有兩個簽章,新密鑰在前。用新密鑰或舊密鑰任一把驗證都會通過。24 小時內再輪替一次時,最早的那把密鑰立即失效。
程式範例
js
import crypto from 'node:crypto';
import express from 'express';
const SECRET = process.env.DOLYU_WEBHOOK_SECRET; // whsec_…
const TOLERANCE_SECONDS = 5 * 60;
function verify(headers, rawBody) {
const id = headers['webhook-id'];
const timestamp = headers['webhook-timestamp'];
const signatures = headers['webhook-signature'];
if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
const now = Math.floor(Date.now() / 1000);
if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false;
const key = Buffer.from(SECRET.replace(/^whsec_/, ''), 'base64');
const expected = crypto
.createHmac('sha256', key)
.update(`${id}.${timestamp}.`)
.update(rawBody)
.digest();
return signatures.split(' ').some((entry) => {
const [version, value] = entry.split(',');
if (version !== 'v1' || !value) return false;
const given = Buffer.from(value, 'base64');
return given.length === expected.length && crypto.timingSafeEqual(given, expected);
});
}
const app = express();
// 用 express.raw 取得未解析的原始位元組
app.post('/dolyu-webhook', express.raw({ type: 'application/json' }), (req, res) => {
if (!verify(req.headers, req.body)) return res.sendStatus(400);
const event = JSON.parse(req.body.toString('utf8'));
// 以 event.id 去重後處理 event.type …
res.sendStatus(200);
});
app.listen(3000);php
<?php
const TOLERANCE_SECONDS = 300;
function verifyDolyuWebhook(string $secret, string $id, string $timestamp, string $signatures, string $rawBody): bool
{
if ($id === '' || $signatures === '' || ! ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > TOLERANCE_SECONDS) {
return false;
}
$key = base64_decode(substr($secret, strlen('whsec_')), true);
if ($key === false || $key === '') {
return false;
}
$expected = hash_hmac('sha256', "{$id}.{$timestamp}.{$rawBody}", $key, true);
foreach (explode(' ', $signatures) as $entry) {
[$version, $value] = array_pad(explode(',', $entry, 2), 2, '');
$given = base64_decode($value, true);
if ($version === 'v1' && $given !== false && hash_equals($expected, $given)) {
return true;
}
}
return false;
}
// 原始位元組:php://input,不要用 $_POST 或重新編碼過的 JSON
$rawBody = file_get_contents('php://input');
$ok = verifyDolyuWebhook(
getenv('DOLYU_WEBHOOK_SECRET'), // whsec_…
$_SERVER['HTTP_WEBHOOK_ID'] ?? '',
$_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
$_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
$rawBody,
);
if (! $ok) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
// 以 $event['id'] 去重後處理 $event['type'] …
http_response_code(200);python
import base64
import hashlib
import hmac
import json
import os
import time
from flask import Flask, request
SECRET = os.environ["DOLYU_WEBHOOK_SECRET"] # whsec_…
TOLERANCE_SECONDS = 5 * 60
app = Flask(__name__)
def verify(headers, raw_body: bytes) -> bool:
event_id = headers.get("webhook-id", "")
timestamp = headers.get("webhook-timestamp", "")
signatures = headers.get("webhook-signature", "")
if not event_id or not signatures or not (timestamp.isascii() and timestamp.isdigit()):
return False
if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
return False
key = base64.b64decode(SECRET.removeprefix("whsec_"))
signed = f"{event_id}.{timestamp}.".encode() + raw_body
expected = hmac.new(key, signed, hashlib.sha256).digest()
for entry in signatures.split(" "):
version, _, value = entry.partition(",")
if version != "v1":
continue
try:
given = base64.b64decode(value, validate=True)
except ValueError:
continue
if hmac.compare_digest(given, expected):
return True
return False
@app.post("/dolyu-webhook")
def dolyu_webhook():
# 用 request.get_data() 取得未解析的原始位元組
raw_body = request.get_data()
if not verify(request.headers, raw_body):
return "", 400
event = json.loads(raw_body)
# 以 event["id"] 去重後處理 event["type"] …
return "", 200