Summary
On a Payment Gateway for iGaming, HMAC-SHA256 proves that a request or webhook was produced by someone holding your signing secret and that its body was not altered in transit. Verify it against the raw bytes you received, compare in constant time, reject stale X-Timestamp values, and make the handler idempotent because deliveries are retried until you return HTTP 200. Get those five habits right and most 401s and duplicate-credit incidents disappear.
01What HMAC-SHA256 actually protects you from
A webhook is an unauthenticated HTTP POST to a public URL. Anyone who discovers that URL can send a body that says a deposit of 45,000 THB has completed, and if your handler trusts the content, your platform credits a player who never paid. HMAC-SHA256 closes that hole by attaching a signature that only someone holding the shared signing secret can produce for that exact message.
It gives you two properties. Authenticity means the sender knew the secret, so it is your gateway and not a stranger or a misconfigured test script. Integrity means that changing even one character of the body, such as an amount or an order reference, produces a completely different signature, so tampering in transit or by an intermediary is detectable.
It does not give you confidentiality, because the body is still readable, and by itself it does not stop someone from re-sending a genuine, captured message. That second gap is why the timestamp and idempotency sections below matter just as much as the hash. Treat the signature as one layer in a stack that also includes TLS, IP allowlisting and a handler that tolerates repeats.
02The headers and the two credentials
SF PayGate authenticates API traffic with three headers: X-API-Key, X-Timestamp and X-Signature. The signature is an HMAC-SHA256 computed over the raw body, and for webhooks the message you recompute is the timestamp, a colon, then the raw body, written as `${timestamp}:${rawBody}` in the product docs. Keep that exact format in a shared constant so that nobody on the team improvises a variant.
The X-API-Key and the signing secret are separate credentials, and the separation is deliberate. The API key is an identifier that travels in every request header and appears in logs, proxies and support screenshots. The signing secret never travels at all; it only exists on your server and on the gateway, and it is used locally to compute the signature. If you collapse the two into one value, every log line becomes a potential secret leak.
In practice this means two environment variables, two entries in your secret manager and two rotation schedules. A leaked API key alone cannot forge a valid signature, and a leaked signing secret alone does not tell an attacker which account to target. You still need to treat both as sensitive, but the blast radius of each is smaller when they are kept apart.
| Item | Sent over the wire? | Appears in logs? | Storage guidance |
|---|---|---|---|
| X-API-Key | Yes, in every request | Often, so mask it | Secret manager; mask in logs and dashboards |
| Signing secret | Never | Must never appear | Secret manager; server-side only; rotate on schedule |
| X-Timestamp | Yes | Safe to log | Unix seconds, used for freshness checks |
| X-Signature | Yes | Safe to log for debugging | Compare in constant time |
03The raw-body rule: why re-serialising JSON breaks signatures
The single most common cause of failed verification is hashing the wrong bytes. The gateway signs the exact byte sequence it sent. If your framework parses that JSON into an object and you call JSON.stringify or json_encode to rebuild a string, whitespace, key order, number formatting, unicode escaping and slash escaping can all differ from the original. One changed byte means a different HMAC, and your handler rejects a perfectly genuine webhook.
A Friday-night spike makes this vivid. Suppose your staging environment passed every test because the sample payloads happened to be compact and ASCII only. In production a player name arrives with a Thai character, PHP escapes it differently from the original, and a small fraction of deposits fail verification. Those orders stay pending, support tickets pile up, and the root cause is a serialiser, not an attacker.
The rule is therefore simple: capture the raw bytes first, verify against them, and only then parse. In Express, mount express.raw on the webhook route instead of express.json. In Next.js route handlers, call req.text() rather than req.json(). In PHP, read php://input and never use the already-decoded $_POST. Also check that no middleware earlier in the chain, such as a body-parsing proxy or WAF rule, rewrites the payload.
// app/api/webhooks/sfpaygate/route.ts (Next.js App Router)
import crypto from "node:crypto";
export async function POST(req: Request) {
const rawBody = await req.text(); // exact bytes, not req.json()
const timestamp = req.headers.get("x-timestamp") ?? "";
const received = req.headers.get("x-signature") ?? "";
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > 300) {
return new Response("stale", { status: 401 });
}
const expected = crypto
.createHmac("sha256", process.env.SFPAYGATE_SIGNING_SECRET!)
.update(timestamp + ":" + rawBody)
.digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(received);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return new Response("bad signature", { status: 401 });
}
// enqueue(JSON.parse(rawBody)) then return immediately
return new Response("ok", { status: 200 });
}04Verifying in Node.js and PHP, step by step
The verification routine has the same shape in every language. You read the three values you need, check freshness, rebuild the message as the timestamp, a colon and the raw body, compute the HMAC-SHA256 hex digest with your signing secret, and compare it to X-Signature. Only if everything matches do you acknowledge and hand the event to your processing code.
The Express example below (alongside our developer API documentation) shows the full flow with the raw-body middleware, and the PHP version after it does the same with php://input and hash_equals. Notice that both acknowledge with HTTP 200 before doing heavy work, and that the JSON is parsed only after the signature check has passed. Adapt the queue call to whatever durable store you use, whether that is a database table, a message broker or a job queue.
- 1Read the raw request body as bytes or an unparsed string.
- 2Read X-Timestamp and X-Signature; reject the request with 401 if either is missing.
- 3Reject if the timestamp is outside your freshness window.
- 4Build the message as timestamp, a colon, then the raw body.
- 5Compute HMAC-SHA256 with the signing secret and encode as hex.
- 6Compare with the received signature using a constant-time function.
- 7Return HTTP 200 quickly, then enqueue the event for processing.
import express from "express";
import crypto from "node:crypto";
const app = express();
const WEBHOOK_SECRET = process.env.SFPAYGATE_SIGNING_SECRET;
const MAX_SKEW_SECONDS = 300;
// Capture raw bytes BEFORE any JSON parsing happens.
app.post(
"/webhooks/sfpaygate",
express.raw({ type: "application/json" }),
async (req, res) => {
const rawBody = req.body.toString("utf8"); // Buffer -> exact bytes sent
const timestamp = req.get("X-Timestamp") || "";
const received = req.get("X-Signature") || "";
// 1) Freshness window
const age = Math.abs(Date.now() / 1000 - Number(timestamp));
if (!Number.isFinite(age) || age > MAX_SKEW_SECONDS) {
return res.status(401).send("stale or missing timestamp");
}
// 2) Recompute: message format is timestamp:rawBody
const message = timestamp + ":" + rawBody;
const expected = crypto
.createHmac("sha256", WEBHOOK_SECRET)
.update(message)
.digest("hex");
// 3) Constant-time comparison (lengths must match first)
const a = Buffer.from(expected);
const b = Buffer.from(received);
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return res.status(401).send("bad signature");
}
// 4) Acknowledge fast, process later
res.status(200).send("ok");
const event = JSON.parse(rawBody); // parse only AFTER verification
await queue.enqueue(event); // your durable queue / outbox
}
);05The same check in PHP
PHP shops often run behind PHP-FPM, which makes the respond-then-process pattern easy through fastcgi_finish_request. The code below reads php://input once, validates the timestamp is numeric before using it, and uses hash_equals for the comparison. Both details matter: casting a non-numeric header to an integer silently yields zero, and a plain string comparison leaks timing information.
If your application is built on a framework such as Laravel or Symfony, retrieve the raw content from the request object (for example, the request's getContent method) rather than from a parsed input bag. Also check whether any global middleware trims or normalises the request body, because that would alter the bytes before your verification runs.
Keep the verification in a small, separately tested class or function that takes the raw body, the two headers and the secret as arguments. A pure function is easy to unit test with fixtures, which lets you reproduce a signature mismatch from a captured request without touching production.
<?php
// webhook.php - read raw bytes, never json_decode before verifying
$secret = getenv('SFPAYGATE_SIGNING_SECRET');
$maxSkew = 300;
$rawBody = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$received = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
if (!ctype_digit($timestamp) || abs(time() - (int)$timestamp) > $maxSkew) {
http_response_code(401);
exit('stale or missing timestamp');
}
// message format is timestamp:rawBody
$expected = hash_hmac('sha256', $timestamp . ':' . $rawBody, $secret);
if (!hash_equals($expected, $received)) {
http_response_code(401);
exit('bad signature');
}
http_response_code(200);
echo 'ok';
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request(); // release the connection, then keep working
}
$event = json_decode($rawBody, true);
enqueue_event($event); // push to a durable queue or table06Constant-time comparison and the X-Timestamp freshness window
An ordinary equality operator returns as soon as it finds the first differing character. An attacker who can measure response time over many attempts could in principle learn the signature one character at a time. Functions such as crypto.timingSafeEqual in Node.js and hash_equals in PHP take the same time regardless of where the strings differ. Use them every time, and compare equal-length values, since Node throws when buffer lengths differ.
The X-Timestamp header addresses replay. A captured, genuine webhook carries a valid signature forever, so without a time check an attacker who recorded it could resend it later. By including the timestamp inside the signed message, the sender makes the time tamper-evident, and by rejecting anything outside a window you shrink the period in which a replay could work. A window of a few minutes is a common starting point; choose yours based on how well your servers keep time.
Clock drift is the practical pitfall. If your server clock is off by more than the window, every webhook looks stale and you will see a wall of 401s that seems to start at no particular moment. Run NTP on every host, alert on skew, and log the computed age when you reject a request. Remember that a freshness window reduces replay exposure but does not eliminate duplicates within the window, which is why handlers must also be idempotent.
07Signing outbound requests and the /api prefix rule
Verification runs in two directions. When you call the gateway, for example POST /api/v2/payins to create a deposit, you sign the request and send X-API-Key, X-Timestamp and X-Signature. The rule that trips up most new integrations is that the leading `/api` is stripped before the signature is verified on the gateway side. You call `/api/v2/payins`, but the path you sign is `/v2/payins`.
This looks odd until you consider infrastructure. A reverse proxy often mounts the service under /api and removes that prefix before the application sees the request, so the application verifies against the path it actually received. If you sign the public URL path including /api, the gateway computes a different message and returns 401 even though your secret is correct.
Build your HTTP client so that the signing path is derived from the endpoint constant, not from the final URL. For example, define the endpoint as `/v2/payins` and let the client add the /api prefix when it builds the request URL. Follow the canonical string layout in the signing reference, and test against the sandbox until a deliberate bad signature returns 401 and a correct one succeeds.
| You call | You sign the path | Common mistake |
|---|---|---|
| POST /api/v2/payins | /v2/payins | Signing /api/v2/payins |
| GET /api/v1/payins/{id} | /v1/payins/{id} | Signing with the id placeholder or the full URL |
| POST /api/v1/payouts | /v1/payouts | Re-serialising the body after signing |
| POST /api/me/issues | /me/issues | Using the API key as the signing secret |
08Idempotent handlers: duplicates, retries and responding fast
SF PayGate retries a signed webhook automatically until your endpoint returns HTTP 200. That is a safety feature, because a deposit confirmation should not be lost just because your server restarted during a deploy. The consequence is at-least-once delivery: your handler will sometimes see the same event twice, and it must produce the same result both times.
Picture a retried timeout. Your endpoint verifies the signature, starts crediting the wallet, and a slow database call pushes the response past the gateway's timeout. The gateway considers the delivery failed and sends it again. If your code simply adds the amount on each call, the player is credited twice. The fix is a uniqueness constraint: record the event or order identifier in a table with a unique key, and treat a conflict as already handled while still replying 200.
Combine that with respond-fast-then-process. Verify, persist or enqueue the event, return 200 immediately, and let a worker do the wallet credit, notifications and reconciliation updates. For payouts, the unique merchant_ref_id works as the idempotency key on the request side, and Smart Withdraw reports each execution step in signed callbacks, so your handler should key on the step as well as the payout. Also use the query API as the second confirmation path when a webhook seems missing, rather than assuming it was never sent.
// Idempotent handler: the unique key makes duplicates harmless
async function handleEvent(event) {
const key = event.merchant_ref_id || event.id; // your stable identifier
const inserted = await db.query(
"INSERT INTO processed_events (event_key) VALUES ($1) ON CONFLICT DO NOTHING RETURNING event_key",
[key]
);
if (inserted.rowCount === 0) return; // already handled, still reply 200
await db.transaction(async (tx) => {
await creditPlayerWallet(tx, event); // business effect
await markOrderPaid(tx, event);
});
}09Debugging 401s: symptom, likely cause, fix
When verification fails, resist the urge to loosen the check. Work from the symptom to the cause and fix the cause. Log the received timestamp, the computed age, the length of the raw body and the first few characters of both signatures, but never log the signing secret itself. A reproducible fixture that contains the raw body, timestamp and signature of a failed request lets you debug offline.
Most failures fall into a handful of buckets, and the table below covers the ones we see most often in integrations. Work through them in order, because the earlier rows are far more common than the later ones. If a problem persists after you have eliminated these, open a ticket through POST /me/issues with the request_id so support can trace the specific call.
| Symptom | Likely cause | Fix |
|---|---|---|
| Every webhook fails, even in sandbox | Body parsed and re-serialised before hashing | Use raw-body middleware; hash exact bytes |
| Outbound calls return 401, secret verified | Signed /api/v2/payins instead of /v2/payins | Strip the leading /api from the signing path |
| Intermittent failures with non-ASCII text | Serialiser escapes unicode or slashes differently | Never rebuild the JSON string; use the received bytes |
| All requests fail after a server change | Clock drift beyond the freshness window | Fix NTP; log computed age; alert on skew |
| Signature differs by case or whitespace | Hex output case or trailing newline mismatch | Normalise encoding; trim header value only, not body |
| Works locally, fails in production | Proxy, WAF or middleware altered the body | Capture raw bytes at the edge; compare lengths |
| Failures began after a rotation | Old secret still deployed on some instances | Confirm every instance loads the new secret |
| Using API key as the secret | Credentials confused | Use the separate signing secret for HMAC |
10Secret storage, rotation and IP allowlisting
Store the signing secret in a secret manager or encrypted environment configuration, never in source control, container images, front-end bundles or chat messages. Give the verification service read access and nobody else. Limit who can view the value in your cloud console, and make sure application logs, error trackers and crash dumps cannot include environment variables.
Rotation needs a plan before you need it. Decide a regular schedule, and also rehearse an emergency procedure for the day a developer leaves or a laptop is lost. A safe pattern is to support the old and new secrets for a short overlap on your side, deploy the new secret to every instance, confirm webhooks verify, and only then retire the old one. Coordinate timing with support so that failed deliveries during the cutover are retried rather than lost.
IP allowlisting adds a network-level check. SF PayGate enforces per-account IP allowlisting and platform security controls on the API and the portal, so requests from unknown addresses are refused even if a key leaks. On your side, restrict the webhook endpoint to the gateway's published source addresses if your firewall allows it. Treat this as defence in depth rather than a replacement for signature verification, because addresses can change and the signature is the check that proves the content.
11Go-live security checklist
Before production review, walk through this list with your engineering and security leads. Each item is something you can verify once you request sandbox access rather than assume. SF PayGate reviews merchants before going live, and merchants remain responsible for their own licensing and for compliance with the rules of the markets they operate in; the checklist below covers the technical side only.
After go-live, rerun the list whenever you change infrastructure, such as a new proxy, a framework upgrade or a move to another cloud region. Webhook verification tends to break at those boundaries, and a ten-minute regression test costs far less than a night of unmatched deposits during month-end reconciliation.
- 1Webhook route reads raw bytes and verifies before parsing JSON.
- 2Message format is exactly timestamp, colon, raw body, and is covered by unit tests.
- 3Comparison uses timingSafeEqual or hash_equals.
- 4X-Timestamp window is enforced, and server clocks are synchronised.
- 5Outbound requests sign the path without the leading /api.
- 6X-API-Key and signing secret are stored separately; secret never logged.
- 7Handler is idempotent with a unique key and returns 200 for duplicates.
- 8Endpoint acknowledges quickly and processes through a durable queue.
- 9IP allowlist is configured on the account; 2FA and RBAC are enabled for portal users.
- 10Rotation procedure is documented and rehearsed in the sandbox.
- 11A reconciliation job uses the query API to catch missed webhooks.
Frequently asked questions
- Why does my signature fail only for some webhooks?
- Intermittent failures usually point to re-serialisation: the body contains characters such as non-ASCII text or escaped slashes that your JSON library writes differently from the original. Verify against the raw bytes before parsing. Also check for a proxy or middleware that alters the body on certain routes.
- Should I sign /api/v2/payins or /v2/payins?
- Sign /v2/payins. The leading /api is stripped before signature verification, so you call the public URL with the prefix but use the path without it in the signed message.
- Can I use the same value for X-API-Key and the signing secret?
- No. They are separate credentials by design. The API key identifies your account and travels in headers, while the signing secret stays on servers and is used only to compute signatures.
- How long does the gateway keep retrying a webhook?
- Webhooks are retried automatically until your endpoint returns HTTP 200. Because of that, your handler must be idempotent and should acknowledge quickly. If you suspect a missed delivery, use the query API to confirm the order status.
- What freshness window should I use for X-Timestamp?
- Choose a window that is short enough to limit replay but wide enough to tolerate normal clock drift and network delay; a few minutes is a typical starting point. Keep servers synchronised with NTP and log the computed age when you reject a request.
- Does IP allowlisting replace signature verification?
- No. Allowlisting restricts where requests may come from, while the signature proves the content is authentic and unmodified. Use both, as they protect against different failure modes.