Verify Webhook Signatures: HMAC Guide for Crypto Payments

Your webhook URL is public, so anyone can POST a fake "payment.paid" to it. Here's how HMAC-SHA256 signatures with timestamps work, the raw-body mistakes that break them, and how to handle replays, duplicates and retries.

TTillCrypto team7 min read

A webhook is how a payment gateway tells your server "this order is paid." It is also a public URL that anyone on the internet can POST to. If you don't verify the webhook signature, there is no difference between a real payment notification and a curl command someone typed to get a free product.

This guide covers how HMAC-signed webhooks work, the mistakes that make verification fail (or pass when it shouldn't), and how to deal with replays, duplicates and retries. The code is in Node.js, Python and PHP and uses the X-TillCrypto-Signature header as the example, but the same pattern applies to most gateways.

Why crypto payment webhooks need signature verification

Your webhook URL is not a secret. It is often something guessable like /webhooks/payment, and it ends up in logs, screenshots and support tickets. Sooner or later, someone will send it a request that looks like this:

json
{ "type": "payment.paid", "data": { "order_id": "ORDER-10001", "status": "paid" } }

If your handler trusts that body, you just marked an unpaid order as paid. With digital goods that are delivered instantly, such as license keys, downloads or account credits, the loss happens before anyone notices. That is one reason selling digital products for USDT needs a careful webhook handler.

HTTPS doesn't fix this, because it protects the connection, not the identity of whoever opened it. IP allowlists help a little, but they break when the provider changes infrastructure, and many providers (TillCrypto included) don't publish a fixed list of sending IPs anyway. The customer landing on your success_url isn't proof either, since anyone can open that URL by hand (more on that in how to accept USDT payments on your website).

What a signature gives you is narrower, and it's exactly what you need. The sender knows a secret that only you and the gateway share. And the body hasn't changed by a single byte since it was signed.

How HMAC-SHA256 webhook signatures work

HMAC is a hash that takes a key. The gateway and you share a signing secret (on TillCrypto it starts with whsec_). For each delivery, the gateway computes HMAC-SHA256(secret, message) and sends the result in a header. You run the same calculation on what you received. If the two values match, the request is genuine.

Here is what a delivery looks like:

http
POST /webhooks/tillcrypto HTTP/1.1
Content-Type: application/json
X-TillCrypto-Event-Id: evt_Xk2...
X-TillCrypto-Signature: t=1794444780,v1=5f1c0d...e9a2
Part What it is What you do with it
t Unix time (seconds) when this delivery was signed Reject it if it's too far from your clock
v1 Hex of HMAC-SHA256(secret, "<t>.<raw body>") Recompute it and compare in constant time
X-TillCrypto-Event-Id The event's ID, the same on every retry Use it for deduplication

The timestamp is part of the signed message on purpose. If it were only a separate header, an attacker could take an old request and update t to make it look new. Because t is signed, changing it breaks the signature. The v1= label leaves room for a future signing scheme without breaking existing code.

How to verify a webhook signature in Node.js, Python and PHP

Every version below follows the same steps:

  1. Read the raw request body as bytes, before any JSON parsing.
  2. Split the header into t and v1.
  3. Reject the request if t is more than 300 seconds away from your clock.
  4. Compute HMAC-SHA256 over t, a dot, and the raw body, using the full secret string (including whsec_) as the key.
  5. Compare the result with v1 in constant time.
  6. Only then parse the JSON and act on it.

Node.js (Express)

javascript
import crypto from 'node:crypto';
import express from 'express';

const SECRET = process.env.TILLCRYPTO_WEBHOOK_SECRET; // whsec_...
if (!SECRET) throw new Error('TILLCRYPTO_WEBHOOK_SECRET is not set');
const TOLERANCE_SECONDS = 300;

function verifySignature(rawBody, header, secret) {
  const parts = {};
  for (const pair of (header || '').split(',')) {
    const i = pair.indexOf('=');
    if (i > 0) parts[pair.slice(0, i).trim()] = pair.slice(i + 1).trim();
  }
  const { t, v1 } = parts;
  if (!t || !/^\d+$/.test(t) || !v1) return false;
  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
  const received = Buffer.from(v1, 'hex');
  return received.length === expected.length && crypto.timingSafeEqual(received, expected);
}

const app = express();

// Register this route BEFORE any global app.use(express.json())
app.post('/webhooks/tillcrypto', express.raw({ type: 'application/json' }), async (req, res) => {
  const ok = Buffer.isBuffer(req.body) &&
    verifySignature(req.body, req.get('X-TillCrypto-Signature'), SECRET);
  if (!ok) return res.status(400).send('invalid signature');

  const event = JSON.parse(req.body.toString('utf8'));
  try {
    await saveToInbox(event); // your code: INSERT ... ON CONFLICT (event_id) DO NOTHING
  } catch (err) {
    console.error(err);
    return res.sendStatus(500); // not stored, so let the gateway retry
  }
  res.sendStatus(200); // fulfilment runs in a background worker
});

app.use(express.json()); // the rest of your API

crypto.timingSafeEqual throws when the two buffers have different lengths, which is why the length check comes first.

Python (Flask)

python
import hashlib, hmac, json, os, time
from flask import Flask, request

app = Flask(__name__)
SECRET = os.environ["TILLCRYPTO_WEBHOOK_SECRET"].encode()  # whsec_...
TOLERANCE_SECONDS = 300

def verify_signature(raw: bytes, header: str, secret: bytes) -> bool:
    parts = {}
    for pair in header.split(","):
        key, sep, value = pair.strip().partition("=")
        if sep:
            parts[key] = value
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not (t.isascii() and t.isdigit()) or not v1:
        return False
    if abs(time.time() - int(t)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret, t.encode() + b"." + raw, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), v1.encode())

