Webhooks
Verify the signature
How to confirm that a webhook really came from Messajo, with examples in several languages.
Why verify
Section titled “Why verify”Your webhook URL is public. Without checking the signature, anyone who finds the URL can send fake events — a made-up “message received”, a “payment” that never happened. The signature proves the body came from Messajo, with your secret, and was not changed on the way. The timestamp inside it stops someone from recording a delivery and replaying it later.
The header
Section titled “The header”Every delivery carries the Messajo-Signature header:
Messajo-Signature: t=1762697007,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bdtis the signing time, in Unix seconds. It appears only once.v1is the HMAC-SHA256 in hexadecimal. During secret rotation there are twov1, one per active secret: one match is enough.- Ignore schemes you don’t know (a future
v2=, for example).
The destination secret starts with whsec_ and is shown only once, when you create the destination (in the dashboard or in the POST /v1/destinations response). After that the dashboard shows only its last 4 characters. Lost it? Rotate the secret.
Step by step
Section titled “Step by step”- Read the request’s raw body, exactly the bytes that arrived, before any JSON parsing.
- Split
tand thev1values out of the header. - Build the message
${t}.${body}— the timestamp, a dot and the raw body. - Compute the HMAC-SHA256 of that message using the whole secret as the key,
whsec_prefix included, in UTF-8. Output in lowercase hexadecimal. - Compare with each
v1in constant time (timingSafeEqual,hmac.compare_digest,hash_equals). Comparing with==leaks information through response time. - Reject if
tis more than 5 minutes away from your clock, in the past or in the future.
Invalid signature → respond 400 and drop the event. Valid → respond 2xx fast and process later (see Events).
Examples
Section titled “Examples”The three examples use no external library and are tested on every build against Messajo’s signer.
Node.js
Section titled “Node.js”import { createHmac, timingSafeEqual } from "node:crypto";
const TOLERANCE_SECONDS = 300;const DIGITS = /^\d+$/;
/** * Checks the Messajo-Signature header ("t=<unix s>,v1=<hex>[,v1=<hex>…]"). * `rawBody` must be the exact body received, before any JSON parsing. */export function verify( header: string, rawBody: string, secret: string, nowSeconds: number = Math.floor(Date.now() / 1000)): boolean { const timestamps: string[] = []; const signatures: string[] = []; for (const part of header.split(",")) { const [key, value = ""] = part.trim().split("=", 2); if (key === "t") { timestamps.push(value); } else if (key === "v1") { signatures.push(value); } } const [rawTimestamp = ""] = timestamps; if (timestamps.length !== 1 || !DIGITS.test(rawTimestamp)) { return false; } const timestamp = Number(rawTimestamp); if (Math.abs(nowSeconds - timestamp) > TOLERANCE_SECONDS) { return false; } const expected = Buffer.from( createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex") ); return signatures.some((signature) => { const received = Buffer.from(signature); return ( received.length === expected.length && timingSafeEqual(received, expected) ); });}Python
Section titled “Python”"""Verify a Messajo webhook signature.
Usage: python3 verify.py <secret> <Messajo-Signature header> < raw_bodyExit code 0 = valid signature, 1 = invalid."""
import hashlibimport hmacimport sysimport time
TOLERANCE_SECONDS = 300
def verify(header: str, raw_body: bytes, secret: str, now: int | None = None) -> bool: """`raw_body` must be the exact bytes received, before any JSON parsing.""" timestamps, signatures = [], [] for part in header.split(","): key, _, value = part.strip().partition("=") if key == "t": timestamps.append(value) elif key == "v1": signatures.append(value) if len(timestamps) != 1 or not (timestamps[0].isascii() and timestamps[0].isdigit()): return False timestamp = int(timestamps[0]) now = int(time.time()) if now is None else now if abs(now - timestamp) > TOLERANCE_SECONDS: return False signed = f"{timestamp}.".encode() + raw_body expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest() return any(hmac.compare_digest(expected, signature) for signature in signatures)
if __name__ == "__main__": secret, header = sys.argv[1], sys.argv[2] sys.exit(0 if verify(header, sys.stdin.buffer.read(), secret) else 1)<?php// Verify a Messajo webhook signature.// Usage: php verify.php <secret> <Messajo-Signature header> < raw_body// Exit code 0 = valid signature, 1 = invalid.
const MESSAJO_TOLERANCE_SECONDS = 300;
// $rawBody must be the exact body received, before json_decode.function messajo_verify(string $header, string $rawBody, string $secret, ?int $now = null): bool{ $timestamps = []; $signatures = []; foreach (explode(',', $header) as $part) { [$key, $value] = array_pad(explode('=', trim($part), 2), 2, ''); if ($key === 't') { $timestamps[] = $value; } elseif ($key === 'v1') { $signatures[] = $value; } } if (count($timestamps) !== 1 || !ctype_digit($timestamps[0])) { return false; } $timestamp = (int) $timestamps[0]; if (abs(($now ?? time()) - $timestamp) > MESSAJO_TOLERANCE_SECONDS) { return false; } $expected = hash_hmac('sha256', "{$timestamp}.{$rawBody}", $secret); foreach ($signatures as $signature) { if (hash_equals($expected, $signature)) { return true; } } return false;}
if (PHP_SAPI === 'cli' && realpath($argv[0]) === __FILE__) { exit(messajo_verify($argv[2], file_get_contents('php://stdin'), $argv[1]) ? 0 : 1);}How to get the raw body in each framework:
| Framework | Raw body |
|---|---|
| Express | app.post("/webhook", express.raw({ type: "application/json" }), …) and req.body.toString("utf8") |
| Hono | await c.req.text() |
| FastAPI | await request.body() |
| Laravel | $request->getContent() |
Use the raw body for verification and only then run JSON.parse / json.loads / json_decode.
- In the Webhook node, under Options, turn on Raw Body.
- After it, a Code node (JavaScript) with the Node.js example code, reading the
messajo-signatureheader and the raw body of the incoming item. - The Code node only loads
cryptoif n8n allows it: setNODE_FUNCTION_ALLOW_BUILTIN=cryptoin n8n’s environment and restart it. - Invalid signature → stop the flow (a Stop and Error node or an IF).
Rotate the secret without downtime
Section titled “Rotate the secret without downtime”-
In the dashboard, open the destination and click Rotate secret, or call
POST /v1/destinations/{id}/rotate-secret. Messajo generates a new secret and shows it only once. -
Pick the overlap window: from 0 to 72 hours, 24 hours by default (
keep_previous_hoursin the API). During the window both are valid and each delivery carries twov1, first the new secret’s, then the old one’s:Messajo-Signature: t=1762697007,v1=<hmac with the new>,v1=<hmac with the old> -
Swap the secret in your application within the window. Since one matching
v1is enough, there is no moment when events get rejected. The end of the window shows on the destination (previous_secret_expires_atin the API). -
Once the window is over, the old secret stops signing and deliveries go back to a single
v1.
With a 0 window the old secret stops signing right away: use it only when the secret leaked. Rotating again within the window drops the older one: only the current secret and the one it just replaced stay valid.
Common mistakes
Section titled “Common mistakes”- Re-serialized JSON. The framework parsed the body and you signed
JSON.stringify(req.body). Whitespace, key order and escaping of accents change and the HMAC no longer matches. Use the raw body. - Wrong clock. A server without NTP drifts outside the 5 minutes and rejects everything as stale. Sync the clock.
- Secret with whitespace. A space or line break at the end of the copied secret (common in
.env). Check its length and trim it. - Secret without the prefix. The HMAC key is the whole secret, with
whsec_. - Body decoded with another charset. Read the bytes as UTF-8; accents and emoji matter.