Verify Webhook Signatures
Prove a webhook really came from MailCraft with HMAC-SHA256 — examples in Node.js, PHP and Python.
Every webhook MailCraft sends carries a signature in the MailCraft-Signature header. Always verify it before trusting the payload, so nobody else can post fake events to your endpoint.
For the event types and their data fields see Webhooks.
Signature format
MailCraft-Signature: t=1765000000,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd
tis the send time (Unix seconds).v1is the lowercase hex HMAC-SHA256 of"<t>.<raw body>", keyed with your webhook secret.- While a secret is being rotated there may be several
v1=values; accept the request if any of them matches.
To verify:
- Read the raw body exactly as received. Do not parse and re-serialise the JSON — key order and whitespace may change.
- Extract
tand everyv1from the header. - Reject the request if
tis more than 300 seconds away from your clock (prevents replays). - Compute
HMAC-SHA256(secret, t + "." + raw_body)and compare it with eachv1using a constant-time comparison. - Answer
2xxonce you have accepted the event; answer400for a bad signature.
Each event has a unique id (evt_…). An event may be delivered more than once if an earlier attempt did not get a 2xx, so use the id to de-duplicate.
Node.js
With the Node.js SDK and Express — note express.raw(), which keeps the raw body:
import express from 'express';
import { parseEvent, WebhookVerificationError } from '@craftintertech/mailcraft';
const app = express();
app.post('/webhooks/mailcraft', express.raw({ type: 'application/json' }), (req, res) => {
try {
const event = parseEvent(req.body, req.get('MailCraft-Signature'), process.env.MAILCRAFT_WEBHOOK_SECRET!, {
tolerance: 300,
});
if (event.type === 'email.bounced') {
// mark the address as undeliverable
}
res.sendStatus(204);
} catch (err) {
if (err instanceof WebhookVerificationError) return res.status(400).send(err.code);
throw err;
}
});
Without the SDK, using only node:crypto:
import { createHmac, timingSafeEqual } from 'node:crypto';
function verify(rawBody: Buffer, header: string, secret: string, tolerance = 300): boolean {
const parts = header.split(',').map((p) => p.trim().split('='));
const t = Number(parts.find(([k]) => k === 't')?.[1]);
const sigs = parts.filter(([k]) => k === 'v1').map(([, v]) => v);
if (!t || Math.abs(Date.now() / 1000 - t) > tolerance) return false;
const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
return sigs.some((s) => {
const got = Buffer.from(s, 'hex');
return got.length === expected.length && timingSafeEqual(got, expected);
});
}
PHP
With the PHP SDK:
use CraftIntertech\MailCraft\Exception\WebhookVerificationException;
use CraftIntertech\MailCraft\Webhook;
$raw = (string) file_get_contents('php://input');
try {
$event = Webhook::parseEvent($raw, $_SERVER['HTTP_MAILCRAFT_SIGNATURE'] ?? null, getenv('MAILCRAFT_WEBHOOK_SECRET'), 300);
} catch (WebhookVerificationException $e) {
http_response_code(400);
exit;
}
http_response_code(204);
In Laravel use $request->getContent() for the raw body and $request->header('MailCraft-Signature').
Without the SDK:
function mailcraft_verify(string $raw, string $header, string $secret, int $tolerance = 300): bool {
$t = null; $sigs = [];
foreach (explode(',', $header) as $part) {
[$k, $v] = array_pad(explode('=', trim($part), 2), 2, '');
if ($k === 't') $t = (int) $v;
if ($k === 'v1') $sigs[] = $v;
}
if (!$t || abs(time() - $t) > $tolerance) return false;
$expected = hash_hmac('sha256', $t . '.' . $raw, $secret);
foreach ($sigs as $sig) {
if (hash_equals($expected, $sig)) return true;
}
return false;
}
Python
With the Python SDK and Flask:
import os
from flask import Flask, abort, request
from mailcraft import WebhookVerificationError, parse_event
app = Flask(__name__)
@app.post("/webhooks/mailcraft")
def mailcraft_webhook():
try:
event = parse_event(
request.get_data(), # raw bytes
request.headers.get("MailCraft-Signature"),
os.environ["MAILCRAFT_WEBHOOK_SECRET"],
tolerance=300,
)
except WebhookVerificationError as e:
abort(400, e.code)
print(event.id, event.type, event.data)
return "", 204
In Django use request.body and decorate the view with @csrf_exempt (the signature replaces the CSRF token).
Without the SDK:
import hashlib, hmac, time
def verify(raw_body: bytes, header: str, secret: str, tolerance: int = 300) -> bool:
pairs = [p.strip().split("=", 1) for p in header.split(",") if "=" in p]
t = next((int(v) for k, v in pairs if k == "t" and v.isdigit()), None)
if t is None or abs(time.time() - t) > tolerance:
return False
expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
return any(hmac.compare_digest(expected, v) for k, v in pairs if k == "v1")
Test locally
Every SDK can create a signature for tests (signPayload / Webhook::signPayload / sign_payload), or use OpenSSL:
BODY='{"id":"evt_test","type":"email.delivered","created_at":"2026-12-05T10:00:00Z","account_id":"acc_1","data":{}}'
T=$(date +%s)
SIG=$(printf '%s' "$T.$BODY" | openssl dgst -sha256 -hmac "$MAILCRAFT_WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -X POST http://localhost:3000/webhooks/mailcraft \
-H "Content-Type: application/json" \
-H "MailCraft-Signature: t=$T,v1=$SIG" \
--data "$BODY"