Skip to content

Webhooks

Verify the signature

How to confirm that a webhook really came from Messajo, with examples in several languages.

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.

Every delivery carries the Messajo-Signature header:

Messajo-Signature: t=1762697007,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
  • t is the signing time, in Unix seconds. It appears only once.
  • v1 is the HMAC-SHA256 in hexadecimal. During secret rotation there are two v1, 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.

  1. Read the request’s raw body, exactly the bytes that arrived, before any JSON parsing.
  2. Split t and the v1 values out of the header.
  3. Build the message ${t}.${body} — the timestamp, a dot and the raw body.
  4. Compute the HMAC-SHA256 of that message using the whole secret as the key, whsec_ prefix included, in UTF-8. Output in lowercase hexadecimal.
  5. Compare with each v1 in constant time (timingSafeEqual, hmac.compare_digest, hash_equals). Comparing with == leaks information through response time.
  6. Reject if t is 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).

The three examples use no external library and are tested on every build against Messajo’s signer.

verify.ts
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)
);
});
}
verify.py
"""Verify a Messajo webhook signature.
Usage: python3 verify.py <secret> <Messajo-Signature header> < raw_body
Exit code 0 = valid signature, 1 = invalid.
"""
import hashlib
import hmac
import sys
import 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)
verify.php
<?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.

  1. In the Webhook node, under Options, turn on Raw Body.
  2. After it, a Code node (JavaScript) with the Node.js example code, reading the messajo-signature header and the raw body of the incoming item.
  3. The Code node only loads crypto if n8n allows it: set NODE_FUNCTION_ALLOW_BUILTIN=crypto in n8n’s environment and restart it.
  4. Invalid signature → stop the flow (a Stop and Error node or an IF).
  1. 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.

  2. Pick the overlap window: from 0 to 72 hours, 24 hours by default (keep_previous_hours in the API). During the window both are valid and each delivery carries two v1, first the new secret’s, then the old one’s:

    Messajo-Signature: t=1762697007,v1=<hmac with the new>,v1=<hmac with the old>
  3. Swap the secret in your application within the window. Since one matching v1 is enough, there is no moment when events get rejected. The end of the window shows on the destination (previous_secret_expires_at in the API).

  4. 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.

  • 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.