Verifying Webhook Signatures
The signature format follows the Standard Webhooks specification. You can verify with that project's official libraries for each language, or implement the algorithm below yourself.
Headers
| Header | Value |
|---|---|
webhook-id | The event ID, the same as id in the body. It doesn't change when the event is retried or resent |
webhook-timestamp | The Unix time in seconds when the request is sent. It is updated on every attempt |
webhook-signature | v1,<Base64>. During secret rotation there are two signatures, separated by a space |
Signature algorithm
- The signing secret is the endpoint's
whsec_…string. Remove thewhsec_prefix and Base64-decode the rest into bytes. Those bytes are the HMAC key. - The string to sign is
{webhook-id}.{webhook-timestamp}.{raw body}. - The signature is the HMAC-SHA256 of that string, Base64-encoded, with
v1,in front.
Verification steps
- Read the raw bytes of the request. The signature is computed over the bytes that were sent, which can differ from a body that was parsed as JSON and encoded again.
- Check that all three headers are present.
- Reject the request if
webhook-timestampdiffers from the current time by more than 5 minutes. - Compute the signature with the algorithm above.
- Split
webhook-signatureon spaces. If any one of the signatures matches the computed value (a constant-time comparison is recommended), the request passes.
Secret rotation
After you rotate the secret in the dashboard, the old secret stays valid for 24 more hours. During that time webhook-signature contains two signatures, with the new secret's first. Verifying with either the new or the old secret succeeds. If you rotate again within the 24 hours, the oldest secret stops working immediately.
Code examples
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();
// Use express.raw to get the unparsed raw bytes
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'));
// Deduplicate by event.id, then handle 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;
}
// Raw bytes: php://input, not $_POST or re-encoded 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);
// Deduplicate by $event['id'], then handle $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():
# Use request.get_data() to get the unparsed raw bytes
raw_body = request.get_data()
if not verify(request.headers, raw_body):
return "", 400
event = json.loads(raw_body)
# Deduplicate by event["id"], then handle event["type"] …
return "", 200