Verify webhook signatures
Anyone can POST to your webhook URL. The signature proves a request came from us and was not changed on the way. Check it on every request before you act.
The header
text
X-MyPayments-Signature: t=1764784760,v1=9f2c4e…e1b7t: when we signed it, in Unix seconds.v1: hex HMAC-SHA256 of<t>.<raw body>, keyed with the endpoint's signing secret (the wholewhsec_…string).
Checking it
- Read the body as raw bytes, before any JSON parsing. Re-encoding parsed JSON changes the bytes and the signature will not match.
- Compute HMAC-SHA256 over
t, a dot, and the raw body, with your secret. - Compare with
v1in constant time. - Reject a
tmore than five minutes from now, so a captured request cannot be replayed later.
import { createHmac, timingSafeEqual } from "node:crypto";
const TOLERANCE = 300; // seconds
// rawBody: the request body exactly as received (a Buffer or string), before JSON parsing.
export function verifyMyPayments(rawBody, header, secret) {
const parts = Object.fromEntries(
String(header ?? "").split(",").map((p) => p.trim().split("=", 2)),
);
const t = Number(parts.t);
if (!parts.t || !parts.v1 || !Number.isInteger(t)) return false;
if (Math.abs(Date.now() / 1000 - t) > TOLERANCE) return false;
const expected = createHmac("sha256", secret).update(`${parts.t}.`).update(rawBody).digest();
const given = Buffer.from(parts.v1, "hex");
return given.length === expected.length && timingSafeEqual(given, expected);
}
// Express: keep the raw body for this route.
// app.post("/mypayments/webhook", express.raw({ type: "application/json" }), (req, res) => {
// if (!verifyMyPayments(req.body, req.get("X-MyPayments-Signature"), process.env.MYPAYMENTS_WEBHOOK_SECRET)) {
// return res.sendStatus(401);
// }
// const { event, transaction } = JSON.parse(req.body);
// res.sendStatus(200); // then fulfil once per transaction.uuid
// });Keep the secret on the server
Store the signing secret like a password (
MYPAYMENTS_WEBHOOK_SECRET in the examples). It is shown once, when you create the endpoint or rotate it. Each endpoint has its own.Rotating a secret
Rotate secret on an endpoint takes effect immediately: deliveries from then on are signed with the new one. To switch without rejecting anything, let your code accept either secret for a few minutes: deploy with both, rotate, put the new one in place, then drop the old.
Testing your check
Press Send test event on the endpoint in the dashboard: a signed webhook.test event arrives. Then change one character of a captured body and make sure your code refuses it. A callback_url delivery is signed with your primary endpoint's secret.