Verify Mautic webhooks

Mautic signs each delivery so you can confirm that it came from your instance and wasn't changed on the way. Webhook-Signature holds the base64 HMAC-SHA256 of the raw request body, keyed with the webhook's secret. Despite the header name this isn't Standard Webhooks: there's no webhook-id or webhook-timestamp. Mautic's docs describe the check but offer no SDK for it.

The facts

Signature header
Webhook-Signature

Format: <base64>, with no prefix

Scheme
HMAC-SHA256
Signed material
{raw body}

The JSON body exactly as sent, with no timestamp or other prefix.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Mautic webhook secret

One secret per webhook, randomly generated by default and editable in the webhook form ("customize the signature"). The sender signs only when a secret is set, and saving a webhook with none generates one. Keep it in an environment variable, not in source code.

  • Set on the webhook's form under **Webhooks**, where Mautic's docs call it customizing the signature.
  • Randomly generated unless you replace it, and unique to each webhook.
  • Use it as a plain string. Don't decode it or add a prefix.
  • Mautic recommends one webhook per app or script, so each secret is exposed in as few places as possible.

Source: Mautic docs ↗

Code

express/src/index.js
javascript
require('dotenv').config({ quiet: true });
const express = require('express');
const crypto = require('crypto');

const app = express();

/**
 * Verify the Mautic Webhook-Signature header.
 * Mautic sends base64(HMAC-SHA256(rawBody, secret)). Nothing else is signed.
 */
function verifyMauticWebhook(rawBody, signatureHeader, secret) {
  if (!signatureHeader || !secret) return false;

  const expected = crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('base64');

  try {
    return crypto.timingSafeEqual(
      Buffer.from(signatureHeader),
      Buffer.from(expected)
    );
  } catch {
    return false; // Different lengths = invalid
  }
}

// Mautic webhook endpoint. express.raw with '*/*' keeps the raw bytes for
// signature verification whatever Content-Type Mautic sends.
app.post('/webhooks/mautic',
  express.raw({ type: '*/*' }),
  (req, res) => {
    const signature = req.headers['webhook-signature'];

    if (!signature) {
      return res.status(400).send('Missing Webhook-Signature header');
    }

    if (!Buffer.isBuffer(req.body) || !verifyMauticWebhook(req.body, signature, process.env.MAUTIC_WEBHOOK_SECRET)) {
      console.error('Webhook signature verification failed');
      return res.status(400).send('Invalid signature');
    }

    // Parse the payload only after verification
    let payload;
    try {
      payload = JSON.parse(req.body.toString('utf8'));
    } catch {
      return res.status(400).send('Invalid JSON');
    }

    // The body is keyed by event type; each value is an array of events.
    // In queue mode one request can hold several types and several events per type.
    for (const [eventType, events] of Object.entries(payload)) {
      for (const event of Array.isArray(events) ? events : []) {
        handleEvent(eventType, event);
      }
    }

    res.status(200).send('OK');
  }
);

function handleEvent(eventType, event) {
  switch (eventType) {
    case 'mautic.lead_post_save_new':
      console.log('Contact identified:', event.contact?.id);
      // Your code: Sync new contact to CRM, etc.
      break;

    case 'mautic.lead_post_save_update':
      console.log('Contact updated:', event.contact?.id);
      // Your code: Update external record
      break;

    case 'mautic.lead_post_delete':
      console.log('Contact deleted:', event.id);
      // Your code: Remove external copies
      break;

    case 'mautic.lead_points_change':
      console.log('Points changed:', event.contact?.id, event.points?.old_points, '->', event.points?.new_points);
      break;

    case 'mautic.lead_channel_subscription_changed':
      console.log('Subscription changed:', event.channel, event.old_status, '->', event.new_status);
      break;

    case 'mautic.lead_company_change':
      console.log(event.added ? 'Contact added to company' : 'Contact removed from company');
      break;

    case 'mautic.company_post_save':
      console.log('Company saved:', event.company?.id);
      break;

    case 'mautic.company_post_delete':
      console.log('Company deleted:', event.id);
      break;

    case 'mautic.email_on_send':
      console.log('Email sent to contact:', event.contact?.id);
      break;

    case 'mautic.email_on_open':
      console.log('Email opened by contact:', event.stat?.lead?.id);
      break;

    case 'mautic.form_on_submit':
      console.log('Form submitted:', event.submission?.id);
      // Your code: Create a ticket, notify sales, etc.
      break;

    case 'mautic.page_on_hit':
      console.log('Page hit:', event.hit?.id);
      break;

    case 'mautic.sms_on_send':
      console.log('SMS sent:', event.smsId);
      break;

    default:
      console.log(`Unhandled event type: ${eventType}`);
  }
}

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

