Skip to content

Verify signatures ​

Every request is signed with the endpoint's secret. Verify the signature before processing the event: it is how you check that it comes from Mailiqo and that nobody changed the content on the way.

The signature follows the Standard Webhooks specification, so you can verify it with its libraries or by hand.

Headers ​

HeaderContent
webhook-idEvent identifier. It is the same on every delivery attempt
webhook-timestampTime of this delivery attempt, in Unix seconds. It changes on each retry
webhook-signatureOne or more signatures separated by spaces, each in the format v1,<base64 signature>

How it is computed ​

  1. Signed content: the value of webhook-id, a dot, the value of webhook-timestamp, another dot and the request body exactly as it arrives.
  2. Key: the secret without the whsec_ prefix, base64-decoded.
  3. Signature: the HMAC-SHA256 of the signed content with that key, base64-encoded.

To verify a request:

  • Compute the signature and compare it with each of the ones in webhook-signature. One match is enough. Use a constant-time comparison.
  • Reject the request if webhook-timestamp is more than 5 minutes away from the current time. That way a captured request cannot be sent again later.

Use the raw body

The signature is computed over the exact bytes of the body. If your framework turns the JSON into an object and you serialize it again, the result does not match and the signature fails. Read the raw body, verify, and only then parse the JSON.

EnvironmentHow to read the raw body
Expressexpress.raw({ type: 'application/json' }) on the webhook route
PHPfile_get_contents('php://input')
Laravel and Symfony$request->getContent()
Flaskrequest.get_data()
Djangorequest.body
FastAPIawait request.body()

With the Standard Webhooks libraries ​

bash
npm install standardwebhooks                          # Node.js
composer require standard-webhooks/standard-webhooks  # PHP
pip install standardwebhooks                          # Python

Pass the secret exactly as the panel shows it, with the whsec_ prefix. The libraries check the signature and the age of webhook-timestamp.

js
import express from 'express';
import { Webhook } from 'standardwebhooks';

const app = express();
const webhook = new Webhook(process.env.MAILIQO_WEBHOOK_SECRET);

app.post('/webhooks/mailiqo', express.raw({ type: 'application/json' }), (req, res) => {
  let event;
  try {
    event = webhook.verify(req.body, req.headers);
  } catch (err) {
    return res.status(400).end();
  }

  // Put the event on a queue and answer right away.
  res.status(204).end();
});
php
<?php

require 'vendor/autoload.php';

$payload = file_get_contents('php://input');
$headers = [
    'webhook-id' => $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    'webhook-timestamp' => $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    'webhook-signature' => $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
];

try {
    $webhook = new \StandardWebhooks\Webhook(getenv('MAILIQO_WEBHOOK_SECRET'));
    $event = $webhook->verify($payload, $headers);
} catch (\StandardWebhooks\Exception\WebhookVerificationException $e) {
    http_response_code(400);
    exit;
}

// Put the event on a queue and answer right away.
http_response_code(204);
python
import json
import os

from flask import Flask, request
from standardwebhooks.webhooks import Webhook, WebhookVerificationError

app = Flask(__name__)
webhook = Webhook(os.environ['MAILIQO_WEBHOOK_SECRET'])


@app.post('/webhooks/mailiqo')
def mailiqo_webhook():
    payload = request.get_data()
    try:
        webhook.verify(payload, request.headers)
    except WebhookVerificationError:
        return '', 400

    event = json.loads(payload)
    # Put the event on a queue and answer right away.
    return '', 204

Without libraries ​

If you would rather not add a dependency, verification is a few lines:

js
import crypto from 'node:crypto';

const TOLERANCE_SECONDS = 300;

export function verifyMailiqoSignature(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const timestamp = headers['webhook-timestamp'];
  const signatures = headers['webhook-signature'];
  if (!id || !timestamp || !signatures) return false;

  const age = Math.abs(Date.now() / 1000 - Number(timestamp));
  if (!(age <= TOLERANCE_SECONDS)) return false;

  const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
  const expected = crypto
    .createHmac('sha256', key)
    .update(`${id}.${timestamp}.`)
    .update(rawBody)
    .digest();

  return signatures.split(' ').some((entry) => {
    const [version, signature] = entry.split(',');
    if (version !== 'v1' || !signature) return false;
    const received = Buffer.from(signature, 'base64');
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}
php
<?php

function verifyMailiqoSignature(string $rawBody, string $id, string $timestamp, string $signatures, string $secret): bool
{
    if ($id === '' || abs(time() - (int) $timestamp) > 300) {
        return false;
    }

    $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
    $expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $rawBody, $key, true));

    foreach (explode(' ', $signatures) as $entry) {
        [$version, $signature] = array_pad(explode(',', $entry, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $signature)) {
            return true;
        }
    }

    return false;
}

$valid = verifyMailiqoSignature(
    file_get_contents('php://input'),
    $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
    getenv('MAILIQO_WEBHOOK_SECRET')
);
python
import base64
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify_mailiqo_signature(raw_body: bytes, headers, secret: str) -> bool:
    event_id = headers.get('webhook-id', '')
    timestamp = headers.get('webhook-timestamp', '')
    signatures = headers.get('webhook-signature', '')
    if not event_id or not timestamp.isdigit():
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    key = base64.b64decode(secret.removeprefix('whsec_'))
    signed_content = f'{event_id}.{timestamp}.'.encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed_content, hashlib.sha256).digest()).decode()

    return any(
        hmac.compare_digest(expected, entry.partition(',')[2])
        for entry in signatures.split(' ')
        if entry.startswith('v1,')
    )

Header names are case-insensitive. Some servers hand them over in another form, such as Webhook-Id or HTTP_WEBHOOK_ID.

Rotate the secret ​

In the domain's Webhooks tab, open the endpoint's ⋯ menu and click Rotate secret. A new secret is generated and shown only once.

For the next 24 hours every event carries two signatures, one with the new secret and one with the previous one, separated by a space. Your server keeps validating with the previous secret until you deploy the new one, and you lose no events during the change. After 24 hours only the new one is used.

The libraries and the examples on this page already check every signature in the header.

If you think the secret has leaked, rotate it and deploy the new one as soon as you can: once your server stops using the previous one, a signature made with it is no longer valid for you.

To make the previous secret stop signing without waiting for the 24 hours, click Expire now next to the notice about the previous secret. Do it once your server already uses the new one: from then on, events carry a single signature.

Where to keep the secret ​

  • In an environment variable or a secrets manager, not in the code or the repository.
  • Each endpoint has its own secret. If you receive events from several domains, use the secret of the endpoint that matches each URL.
  • The testing secret, which starts with whsec_test, is only for your development environments. See Testing.

Built with VitePress