On this page
Why you must verify the signature
A webhook handler usually does something important: confirms an order, delivers a digital product or updates an account balance. Without a signature check, anyone who learns your URL can send a fake invoice.paid notification and get the goods without paying. Verification guarantees three things:
- Origin: the request was signed with a secret only you and HisarPay know.
- Integrity: if a single byte of the body changes, the signature no longer matches.
- Freshness: the timestamp stops an old request from being captured and replayed.
Anatomy of the signature header
Every delivery carries this header:
X-HisarPay-Signature: t=1767225600,v1=5f2b9c…e41a| Field | Meaning |
|---|---|
t | When the signature was created, as a Unix timestamp in seconds |
v1 | Hex HMAC-SHA256 of t + "." + raw_body, keyed with your signing secret |
During a secret rotation the header carries a second v1 value: one signed with the new secret and one with the previous secret. Both stay valid for 24 hours, and the request is genuine if either value matches. Each delivery also includes an X-HisarPay-Event-Id header and the HisarPay-Webhook/1.0 user agent.
The verification steps
- Capture the raw body. Keep the request bytes exactly as received, before any JSON parsing.
- Parse the header. Split on commas and separate
tfrom everyv1value. - Check the timestamp. Reject the request if
tis more than 5 minutes away from your server clock. - Compute the expected signature. Produce the hex value of
HMAC-SHA256(secret, t + "." + raw_body). - Compare in constant time. Compare the expected value with each
v1using a function that does not leak timing. - Drop duplicates. Store
X-HisarPay-Event-Id; if the same event arrives again, return 200 without reprocessing it. - Respond quickly. Queue the work and return a 2xx within 10 seconds.
Example code
The examples below have no SDK dependency and implement the same algorithm. When adapting them to your framework, make sure you are reading the raw body.
Node.js (Express)
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';
function verifyHisarPay(rawBody, header, secret, toleranceSec = 300) {
if (!header || !secret) return false;
const parts = header.split(',').map((p) => p.trim().split('='));
const t = Number(parts.find(([k]) => k === 't')?.[1]);
if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > toleranceSec) return false;
const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
return parts
.filter(([k]) => k === 'v1')
.some(([, v]) => {
const got = Buffer.from(v ?? '', 'hex');
return got.length === expected.length && timingSafeEqual(got, expected);
});
}
const app = express();
// raw body: never verify a re-serialized JSON object
app.post('/webhooks/hisarpay', express.raw({ type: 'application/json' }), (req, res) => {
const ok = verifyHisarPay(req.body, req.get('X-HisarPay-Signature'), process.env.HISARPAY_WEBHOOK_SECRET);
if (!ok) return res.status(400).send('invalid signature');
const event = JSON.parse(req.body.toString('utf8'));
queue.add(event); // process asynchronously
res.sendStatus(200);
});PHP
<?php
function hisarpay_verify(string $payload, ?string $header, string $secret, int $tolerance = 300): bool
{
if ($header === null || $secret === '') {
return false;
}
$t = null;
$signatures = [];
foreach (explode(',', $header) as $part) {
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
if ($key === 't' && ctype_digit($value)) {
$t = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value;
}
}
if ($t === null || abs(time() - $t) > $tolerance) {
return false;
}
$expected = hash_hmac('sha256', $t . '.' . $payload, $secret);
foreach ($signatures as $signature) {
if (hash_equals($expected, strtolower($signature))) {
return true;
}
}
return false;
}
$payload = file_get_contents('php://input');
$header = $_SERVER['HTTP_X_HISARPAY_SIGNATURE'] ?? null;
if (!hisarpay_verify($payload, $header, (string) getenv('HISARPAY_WEBHOOK_SECRET'))) {
http_response_code(400);
exit;
}
$event = json_decode($payload, true);
http_response_code(200);Python (Flask)
import hashlib
import hmac
import os
import time
from flask import Flask, abort, request
app = Flask(__name__)
def verify_hisarpay(payload: bytes, header: str | None, secret: str, tolerance: int = 300) -> bool:
if not header or not secret:
return False
t, signatures = None, []
for part in header.split(","):
key, _, value = part.strip().partition("=")
if key == "t" and value.isdigit():
t = int(value)
elif key == "v1":
signatures.append(value)
if t is None or abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + payload, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected.encode(), s.lower().encode()) for s in signatures)
@app.post("/webhooks/hisarpay")
def hisarpay_webhook():
header = request.headers.get("X-HisarPay-Signature")
if not verify_hisarpay(request.get_data(), header, os.environ["HISARPAY_WEBHOOK_SECRET"]):
abort(400)
event = request.get_json()
return "", 200One line with an SDK
Our official SDKs ship the same check ready to use: they verify the signature and timestamp, accept both signatures during a rotation and return the parsed event. If the signature is invalid, they throw an error.
// Node.js: @hisarpay/node
import { HisarPay } from '@hisarpay/node';
const event = HisarPay.webhooks.constructEvent(rawBody, signatureHeader, secret);
// PHP: hisarpay/hisarpay-php
$event = \HisarPay\Webhook::constructEvent($payload, $header, $secret);
# Python: hisarpay
from hisarpay import webhooks
event = webhooks.construct_event(payload, header, secret)The most common mistakes
- Signing parsed JSON:
JSON.stringify(req.body)does not reproduce the original bytes; whitespace and key order can change. Always use the raw body. - Comparing with
==: ordinary string comparison stops at the first different character and leaks timing. UsetimingSafeEqual,hash_equalsorhmac.compare_digest. - Ignoring the timestamp: without a tolerance check, a captured old request stays valid forever.
- Checking only the first
v1: during a rotation, the matching signature may be the second one. - Relying on redirects: deliveries do not follow redirects. Your endpoint must be the final URL; even an HTTP-to-HTTPS redirect makes the delivery fail.
- Slow handlers: responses that take longer than 10 seconds count as failures and are retried. Move heavy work to the background.
Retries and ordering
If your endpoint returns anything other than a 2xx or times out, the delivery is retried on this schedule: 30 seconds, 2 minutes, 10 minutes, 30 minutes, 1 hour, 3 hours, 6 hours, 12 hours and 24 hours. Event order is not guaranteed, so base your decisions on the invoice’s current status rather than on the order events arrive in.
test.ping event to your endpoint and inspect the delivery log. For full scenarios, see our test mode guide.Frequently asked questions
Why is the signature computed over the raw body?
Why are there two v1 values in the header?
What timestamp tolerance should I use?
What should I do if the same event arrives twice?
- #Webhooks
- #HMAC
- #Security
- #API
Try crypto payments in test mode
No setup or monthly fees. Experiment as much as you like in test mode and go live when you are ready.