// Export app for testing
module.exports = { app, verifyMauticWebhook };

// Start server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/mautic`);
  });
}
nextjs/app/webhooks/mautic/route.ts
typescript
import { NextRequest, NextResponse } from 'next/server';
import { verifyMauticWebhook } from '../../../lib/verify';

export async function POST(request: NextRequest) {
  // Read the raw body (text) for signature verification, whatever the content type
  const body = await request.text();
  const signature = request.headers.get('webhook-signature');

  if (!signature) {
    return NextResponse.json({ error: 'Missing Webhook-Signature header' }, { status: 400 });
  }

  if (!verifyMauticWebhook(body, signature, process.env.MAUTIC_WEBHOOK_SECRET)) {
    console.error('Webhook signature verification failed');
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  // Parse the payload only after verification
  let payload: Record<string, unknown>;
  try {
    payload = JSON.parse(body);
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  // The body is keyed by event type; each value is an array of events.
  // In queue mode one request can hold several types and several events per type.
  for (const [eventType, events] of Object.entries(payload)) {
    if (!Array.isArray(events)) continue;
    for (const event of events) {
      handleEvent(eventType, event);
    }
  }

  return NextResponse.json({ received: true });
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function handleEvent(eventType: string, event: any) {
  switch (eventType) {
    case 'mautic.lead_post_save_new':
      console.log('Contact identified:', event.contact?.id);
      // Your code: Sync new contact to CRM, etc.
      break;

    case 'mautic.lead_post_save_update':
      console.log('Contact updated:', event.contact?.id);
      break;

    case 'mautic.lead_post_delete':
      console.log('Contact deleted:', event.id);
      break;

    case 'mautic.lead_points_change':
      console.log('Points changed:', event.contact?.id, event.points?.old_points, '->', event.points?.new_points);
      break;

    case 'mautic.lead_channel_subscription_changed':
      console.log('Subscription changed:', event.channel, event.old_status, '->', event.new_status);
      break;

    case 'mautic.lead_company_change':
      console.log(event.added ? 'Contact added to company' : 'Contact removed from company');
      break;

    case 'mautic.company_post_save':
      console.log('Company saved:', event.company?.id);
      break;

    case 'mautic.company_post_delete':
      console.log('Company deleted:', event.id);
      break;

    case 'mautic.email_on_send':
      console.log('Email sent to contact:', event.contact?.id);
      break;

    case 'mautic.email_on_open':
      console.log('Email opened by contact:', event.stat?.lead?.id);
      break;

    case 'mautic.form_on_submit':
      console.log('Form submitted:', event.submission?.id);
      // Your code: Create a ticket, notify sales, etc.
      break;

    case 'mautic.page_on_hit':
      console.log('Page hit:', event.hit?.id);
      break;

    case 'mautic.sms_on_send':
      console.log('SMS sent:', event.smsId);
      break;

    default:
      console.log(`Unhandled event type: ${eventType}`);
  }
}
fastapi/main.py
python
import os
import hmac
import hashlib
import base64
import json
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException

load_dotenv()

app = FastAPI()


def verify_mautic_webhook(raw_body: bytes, signature_header: str | None, secret: str | None) -> bool:
    """Verify the Mautic Webhook-Signature header.

    Mautic sends base64(HMAC-SHA256(raw_body, secret)). Nothing else is signed.
    """
    if not signature_header or not secret:
        return False

    expected = base64.b64encode(
        hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).digest()
    ).decode("utf-8")

    return hmac.compare_digest(signature_header.encode(), expected.encode())


def handle_event(event_type: str, event: dict) -> None:
    if event_type == "mautic.lead_post_save_new":
        print(f"Contact identified: {(event.get('contact') or {}).get('id')}")
        # Your code: Sync new contact to CRM, etc.
    elif event_type == "mautic.lead_post_save_update":
        print(f"Contact updated: {(event.get('contact') or {}).get('id')}")
    elif event_type == "mautic.lead_post_delete":
        print(f"Contact deleted: {event.get('id')}")
    elif event_type == "mautic.lead_points_change":
        points = event.get("points") or {}
        print(f"Points changed: {points.get('old_points')} -> {points.get('new_points')}")
    elif event_type == "mautic.lead_channel_subscription_changed":
        print(f"Subscription changed: {event.get('channel')} {event.get('old_status')} -> {event.get('new_status')}")
    elif event_type == "mautic.lead_company_change":
        print("Contact added to company" if event.get("added") else "Contact removed from company")
    elif event_type == "mautic.company_post_save":
        print(f"Company saved: {(event.get('company') or {}).get('id')}")
    elif event_type == "mautic.company_post_delete":
        print(f"Company deleted: {event.get('id')}")
    elif event_type == "mautic.email_on_send":
        print(f"Email sent to contact: {(event.get('contact') or {}).get('id')}")
    elif event_type == "mautic.email_on_open":
        print(f"Email opened by contact: {((event.get('stat') or {}).get('lead') or {}).get('id')}")
    elif event_type == "mautic.form_on_submit":
        print(f"Form submitted: {(event.get('submission') or {}).get('id')}")
        # Your code: Create a ticket, notify sales, etc.
    elif event_type == "mautic.page_on_hit":
        print(f"Page hit: {(event.get('hit') or {}).get('id')}")
    elif event_type == "mautic.sms_on_send":
        print(f"SMS sent: {event.get('smsId')}")
    else:
        print(f"Unhandled event type: {event_type}")


@app.post("/webhooks/mautic")
async def mautic_webhook(request: Request):
    # Raw bytes for signature verification, whatever the Content-Type
    raw_body = await request.body()
    signature = request.headers.get("webhook-signature")

    if not signature:
        raise HTTPException(status_code=400, detail="Missing Webhook-Signature header")

    if not verify_mautic_webhook(raw_body, signature, os.environ.get("MAUTIC_WEBHOOK_SECRET")):
        raise HTTPException(status_code=400, detail="Invalid signature")

    # Parse the payload only after verification
    try:
        payload = json.loads(raw_body)
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Invalid payload")

    # The body is keyed by event type; each value is a list of events.
    # In queue mode one request can hold several types and several events per type.
    for event_type, events in payload.items():
        if not isinstance(events, list):
            continue
        for event in events:
            handle_event(event_type, event if isinstance(event, dict) else {})

    return {"status": "success"}


@app.get("/health")
async def health():
    return {"status": "ok"}

From hookdeck/webhook-skills ↗

Or install the Mautic webhooks skill:

npx skills add hookdeck/webhook-skills --skill mautic-webhooks

Common failures

Standard Webhooks library

Mautic's Webhook-Signature shares its name with the Standard Webhooks header, but the value is a bare base64 digest of the body. A Standard Webhooks library will reject it, so compute the HMAC yourself.

Body parsed before verification

The signature covers the raw body. Read the bytes before any JSON parsing, because serializing parsed JSON again can change them.

Secret decoded, or from another webhook

Each webhook has its own secret, used as a plain string. Don't base64-decode it, and don't reuse one from another webhook.

Hex digest

Mautic's signature is base64, so compare base64 with base64.

From Hookdeck's Mautic guide

Let Event Gateway verify Mautic signatures.

Event Gateway verifies the signature on each Mautic delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Mautic. Facts are compiled from public sources and linked inline.