Verify Mercury webhooks
The Mercury-Signature header lets you confirm that a delivery came from Mercury and wasn't changed on the way. It holds a timestamp t and v1, a hex HMAC-SHA256 of the timestamp, a dot and the raw body, keyed with the signing secret Mercury returned when you created the endpoint. Mercury's docs have verification samples in TypeScript, JavaScript, Python and Ruby.
The event names on these pages are what you subscribe to with eventTypes. They aren't in the delivery: its body identifies the change with resourceType and operationType, so route on those.
The facts
{t}.{raw body} t from the Mercury-Signature header, a literal dot, then the body exactly as received. Re-serialised JSON will not verify.
Recompute an HMAC-SHA256 over the timestamp, a dot and the raw body, then compare it with v1. Mercury webhook secret
Each endpoint has its own signing secret, returned once in the secret field of the create response. GET and update never return it, so save it at creation. Keep it in an environment variable, not in source code.
- From the API:
POST /webhooksreturns it assecret. Mercury's Webhooks page calls the same valuesecretKey, but the API schema names the fieldsecret. - Format: Mercury's code samples use the string as the HMAC key directly, with no decoding.
- One chance: GET and update responses leave it out, so store it as soon as you create the endpoint.
- Sandbox: webhooks aren't available there, so every secret belongs to a production endpoint.
Source: Mercury docs ↗
Code
// Generated with: mercury-webhooks skill
// https://github.com/hookdeck/webhook-skills
const express = require('express');
const crypto = require('crypto');
require('dotenv').config({ quiet: true });
const app = express();
const PORT = process.env.PORT || 3000;
// Mercury signs every delivery with a Mercury-Signature header:
// t=<unix seconds>,v1=<hex>
// v1 is HMAC-SHA256 (hex) of "<t>.<raw body>", keyed with the endpoint's secret as-is.
// https://docs.mercury.com/reference/webhooks#verifying-webhook-signatures
// Optional replay window in seconds. Off by default (0): Hookdeck's retries and replays
// carry the original timestamp, so a window would reject late redeliveries.
// Set MERCURY_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
// treated as 0, with a warning.
let warnedInvalidTolerance = false;
function timestampToleranceSeconds() {
const raw = (process.env.MERCURY_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
if (raw === '') return 0;
if (!/^\d+$/.test(raw)) {
if (!warnedInvalidTolerance) {
console.warn(`MERCURY_TIMESTAMP_TOLERANCE_SECONDS=${JSON.stringify(raw)} is not a whole number of seconds; the timestamp check is off`);
warnedInvalidTolerance = true;
}
return 0;
}
return Number(raw);
}
timestampToleranceSeconds(); // surface an invalid value at startup
function safeEqual(a, b) {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
function parseSignatureHeader(header) {
const parts = {};
for (const kv of header.split(',')) {
const i = kv.indexOf('=');
if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim();
}
return parts;
}
function verifyMercury(rawBody, signatureHeader, secret) {
if (!secret || !signatureHeader) return false;
const { t, v1 } = parseSignatureHeader(signatureHeader);
if (!t || !v1) return false;
const ts = Number(t);
if (!Number.isInteger(ts)) return false;
// Mercury recommends rejecting timestamps older than 5 minutes. It's opt-in here: off unless
// MERCURY_TIMESTAMP_TOLERANCE_SECONDS > 0.
const tolerance = timestampToleranceSeconds();
if (tolerance > 0 && Math.abs(Math.floor(Date.now() / 1000) - ts) > tolerance) {
return false;
}
const expected = crypto
.createHmac('sha256', secret) // secret used as-is, not decoded
.update(`${t}.`)
.update(rawBody)
.digest('hex');
return safeEqual(v1, expected);
}
// Raw body is required: the signature covers the exact bytes Mercury sent.
// type: '*/*' reads the body whatever the Content-Type is, so verification never depends on it.
app.post('/webhooks/mercury', express.raw({ type: '*/*' }), (req, res) => {
const secret = process.env.MERCURY_WEBHOOK_SECRET;
if (!secret) {
console.error('MERCURY_WEBHOOK_SECRET is not set');
return res.status(500).send('Webhook secret not configured');
}
const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
if (!verifyMercury(rawBody, req.headers['mercury-signature'], secret)) {
console.error('Mercury webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
let event;
try {
event = JSON.parse(rawBody.toString('utf8'));
} catch {
return res.status(400).send('Invalid JSON');
}
// The eventTypes you subscribe to (transaction.created, ...) are not in the body.
// The body carries resourceType + operationType ("create" | "update" | "delete").
const key = `${event.resourceType}.${event.operationType}`;
switch (key) {
case 'transaction.create':
console.log(`Transaction ${event.resourceId} created: ${event.mergePatch?.status}`);
break;
case 'transaction.update':
console.log(`Transaction ${event.resourceId} updated: ${(event.changedPaths || []).join(', ')}`);
break;
case 'checkingAccount.update':
case 'savingsAccount.update':
case 'treasuryAccount.update':
case 'creditAccount.update':
case 'investmentAccount.update':
console.log(`${event.resourceType} ${event.resourceId} balance updated: ${(event.changedPaths || []).join(', ')}`);
break;
default:
console.log(`Unhandled event: ${key}`);
}
res.json({ received: true });
});
if (require.main === module) {
app.listen(PORT, () => {
console.log(`Mercury webhook server listening on http://localhost:${PORT}`);
});
}
module.exports = { app, verifyMercury }; // Generated with: mercury-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';
// Mercury signs every delivery with a Mercury-Signature header:
// t=<unix seconds>,v1=<hex>
// v1 is HMAC-SHA256 (hex) of "<t>.<raw body>", keyed with the endpoint's secret as-is.
// https://docs.mercury.com/reference/webhooks#verifying-webhook-signatures
// Optional replay window in seconds. Off by default (0): Hookdeck's retries and replays
// carry the original timestamp, so a window would reject late redeliveries.
// Set MERCURY_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
// treated as 0, with a warning.
let warnedInvalidTolerance = false;
function timestampToleranceSeconds(): number {
const raw = (process.env.MERCURY_TIMESTAMP_TOLERANCE_SECONDS ?? '').trim();
if (raw === '') return 0;
if (!/^\d+$/.test(raw)) {
if (!warnedInvalidTolerance) {
console.warn(`MERCURY_TIMESTAMP_TOLERANCE_SECONDS=${JSON.stringify(raw)} is not a whole number of seconds; the timestamp check is off`);
warnedInvalidTolerance = true;
}
return 0;
}
return Number(raw);
}
timestampToleranceSeconds(); // surface an invalid value at startup
function safeEqual(a: string, b: string): boolean {
const x = Buffer.from(a);
const y = Buffer.from(b);
return x.length === y.length && crypto.timingSafeEqual(x, y);
}
function parseSignatureHeader(header: string): Record<string, string> {
const parts: Record<string, string> = {};
for (const kv of header.split(',')) {
const i = kv.indexOf('=');
if (i > 0) parts[kv.slice(0, i).trim()] = kv.slice(i + 1).trim();
}
return parts;
}
function verifyMercury(rawBody: string, signatureHeader: string | null, secret: string): boolean {
if (!secret || !signatureHeader) return false;
const { t, v1 } = parseSignatureHeader(signatureHeader);
if (!t || !v1) return false;
const ts = Number(t);
if (!Number.isInteger(ts)) return false;
// Mercury recommends rejecting timestamps older than 5 minutes. It's opt-in here: off unless
// MERCURY_TIMESTAMP_TOLERANCE_SECONDS > 0.
const tolerance = timestampToleranceSeconds();
if (tolerance > 0 && Math.abs(Math.floor(Date.now() / 1000) - ts) > tolerance) {
return false;
}
const expected = crypto
.createHmac('sha256', secret) // secret used as-is, not decoded
.update(`${t}.${rawBody}`)
.digest('hex');
return safeEqual(v1, expected);
}
export async function POST(request: NextRequest) {
const secret = process.env.MERCURY_WEBHOOK_SECRET;
if (!secret) {
console.error('MERCURY_WEBHOOK_SECRET is not set');
return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
}
// Raw body: read as text before any JSON parsing, whatever the Content-Type is
const rawBody = await request.text();
if (!verifyMercury(rawBody, request.headers.get('mercury-signature'), secret)) {
console.error('Mercury webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
let event: any;
try {
event = JSON.parse(rawBody);
} catch {
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
}
// The eventTypes you subscribe to (transaction.created, ...) are not in the body.
// The body carries resourceType + operationType ("create" | "update" | "delete").
const key = `${event.resourceType}.${event.operationType}`;
switch (key) {
case 'transaction.create':
console.log(`Transaction ${event.resourceId} created: ${event.mergePatch?.status}`);
break;
case 'transaction.update':
console.log(`Transaction ${event.resourceId} updated: ${(event.changedPaths || []).join(', ')}`);
break;
case 'checkingAccount.update':
case 'savingsAccount.update':
case 'treasuryAccount.update':
case 'creditAccount.update':
case 'investmentAccount.update':
console.log(`${event.resourceType} ${event.resourceId} balance updated: ${(event.changedPaths || []).join(', ')}`);
break;
default:
console.log(`Unhandled event: ${key}`);
}
return NextResponse.json({ received: true });
} # Generated with: mercury-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hashlib
import hmac
import json
import logging
import os
import time
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request
load_dotenv()
logger = logging.getLogger("mercury-webhooks")
app = FastAPI()
# Mercury signs every delivery with a Mercury-Signature header:
# t=<unix seconds>,v1=<hex>
# v1 is HMAC-SHA256 (hex) of "<t>.<raw body>", keyed with the endpoint's secret as-is.
# https://docs.mercury.com/reference/webhooks#verifying-webhook-signatures
# Optional replay window in seconds. Off by default (0): Hookdeck's retries and replays
# carry the original timestamp, so a window would reject late redeliveries.
# Set MERCURY_TIMESTAMP_TOLERANCE_SECONDS to a positive whole number to opt in; any other value is
# treated as 0, with a warning.
_warned_invalid_tolerance = False
def timestamp_tolerance_seconds() -> int:
global _warned_invalid_tolerance
raw = (os.getenv("MERCURY_TIMESTAMP_TOLERANCE_SECONDS") or "").strip()
if not raw:
return 0
if not (raw.isascii() and raw.isdigit()):
if not _warned_invalid_tolerance:
logging.getLogger(__name__).warning(
"MERCURY_TIMESTAMP_TOLERANCE_SECONDS=%r is not a whole number of seconds; the timestamp check is off",
raw,
)
_warned_invalid_tolerance = True
return 0
return int(raw)
timestamp_tolerance_seconds() # surface an invalid value at startup
def parse_signature_header(header: str) -> dict:
parts = {}
for kv in header.split(","):
key, sep, value = kv.partition("=")
if sep and key.strip():
parts[key.strip()] = value.strip()
return parts
def verify_mercury(raw_body: bytes, signature_header, secret: str) -> bool:
if not secret or not signature_header:
return False
parts = parse_signature_header(signature_header)
t, v1 = parts.get("t"), parts.get("v1")
if not t or not v1:
return False
try:
ts = int(t)
except ValueError:
return False
# Mercury recommends rejecting timestamps older than 5 minutes. It's opt-in here: off unless
# MERCURY_TIMESTAMP_TOLERANCE_SECONDS > 0.
tolerance = timestamp_tolerance_seconds()
if tolerance > 0 and abs(time.time() - ts) > tolerance:
return False
signed = t.encode() + b"." + raw_body
# secret used as-is, not decoded
expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
return hmac.compare_digest(v1.encode(), expected.encode())
async def verified_body(request: Request) -> bytes:
"""Dependency: read the raw body and verify it before any JSON parsing."""
secret = os.getenv("MERCURY_WEBHOOK_SECRET", "")
if not secret:
logger.error("MERCURY_WEBHOOK_SECRET is not set")
raise HTTPException(status_code=500, detail="Webhook secret not configured")
raw_body = await request.body()
if not verify_mercury(raw_body, request.headers.get("mercury-signature"), secret):
logger.error("Mercury webhook signature verification failed")
raise HTTPException(status_code=400, detail="Invalid signature")
return raw_body
BALANCE_RESOURCES = {
"checkingAccount",
"savingsAccount",
"treasuryAccount",
"creditAccount",
"investmentAccount",
}
@app.post("/webhooks/mercury")
async def mercury_webhook(raw_body: bytes = Depends(verified_body)):
try:
event = json.loads(raw_body)
except json.JSONDecodeError:
raise HTTPException(status_code=400, detail="Invalid JSON")
# The eventTypes you subscribe to (transaction.created, ...) are not in the body.
# The body carries resourceType + operationType ("create" | "update" | "delete").
resource_type = event.get("resourceType")
key = f"{resource_type}.{event.get('operationType')}"
changed = ", ".join(event.get("changedPaths") or [])
if key == "transaction.create":
logger.info("Transaction %s created: %s", event.get("resourceId"), (event.get("mergePatch") or {}).get("status"))
elif key == "transaction.update":
logger.info("Transaction %s updated: %s", event.get("resourceId"), changed)
elif resource_type in BALANCE_RESOURCES and event.get("operationType") == "update":
logger.info("%s %s balance updated: %s", resource_type, event.get("resourceId"), changed)
else:
logger.info("Unhandled event: %s", key)
return {"received": True}
@app.get("/health")
async def health():
return {"status": "ok"} Or install the Mercury webhooks skill:
npx skills add hookdeck/webhook-skills --skill mercury-webhooks
Common failures
Body parsed before verification
The signature covers the exact bytes. Mercury warns that re-serialising the JSON changes whitespace and key order, which breaks the check.
Timestamp left out of the signed string
The signed message is t, a dot, then the body. A digest of the body alone never matches v1.
Wrong or lost secret
Each endpoint has its own secret, returned only by the create call, in a field named secret. If you've lost it, create a new endpoint, because GET and update won't return it.
A replay window rejects redeliveries
Mercury recommends rejecting timestamps older than 5 minutes. Deliveries that Hookdeck retries or replays keep their original t, so widen that window or drop it and deduplicate on id.
Let Event Gateway verify Mercury signatures.
Event Gateway verifies the signature on each Mercury delivery before it reaches your service, then queues it and retries failures on your schedule.