Verify a webhook signature
Check that the call really came from the provider: matching signature and a fresh timestamp.
PHP · Verify a webhook signatureAdvanced
function verifyWebhook(string $rawBody, string $header, string $secret, int $tolerance = 300): bool
{
// header looks like: t=1730000000,v1=5257a869e7...
$parts = [];
foreach (explode(',', $header) as $piece) {
[$k, $v] = array_pad(explode('=', $piece, 2), 2, '');
$parts[trim($k)] = trim($v);
}
if (!isset($parts['t'], $parts['v1']) || abs(time() - (int)$parts['t']) > $tolerance) {
return false; // missing or too old (replay)
}
$expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, $secret);
return hash_equals($expected, $parts['v1']);
}
// In your webhook endpoint:
// $raw = file_get_contents('php://input'); // use the raw body, not json_decode()
// if (!verifyWebhook($raw, $_SERVER['HTTP_X_SIGNATURE'] ?? '', 'whsec_from_provider')) {
// http_response_code(400);
// exit;
// }webhookhmacapisecurity