Webhooks

How to verify webhook signatures

Short answer

Mailcandor signs every webhook with Standard Webhooks. Take the webhook-id, webhook-timestamp and the raw request body, join them as id.timestamp.body, compute HMAC-SHA256 with the base64 part of your secret after mcws_, and base64 the result. It must match the value after v1, in the webhook-signature header. Reject timestamps more than five minutes old and compare in constant time.

Last checked 16 November 2026

Anyone who learns your webhook URL can send it a request. The signature proves a request came from Mailcandor and was not changed on the way. Check it on every request before you act on the body.

How the signature works

Every delivery carries three headers, as defined by Standard Webhooks:

Header Example Meaning
webhook-id b1c2... The message id. It stays the same on retries and replays.
webhook-timestamp 1763280000 Unix time in seconds when this attempt was signed.
webhook-signature v1,K5o...= v1, followed by the base64 signature.

To check it:

  1. Take your secret, drop the mcws_ prefix and base64-decode the rest. That is the HMAC key.
  2. Build the signed text: {webhook-id}.{webhook-timestamp}.{raw body}.
  3. Compute HMAC-SHA256 of that text with the key, and base64-encode it.
  4. Compare it with the part after v1, using a constant-time comparison.
  5. Reject the request if the timestamp is more than five minutes from your clock.

Store the secret in an environment variable. The examples use MAILCANDOR_WEBHOOK_SECRET.

Node.js (Express)

import crypto from 'node:crypto';
import express from 'express';

function verifyMailcandor(rawBody, headers, secret) {
  const id = headers['webhook-id'];
  const ts = headers['webhook-timestamp'];
  const sigHeader = headers['webhook-signature'];
  if (!id || !ts || !sigHeader) return false;
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;

  const key = Buffer.from(secret.slice('mcws_'.length), 'base64');
  const expected = crypto.createHmac('sha256', key).update(`${id}.${ts}.${rawBody}`).digest('base64');

  return sigHeader.split(' ').some((part) => {
    const [version, sig] = part.split(',');
    if (version !== 'v1' || !sig) return false;
    const a = Buffer.from(sig);
    const b = Buffer.from(expected);
    return a.length === b.length && crypto.timingSafeEqual(a, b);
  });
}

const app = express();
// express.raw keeps the exact bytes; express.json would break the signature.
app.post('/webhooks/mailcandor', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8');
  if (!verifyMailcandor(raw, req.headers, process.env.MAILCANDOR_WEBHOOK_SECRET)) {
    return res.status(401).send('bad signature');
  }
  const event = JSON.parse(raw);
  console.log(event.type, event.data);
  res.sendStatus(200);
});

app.listen(3000);

Python (Flask)

import base64, hashlib, hmac, os, time
from flask import Flask, request, abort

def verify_mailcandor(raw_body: bytes, headers, secret: str) -> bool:
    msg_id = headers.get("webhook-id")
    ts = headers.get("webhook-timestamp")
    sig_header = headers.get("webhook-signature")
    if not (msg_id and ts and sig_header):
        return False
    if abs(time.time() - int(ts)) > 300:
        return False
    key = base64.b64decode(secret.removeprefix("mcws_"))
    signed = f"{msg_id}.{ts}.".encode() + raw_body
    expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
    for part in sig_header.split(" "):
        version, _, sig = part.partition(",")
        if version == "v1" and hmac.compare_digest(sig, expected):
            return True
    return False

app = Flask(__name__)

@app.post("/webhooks/mailcandor")
def mailcandor_webhook():
    raw = request.get_data()
    if not verify_mailcandor(raw, request.headers, os.environ["MAILCANDOR_WEBHOOK_SECRET"]):
        abort(401)
    event = request.get_json()
    print(event["type"], event["data"])
    return "", 200

PHP

<?php
function verify_mailcandor(string $body, string $id, string $ts, string $sigHeader, string $secret): bool
{
    if ($id === '' || $ts === '' || $sigHeader === '') {
        return false;
    }
    if (abs(time() - (int) $ts) > 300) {
        return false;
    }
    $key = base64_decode(substr($secret, strlen('mcws_')));
    $expected = base64_encode(hash_hmac('sha256', "{$id}.{$ts}.{$body}", $key, true));
    foreach (explode(' ', $sigHeader) as $part) {
        [$version, $sig] = array_pad(explode(',', $part, 2), 2, '');
        if ($version === 'v1' && hash_equals($expected, $sig)) {
            return true;
        }
    }
    return false;
}

$body = file_get_contents('php://input');
$ok = verify_mailcandor(
    $body,
    $_SERVER['HTTP_WEBHOOK_ID'] ?? '',
    $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '',
    $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '',
    getenv('MAILCANDOR_WEBHOOK_SECRET')
);
if (!$ok) {
    http_response_code(401);
    exit;
}
$event = json_decode($body, true);
http_response_code(200);

Use the id to skip duplicates

Retries and replays reuse the same webhook-id. Save ids you have handled and skip a request whose id you have already seen. Answer it with 200 anyway, so it is not retried again.

Rotating the secret

Open the webhook and press Rotate secret, or call POST /v1/webhooks/{id}/rotate-secret. The old secret stops working at once, so put the new secret in your app first, or expect failed attempts until you do. Those can be replayed afterwards.

If it does not work

  • Every request fails. Your framework parsed the JSON before you checked it. Sign the raw body, byte for byte.
  • Wrong key. You used the whole secret string as the key. Drop mcws_ and base64-decode the rest.
  • Timestamp rejected. Your server clock is off. Sync it with NTP.
  • Worked, then stopped. Someone rotated the secret. Check the audit log for webhook.secret_rotated.
  • Headers missing. A proxy in front of your app strips unknown headers. Let webhook-* headers through.

More detail is in the API reference.

Questions

Where do I find the signing secret?

It is shown when you create the webhook. In the dashboard you can open the webhook and press Show signing secret at any time. It starts with mcws_.

Can I use a Standard Webhooks library instead of my own code?

Yes. Mailcandor follows the Standard Webhooks spec. Give the library the part of the secret after mcws_, which is the base64 key.

My code already verifies Resend webhooks. Does it work?

Yes. Mailcandor also sends the same values as svix-id, svix-timestamp and svix-signature. Use your Mailcandor secret with mcws_ replaced by whsec_.

Why does verification fail even with the right secret?

Almost always because the body was parsed and re-serialized before checking. Sign the raw bytes exactly as received.

Related

Send with someone on your side.

Unlimited domains on every plan, a person before any block, and 3,000 emails a month free. Tell us what you send and we set you up within one business day.