@app.post("/webhooks/tillcrypto")
def tillcrypto_webhook():
    raw = request.get_data()  # exact bytes, before any JSON parsing
    if not verify_signature(raw, request.headers.get("X-TillCrypto-Signature", ""), SECRET):
        return "invalid signature", 400
    event = json.loads(raw)
    save_to_inbox(event)  # your code; if it raises, Flask returns 500 and the gateway retries
    return "", 200

PHP

php
<?php
const TOLERANCE_SECONDS = 300;

function verify_signature(string $raw, string $header, string $secret): bool {
    $parts = [];
    foreach (explode(',', $header) as $pair) {
        $kv = explode('=', trim($pair), 2);
        if (count($kv) === 2) {
            $parts[$kv[0]] = $kv[1];
        }
    }
    $t = $parts['t'] ?? '';
    $v1 = $parts['v1'] ?? '';
    if (!ctype_digit($t) || $v1 === '') {
        return false;
    }
    if (abs(time() - (int) $t) > TOLERANCE_SECONDS) {
        return false;
    }
    $expected = hash_hmac('sha256', $t . '.' . $raw, $secret);
    return hash_equals($expected, $v1);
}

$secret = getenv('TILLCRYPTO_WEBHOOK_SECRET');
if (!$secret) {
    http_response_code(500);   // never verify with an empty key
    exit('webhook secret not configured');
}

$raw = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_TILLCRYPTO_SIGNATURE'] ?? '';
if (!verify_signature($raw, $header, $secret)) {
    http_response_code(400);
    exit('invalid signature');
}

$event = json_decode($raw, true);
try {
    save_to_inbox($event);   // your code: insert keyed on event_id, ignore duplicates
} catch (Throwable $e) {
    error_log((string) $e);
    http_response_code(500); // not stored, so let the gateway retry
    exit;
}
http_response_code(200);

The try/catch matters more in PHP than it looks. With display_errors on, an uncaught exception can go out as an error page with status 200, and the gateway will treat the event as delivered.

Why constant time? A normal == returns as soon as it finds the first character that differs, so a wrong guess fails slightly faster than a nearly right one. Measuring that over a network is hard, but the safe comparison costs nothing. Every language has one: crypto.timingSafeEqual, hmac.compare_digest and hash_equals.

Raw body pitfalls and other reasons verification fails

