Webhooks

Check that a webhook really came from Morzepay.

Anyone can send a request to your webhook URL. The signature proves a webhook really came from Morzepay and wasn’t changed on the way. Check it on every webhook, before you do anything with it.

How the signature works#

Every webhook has a Morzepay-Signature header:

Header
Morzepay-Signature: t=1791127650,v1=5e8f0c7a9b...
  • t is when we signed it, in Unix seconds.
  • v1 is an HMAC-SHA256 of t + "." + raw_body, made with your signing secret, as hexadecimal.

To check it, make the same HMAC yourself and compare it with v1 in constant time. Also reject timestamps more than 5 minutes old, so an old webhook can’t be replayed.

Use the raw body exactly as received, before any JSON parsing. Parsing and re-encoding changes the bytes, and the signature won’t match.

Code#

<?php
$secret = getenv('MORZEPAY_WEBHOOK_SECRET');         // whsec_...
$body   = file_get_contents('php://input');          // the raw body
$header = $_SERVER['HTTP_MORZEPAY_SIGNATURE'] ?? '';

parse_str(str_replace(',', '&', $header), $sig);      // ['t' => ..., 'v1' => ...]
$expected = hash_hmac('sha256', ($sig['t'] ?? '') . '.' . $body, $secret);

if (!hash_equals($expected, $sig['v1'] ?? '') || abs(time() - (int) ($sig['t'] ?? 0)) > 300) {
    http_response_code(400);
    exit;
}

$event = json_decode($body, true);
// Skip events you've already handled ($event['id']), then use $event['data'].
http_response_code(200);
import crypto from 'node:crypto';
import express from 'express';

const app = express();

// express.raw keeps the body exactly as it arrived.
app.post('/webhooks/morzepay', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('Morzepay-Signature') || '';
  const sig = Object.fromEntries(header.split(',').map((p) => p.split('=')));
  const expected = crypto
    .createHmac('sha256', process.env.MORZEPAY_WEBHOOK_SECRET)
    .update(`${sig.t}.${req.body}`)
    .digest('hex');

  const fresh = Math.abs(Date.now() / 1000 - Number(sig.t)) <= 300;
  const valid = sig.v1 && sig.v1.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(sig.v1), Buffer.from(expected));
  if (!valid || !fresh) return res.sendStatus(400);

  const event = JSON.parse(req.body);
  // Skip events you've already handled (event.id), then use event.data.
  res.sendStatus(200);
});
import hashlib, hmac, json, os, time
from flask import Flask, request, abort

app = Flask(__name__)

@app.post('/webhooks/morzepay')
def morzepay_webhook():
    body = request.get_data()  # the raw body, as bytes
    parts = dict(p.split('=', 1) for p in request.headers.get('Morzepay-Signature', '').split(',') if '=' in p)
    expected = hmac.new(
        os.environ['MORZEPAY_WEBHOOK_SECRET'].encode(),
        parts.get('t', '').encode() + b'.' + body,
        hashlib.sha256,
    ).hexdigest()

    if not hmac.compare_digest(expected, parts.get('v1', '')) or abs(time.time() - int(parts.get('t', 0))) > 300:
        abort(400)

    event = json.loads(body)
    # Skip events you've already handled (event['id']), then use event['data'].
    return '', 200

Change the secret#

If you think your signing secret has leaked, go to Developers → Payment notifications, tick Generate a new signing secret and save. The old secret stops working at once, so update your server straight away.