Skip to content

Verify webhook signatures ​

Every delivery is signed with the endpoint's secret. Verify the signature before you trust anything in the body. Without it, anyone who learns your endpoint's address can post a payment.succeeded to it.

The scheme ​

PartValue
KeyThe endpoint secret, the whole string including whsec_ (54 characters), used as UTF-8 bytes
MessageThe X-Mookh-Timestamp header value, a ., then the raw request body exactly as it arrived
AlgorithmHMAC-SHA256
HeaderX-Mookh-Signature: sha256= followed by the digest as 64 lowercase hex characters. For 24 hours after a rotation, two such values separated by , , newest first
text
signature = "sha256=" + hex(HMAC_SHA256(key = secret, message = timestamp + "." + raw_body))

The timestamp is inside what is signed. A captured delivery cannot be replayed later under a new timestamp, so refusing old timestamps stops replays.

More than one signature ​

When you rotate an endpoint's secret, MOOKHPay signs every delivery with both the new and the old secret for the next 24 hours, and sends both signatures in the one header, newest first:

text
X-Mookh-Signature: sha256=4cf8c00652d35d07fb42405acfd1da77b69218599bec3dcc57dcf7d5eea3278e, sha256=7ab6a0cf9a774ccfe177fd9814d5d10e4db972b4e0a46374bacefc28586e9480

Both are made the same way, over the same timestamp and body; only the key differs. Split the header on ,, trim the spaces from each part, and accept the delivery if any one part matches the signature you compute, comparing each in constant time. That way your receiver keeps working whether it holds the new secret or the old one, and you can deploy the new secret at any point in the 24 hours.

Outside a rotation the header holds one signature, and the same code handles it. Never expect a fixed number of signatures, and never require all of them to match: your server holds one secret, so only one can.

Verify a delivery ​

  1. Read the raw body as bytes, before any JSON parser touches it.
  2. Read X-Mookh-Timestamp. Refuse it unless it is all digits and within your tolerance of your own clock. 300 seconds either way is a sensible choice; MOOKHPay sets the header when it sends each attempt.
  3. Compute sha256= and the hex HMAC-SHA256 of the timestamp, ., and the raw body, with your secret.
  4. Split X-Mookh-Signature on , and trim each part. Compare your value with each part in constant time. Refuse unless one of them matches.
  5. Only then parse the body as JSON.

Answer 400 (or any non-2xx) to a delivery that fails verification. A genuine delivery that you refused will be retried, so a clock or code mistake on your side does not lose events while you fix it.

Code ​

sh
# Check a signature by hand: the output must equal X-Mookh-Signature,
# or one of the comma-separated values in it during a rotation.
TS="1763635200"
BODY='{"event":"payment.succeeded"}'
printf '%s' "$TS.$BODY" \
  | openssl dgst -sha256 -hmac "$MOOKHPAY_WEBHOOK_SECRET" \
  | sed 's/^.* /sha256=/'
js
import { createHmac, timingSafeEqual } from "node:crypto";

// rawBody must be a Buffer of the bytes as received.
// With Express: app.post("/mookhpay/webhooks", express.raw({ type: "application/json" }), ...)
// and pass req.body (a Buffer).
export function verifyWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
  const timestamp = headers["x-mookh-timestamp"];
  const received = headers["x-mookh-signature"];
  if (typeof timestamp !== "string" || typeof received !== "string") return false;
  if (!/^\d+$/.test(timestamp)) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;

  const expected = Buffer.from(
    "sha256=" +
      createHmac("sha256", secret)
        .update(`${timestamp}.`)
        .update(rawBody)
        .digest("hex"),
  );

  return received
    .split(",")
    .map((part) => Buffer.from(part.trim()))
    .some((got) => got.length === expected.length && timingSafeEqual(got, expected));
}
python
import hashlib
import hmac
import time