Code that passes a unit test and then rejects every real delivery usually trips over one of these:

  • Re-serialized JSON. If you parse the body and serialize it again, the bytes change: key order, spacing, 10.0 versus 10, or 中 versus 中 (Python's json.dumps escapes non-ASCII characters by default, JavaScript's JSON.stringify doesn't). One changed byte produces a completely different HMAC.
  • Middleware order in Express. If app.use(express.json()) runs first, it has already parsed the body, so express.raw skips the request and req.body is an object instead of the raw Buffer. Verification then fails every time. Put the webhook route above the global parser.
  • Next.js and other frameworks. In the App Router, read await request.text() instead of request.json(). In the Pages Router, turn off the built-in body parser for that route.
  • Wrong secret. Check that you used the full value including whsec_, with no trailing newline from a .env file. Rotating the secret takes effect immediately, with no overlap: every delivery after that, including retries of older events, is signed with the new one. Deliveries fail until your server has it, but they're retried, so nothing is lost.
  • Redirects. TillCrypto doesn't follow redirects, so a 301 from http to https, or from a missing trailing slash, counts as a failed delivery. Register the final URL.
  • Clock drift. A server clock that is several minutes off will reject everything. Keep NTP running.

Return a 4xx when the signature is bad, and log it. Don't return 200 to stop the noise. If the cause is a wrong secret on your side, the retries will go through once you fix it.

Replay windows and idempotency with event IDs

A valid signature tells you the gateway sent this request. It doesn't tell you that this is the first time you've seen it. Duplicates come from two places:

  • Replays. Someone captures a valid request and sends it again. The timestamp window limits this to a few minutes.
  • Honest retries. Your server handled the event but responded too late, for example after TillCrypto's 10-second timeout, so the gateway sends it again with the same event ID.

You handle both the same way: record each event ID once, and make the business update conditional.

sql
-- Postgres syntax; on MySQL use ? placeholders and INSERT IGNORE
CREATE TABLE webhook_inbox (
  event_id     VARCHAR(64) PRIMARY KEY,
  type         TEXT NOT NULL,
  payload      TEXT NOT NULL,
  received_at  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  processed_at TIMESTAMP
);

-- in the webhook handler
INSERT INTO webhook_inbox (event_id, type, payload)
VALUES ($1, $2, $3)
ON CONFLICT (event_id) DO NOTHING;

-- in the worker: only one run can move the order to "paid"
UPDATE orders SET status = 'paid', paid_at = CURRENT_TIMESTAMP
WHERE id = $1 AND status IN ('pending', 'expired');

If the UPDATE changes zero rows, the order is already paid, so skip fulfilment. Take the event ID from the verified body (event.id) rather than from the header, because only the body is covered by the signature.

Notice that expired is in that WHERE clause. Don't treat an expired order as a dead end. TillCrypto still credits payments that arrive up to 30 minutes after the checkout expires, and a transfer that couldn't be matched automatically can be assigned to an expired payment during manual review. In both cases you get payment.paid, and the customer really did pay.

Before you ship anything, the worker should also check:

  • livemode is true in production. Test events have it set to false.
  • data.status is "paid" and data.order_id matches a real order.
  • data.amount and data.currency match what you charged. Compare data.amount (what you asked for), not pay_amount, which may carry a tiny increment such as 100.01 to tell concurrent orders apart. If partial payments matter to you, also look at received_amount: for a transfer matched by hand it is what actually arrived.
  • Unknown event types, including webhook.test, are marked processed and skipped, not raised as errors.
  • The order never goes backwards. Once it's paid, a late, older event shouldn't move it.

Late payments, underpayments and other messy cases are covered in crypto payment edge cases. If you're ever unsure, ask the API directly with GET /v1/payments/{id}.

Respond fast, process later: how retries work

TillCrypto waits 10 seconds for your answer, and many gateways wait less. If your handler sends emails, generates license keys and calls your ERP before it replies, it will eventually time out and trigger a retry for an event you've already processed.

The reliable pattern is: verify, store, return 2xx, then process in a worker. Storing the event before you reply matters. If you reply first and crash before saving, the event is lost and nothing will retry it.

When a delivery fails because of a non-2xx response, a timeout or a connection error, TillCrypto retries on this schedule:

Attempt Wait after the previous failure Roughly how long after the first try
1 right away 0
2 1 minute 1 minute
3 5 minutes 6 minutes
4 15 minutes 21 minutes
5 1 hour 1 h 21 min
6 6 hours 7 h 21 min
7 24 hours about 31 hours

After the last attempt the event is marked as failed, and you can resend it by hand from the dashboard.

Sources and further reading

Accept USDT on your website

Hosted checkout, signed webhooks and a test mode. 0% processing fee, no monthly fee.