Skip to content

How to verify webhook signatures (HMAC-SHA256): a step-by-step guide with code

How to verify a webhook signature with HMAC-SHA256: the raw body, the timestamp, constant-time comparison, secret rotation, and why verification fails.

Published 4 min read

Hand-drawn illustration of a webhook request with a t= and v1= signature header passing through an HMAC-SHA256 check to a tick, next to a person pointing at it
On this page
  1. What is in a webhook signature?
  2. How to verify a webhook signature, step by step
  3. Webhook signature verification code
  4. Why webhook signature verification fails
  5. How to test webhook signature verification
  6. After the signature: what a webhook handler still has to do
  7. Summary

To verify a webhook signature, compute an HMAC-SHA256 of the request with your signing secret and compare it with the signature the sender put in the header. If they match, the request came from someone who holds the secret, and the body was not changed on the way. If they do not, reject it. Webhook signature verification is what stops anyone who finds your webhook URL from posting a fake "payment succeeded" to it.

This guide shows how to verify KukoPay webhook signatures step by step, with Node.js and Python code, and covers the four mistakes behind almost every failed check: a re-serialized body, the wrong secret, a lost second signature during rotation, and a clock that has drifted.

What is in a webhook signature?

Every webhook KukoPay sends carries this header:

X-KukoPay-Signature: t=1758268800,v1=9c1f...
  • t is the Unix time, in seconds, when the request was signed;
  • v1 is the hex-encoded HMAC-SHA256(secret, "{t}.{raw request body}").

Signing the timestamp together with the body is what makes an old request useless to replay: change the timestamp and the signature no longer matches; keep it and your receiver sees that it is old.

How to verify a webhook signature, step by step

Read the raw request body

The bytes exactly as they arrived, before any JSON parsing.

Parse the header

Take t, and collect every v1= value — there can be more than one.

Check the timestamp

Reject the request if t is more than 300 seconds (5 minutes) away from your clock.

Compute the expected signature

HMAC-SHA256 of {t}.{raw body} with your signing secret, as lowercase hex.

Compare in constant time

Accept the request if any v1 matches; otherwise answer an error and do nothing else.

Webhook signature verification code

import crypto from "crypto"
 
export function verifyKukoPay(rawBody, signatureHeader, secret) {
  const parts = signatureHeader.split(",").map((item) => {
    const index = item.indexOf("=")
    return [item.slice(0, index).trim(), item.slice(index + 1).trim()]
  })
  const timestamp = parts.find(([key]) => key === "t")?.[1]
  const received = parts.filter(([key]) => key === "v1").map(([, value]) => value)
  if (!timestamp || received.length === 0) return false
 
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false
 
  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex")
  )
  return received.some((candidate) => {
    const buffer = Buffer.from(candidate)
    return buffer.length === expected.length && crypto.timingSafeEqual(buffer, expected)
  })
}
import hashlib, hmac, time
 
def verify_kukopay(raw_body: bytes, signature_header: str, secret: str) -> bool:
    timestamp, received = None, []
    for item in signature_header.split(","):
        key, _, value = item.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1":
            received.append(value)
    if not timestamp or not received:
        return False
    if abs(time.time() - int(timestamp)) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{timestamp}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(expected, candidate) for candidate in received)

A PHP version, and the full list of headers and event types, are in the webhooks documentation.

Why webhook signature verification fails

The body was parsed and re-serialized

The most common cause. Many frameworks parse JSON before your handler runs; serializing it again changes spacing or key order, and the HMAC no longer matches even though the content is "the same". Verify the raw bytes. In Express, for example, give the webhook route express.raw({ type: "application/json" }) instead of express.json(), and parse the JSON only after the signature checks out.

The wrong signing secret

Each signing secret belongs to one place:

  • a webhook endpoint has its own secret, shown only when the endpoint is created or its secret is rotated;
  • an order's own notify_url is signed with the app's callback signing secret, issued under Developers → API keys;
  • test and live are separate: a sandbox secret never verifies a live webhook.

If you run several endpoints or apps, check that the receiver uses the secret of the endpoint the request was sent to — the X-KukoPay-Endpoint-Id header names it. See how to manage multiple webhook endpoints.

Only the last signature was kept

When a secret is rotated, the old secret keeps signing alongside the new one for 24 hours, so the header carries two v1= values. Code that turns the header into a map — Object.fromEntries, a dictionary — keeps only one of them and fails for the whole window on whichever side has not switched yet. Collect every v1 and accept a match on any. The rotation itself is covered in how to rotate a webhook secret.

The clock is wrong

A server whose clock has drifted by more than 5 minutes rejects genuine webhooks as stale. Keep time synced (NTP), and log the age of rejected timestamps so drift shows up quickly.

How to test webhook signature verification

You do not need a real payment to know your check works:

  • Send a test webhook from Developers → Sandbox testing. It is built and signed exactly like a real one, and the page shows both the request and your receiver's response. Test webhooks carry "test": true and an id beginning evt_test_ — never fulfil on them.
  • Signature self-check on Developers → Webhooks: paste a raw body and its X-KukoPay-Signature, and the dashboard recomputes the signature in your browser and tells you whether the secret, a reformatted body or the timestamp is the problem.
  • Simulate a payment result on a sandbox order to receive a real payment.succeeded, signed and retried by the normal rules. See sandbox vs live mode.

After the signature: what a webhook handler still has to do

A valid signature proves who sent the request, not that you have not processed it before. Webhooks can be delivered more than once, so the next steps are:

  1. store the event id under a unique constraint, in the same transaction as your state change — see payment webhook idempotency;
  2. answer 2xx within 10 seconds and move slow work to a queue;
  3. if something still goes missing, recover it from the events API — see webhook not received.

Summary

  • To verify a webhook signature, recompute HMAC-SHA256(secret, "{t}.{raw body}") and compare it with the header's v1 in constant time;
  • reject timestamps more than 5 minutes off, and accept a match on any v1, since rotation sends two for 24 hours;
  • verify the raw bytes, never re-serialized JSON, and use the secret of the endpoint (or app) the request was sent to, in the right environment;
  • test with a test webhook and the signature self-check before going live, then deduplicate by event id.

Try it in the sandbox

Create a merchant account and request a test key. The sandbox needs no business verification.