def verify_webhook(raw_body: bytes, headers, secret: str, tolerance: int = 300) -> bool:
    timestamp = headers.get("X-Mookh-Timestamp", "")
    received = headers.get("X-Mookh-Signature", "")
    if not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > tolerance:
        return False
    expected = "sha256=" + hmac.new(
        secret.encode("utf-8"),
        timestamp.encode("ascii") + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    matched = False
    for part in received.split(","):
        if hmac.compare_digest(expected, part.strip()):
            matched = True
    return matched

# Flask: verify_webhook(request.get_data(), request.headers, secret)
# Django: verify_webhook(request.body, request.headers, secret)
php
<?php
function verify_webhook(string $rawBody, string $timestamp, string $received, string $secret, int $tolerance = 300): bool
{
    if (!ctype_digit($timestamp)) {
        return false;
    }
    if (abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }
    $expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    $matched = false;
    foreach (explode(',', $received) as $part) {
        if (hash_equals($expected, trim($part))) {
            $matched = true;
        }
    }
    return $matched;
}

$ok = verify_webhook(
    file_get_contents('php://input'),
    $_SERVER['HTTP_X_MOOKH_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_X_MOOKH_SIGNATURE'] ?? '',
    getenv('MOOKHPAY_WEBHOOK_SECRET')
);

Test your implementation ​

Run your verifier on these exact values with the timestamp check turned off (the timestamp is in the past). It must produce the signature shown, and accept it.

InputValue
Secretwhsec_000102030405060708090a0b0c0d0e0f1011121314151617
X-Mookh-Timestamp1763635200
Body (one line, no trailing newline)see below
Expected X-Mookh-Signaturesha256=7ab6a0cf9a774ccfe177fd9814d5d10e4db972b4e0a46374bacefc28586e9480
json
{"id":"evt_4b7e1c9a2d5f80e3a6c1b0d7","event":"payment.succeeded","checkout_id":"cs_ke_3f9a1c7e5b2d4a8e6c0b91d7","intent_id":"pi_8c1e4f0a7b3d92e5a6f01c48","amount":"150000","currency":"KES","reference":"order-1042","rail":"mpesa","provider_receipt":"TKJ8X2M4PQ","ledger_reference":"SMK4H2PL9Q","test":false,"created_at":"2026-11-20T09:14:02.000Z"}

Then test a rotation. The same timestamp and body, signed with the old secret above and the new secret whsec_18191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f, give this header:

text
sha256=4cf8c00652d35d07fb42405acfd1da77b69218599bec3dcc57dcf7d5eea3278e, sha256=7ab6a0cf9a774ccfe177fd9814d5d10e4db972b4e0a46374bacefc28586e9480

Your verifier must accept it with either secret, and refuse it with any other.

If you get a different signature, check the mistakes below, starting with the first.

Common mistakes ​

MistakeWhat happensFix
Verifying a re-serialised body (JSON.stringify(req.body), json.dumps(request.json))Key order, spacing or escaping differs from what was signed, so the signature never matchesVerify the raw bytes. In Express use express.raw({ type: "application/json" }) on the webhook route, in Flask request.get_data(), in Django request.body, in PHP file_get_contents('php://input'), in a Cloudflare Worker await request.text()
A global body parser runs firstThe raw body is gone by the time your handler runsMount the webhook route before the JSON parser, or give it its own raw parser
Decoding and re-encoding the body as text in another encodingNon-ASCII characters (an é in a description) change bytesKeep the body as bytes, or as UTF-8 text decoded once
Comparing with == or ===Works, but leaks timingUse timingSafeEqual, hmac.compare_digest or hash_equals
Comparing your value with the whole headerWorks until a rotation, then every delivery fails for 24 hoursSplit the header on ,, trim each part, and accept any one match
Requiring every signature in the header to matchEvery delivery during a rotation fails, because your server holds one secretAccept the delivery when any one part matches
Comparing uppercase hexMOOKHPay sends lowercase; a byte compare failsCompute lowercase hex, which every sample above does
Leaving out the sha256= prefix, or the . between timestamp and bodyMismatchSign timestamp + "." + body and prefix sha256=
Stripping whsec_ from the secretMismatchThe key is the whole secret string
Using your secret API key or the payout signing secretMismatchEach endpoint has its own whsec_ secret
Refusing every delivery because the server clock is wrongEvery delivery fails the timestamp check and is retriedKeep the clock synced with NTP

Staging documentation. A checkout made with a secret key on staging charges a real phone. See Environments.