PHP

HMAC Webhook Signature Verify

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Verify an inbound webhook (Stripe / GitHub / etc.) is genuine using HMAC-SHA256 and a shared secret. Includes timestamp tolerance to block replay attacks.
PHP
Raw
<?php
function verifyWebhookSig(string $rawBody, string $sigHeader, string $secret, int $tolerance = 300): bool {
    // Expecting header like: "t=1234567890,v1=abc123..."
    $parts = [];
    foreach (explode(',', $sigHeader) as $part) {
        if (str_contains($part, '=')) {
            [$k, $v] = explode('=', $part, 2);
            $parts[trim($k)] = trim($v);
        }
    }
    if (empty($parts['t']) || empty($parts['v1'])) return false;
    if (abs(time() - (int)$parts['t']) > $tolerance) return false;

    $signed   = $parts['t'] . '.' . $rawBody;
    $expected = hash_hmac('sha256', $signed, $secret);
    return hash_equals($expected, $parts['v1']);
}

$raw = file_get_contents('php://input');
$sig = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!verifyWebhookSig($raw, $sig, getenv('WEBHOOK_SECRET'))) {
    http_response_code(400); exit('Bad signature');
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.