Webhooks

Check the signature

On this page

Anyone who knows your endpoint's address could post fake messages to it. Check the signature of every message, and ignore messages that fail.

How the signature works#

Every message carries the header X-GroKeeper-Signature with a time and one or two signatures:

X-GroKeeper-Signature: t=1763719200,v1=3b1d9c0f...
  1. Take the raw body exactly as you received it, before any JSON parsing. Changing even one space breaks the signature.
  2. Build the text {t}.{raw body}: the number after t=, a dot, then the body.
  3. Compute HMAC-SHA256 of that text with your endpoint's signing secret and write the result as lowercase hexadecimal.
  4. Compare it with each v1= value using a constant-time comparison. If any one matches, the message is genuine.
  5. Also reject messages whose t is more than 5 minutes away from your clock. A retry sent hours later still passes, because the time is renewed at every attempt.

There can be two v1= values while you rotate a secret: the old secret keeps signing for 24 hours so you can switch over without losing messages.

Working code#

<?php
// $secret is your endpoint's signing secret. Keep it out of your code: use a setting or an environment variable.
$secret  = getenv('GROKEEPER_WEBHOOK_SECRET');
$payload = file_get_contents('php://input');            // the RAW body, exactly as received
$header  = $_SERVER['HTTP_X_GROKEEPER_SIGNATURE'] ?? '';   // t=1763719200,v1=3b1d...

// Read the parts by hand, because v1 can appear twice while a secret is being rotated.
$t = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
    [$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
    if ($k === 't')  { $t = (int) $v; }
    if ($k === 'v1') { $signatures[] = $v; }
}

// Reject anything older (or newer) than 5 minutes.
if (!$t || abs(time() - $t) > 300) {
    http_response_code(400);
    exit('timestamp too old');
}

$expected = hash_hmac('sha256', $t . '.' . $payload, $secret);
$ok = false;
foreach ($signatures as $s) {
    $ok = $ok || hash_equals($expected, $s);
}
if (!$ok) {
    http_response_code(400);
    exit('bad signature');
}

$event = json_decode($payload, true);   // $event['id'], $event['type'], $event['data']
http_response_code(200);                // answer with 2xx quickly; do the slow work afterwards

Check your code with a test value#

Use these made-up values to confirm your code produces the same signature. The secret is not a real one.

ItemValue
Secretwhsec_example
Time (t)1763719200
Raw body{"id":"evt_example0001","type":"order.paid"}
Expected headerX-GroKeeper-Signature: t=1763719200,v1=3f1ac112b6131d00e3b5311eeb658a24cabfb00fb51f4a0ccb2fe13cd5c7a6e0

Important

Never put your real signing secret in a web page, a repository or an email. It is shown once when the endpoint is created or rotated.