Gareth Wilson Gareth Wilson

Guide to Modem Pay Webhooks: Features and Best Practices

Published


Modem Pay is a payments platform licensed by the Central Bank of The Gambia. It accepts Wave, Afrimoney, QMoney, APS, cards and bank transfers through one API, and sends payouts. Its webhooks tell your server when a customer, payment intent, charge or transfer changes, so you can fulfil orders and reconcile payouts without polling.

This guide covers the events Modem Pay sends, verifying the x-modem-signature header against the raw body, testing with the Modem Pay CLI, and handling retries that can deliver the same event more than once.

What are Modem Pay webhooks?

Modem Pay sends a POST request to your endpoint when something happens in your account. The body is JSON with two fields: event, the event type, and payload, the object it's about. Each request carries an x-modem-signature header, an HMAC-SHA512 of the body keyed with your webhook secret.

You generate the webhook secret in the Modem Pay dashboard under Developers > Webhooks. Test mode has its own secret, which the Modem Pay CLI also prints.

Modem Pay webhook features

FeatureDetails
ConfigurationModem Pay dashboard, Developers > Webhooks
EventsCustomer, payment intent, charge and transfer events
BodyJSON: { "event": "...", "payload": { ... } }, sent with POST
Signaturehex HMAC-SHA512 of the request body
Signature headerx-modem-signature
Timestamp or event ID headerNone
RetriesUp to 3, spaced 10 minutes apart, after a timeout, network error or non-2xx response
Testingmodem-pay-cli: modempay listen and modempay trigger <event>, test mode only
Content type, timeout, source IPsNot documented

Events and payloads

Modem Pay's webhooks page lists these events:

GroupEvents
Customercustomer.created, customer.updated, customer.deleted
Payment intentpayment_intent.created, payment_intent.cancelled, payment_intent.expired
Chargecharge.succeeded, charge.cancelled, charge.created, charge.updated, charge.expired
Transfer (payout)transfer.succeeded, transfer.cancelled, transfer.reversed, transfer.failed, transfer.flagged

The CLI's trigger list also includes charge.failed, and the Laravel example handles it, but the webhooks page doesn't list it. Handle it if it arrives, and acknowledge any event you don't recognise.

Modem Pay's sample charge.succeeded body looks like this (customer details and payment_metadata trimmed):

{
  "event": "charge.succeeded",
  "payload": {
    "id": "23419194-7324-4c2b-a74b-d8fba736e692",
    "type": "payment",
    "amount": 2500,
    "currency": "GMD",
    "payment_method": "qmoney",
    "customer": "0f6e0912-2f2f-4d8b-bd68-ac8c97c44ae6",
    "metadata": {},
    "status": "completed",
    "payment_link_id": null,
    "business_id": "a10a51ae-05c8-406e-968c-7b1d309a77e0",
    "account_id": "7788dd90-3801-47a6-8597-b46eaa0a7d7d",
    "test_mode": true,
    "createdAt": "2024-12-15T09:34:17.036Z",
    "updatedAt": "2024-12-15T09:34:43.306Z",
    "payment_intent_id": "273ac751-369d-4198-8340-da480208bded",
    "transaction_reference": "VOAO1CFEN7",
    "payment_method_id": "4dbaaec5-7a16-4908-8fd9-c3d2bd24f739"
  }
}

These are the fields of a Modem Pay transaction, whose status is one of pending, completed, failed, refunded or cancelled. test_mode tells test events from live ones. Modem Pay doesn't publish sample bodies for the other events, so capture one of each before you rely on their fields.

Inspect Modem Pay webhooks as they arrive. Point Modem Pay at a Hookdeck Inspect URL and trigger an event to see the exact body and headers, with no account or setup required.

Setting up Modem Pay webhooks

  1. Create an HTTPS endpoint that accepts POST.
  2. In the Modem Pay dashboard, go to Developers > Webhooks, generate the webhook secret, and store it as MODEM_PAY_WEBHOOK_SECRET.
  3. Set your endpoint as the webhook URL. The docs don't describe this form, so check the URL in the dashboard after saving.
  4. Return 200 quickly, and do the work afterwards.

For local testing, the Modem Pay CLI forwards test-mode events through a Localtunnel URL and prints the test-mode signing secret:

npm install -g modem-pay-cli
modempay login
modempay listen --forward-url=http://localhost:3000/webhooks/modem-pay
modempay trigger charge.succeeded

Use the secret that listen prints while testing. The live secret is separate, and test-mode settings don't affect live endpoints.

To route through Hookdeck, create a source with the Modem Pay type, paste the webhook secret as the Webhook Signing Secret, and set the source URL as your webhook URL in Modem Pay. The source accepts POST only. For local development:

npx hookdeck-cli listen 3000 modem-pay --path /webhooks/modem-pay

Securing Modem Pay webhooks

x-modem-signature is the hex HMAC-SHA512 of the request body, keyed with the webhook secret as plain text. There's no timestamp or version prefix. Compute the HMAC over the raw bytes you received and compare it in constant time.

Don't follow Modem Pay's examples on this point. Its raw Node example hashes JSON.stringify(req.body) after a JSON parser has run, and its raw Python example hashes json.dumps(request.json), which adds spaces after separators. Its Python SDK sorts the keys when you pass it a dict. Those produce different bytes, so they can't all match what Modem Pay signs. The SDKs' composeEventDetails and compose_event_details hash a string payload exactly as given, so if you use them, pass the raw body as a string.

Node.js verification

const crypto = require('node:crypto');

function verifyModemPaySignature(rawBody, signature, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof signature !== 'string' || typeof secret !== 'string' || !secret) {
    return false;
  }
  if (!/^[0-9a-fA-F]{128}$/.test(signature)) return false;
  const expected = crypto.createHmac('sha512', secret).update(rawBody).digest();
  return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected);
}

The handler verifies the request, acknowledges events it doesn't handle, and queues the rest with a hash of the raw body as a dedupe key. Act on the event in the worker.

const express = require('express');

const app = express();
const HANDLED_EVENTS = new Set(['charge.succeeded', 'charge.failed', 'transfer.succeeded', 'transfer.failed']);

app.post('/webhooks/modem-pay', express.raw({ type: '*/*' }), async (req, res) => {
  const secret = process.env.MODEM_PAY_WEBHOOK_SECRET;
  if (!secret) return res.sendStatus(500);
  if (!verifyModemPaySignature(req.body, req.get('x-modem-signature'), secret)) {
    return res.sendStatus(401);
  }

  let event;
  try {
    event = JSON.parse(req.body.toString('utf8'));
  } catch {
    return res.sendStatus(400);
  }
  if (!event || typeof event !== 'object') return res.sendStatus(400);
  if (!HANDLED_EVENTS.has(event.event)) return res.sendStatus(200); // acknowledge events you don't handle

  const dedupeKey = crypto.createHash('sha256').update(req.body).digest('hex');
  try {
    if (await alreadyHandled(dedupeKey)) return res.sendStatus(200);
    await queue.add('modem-pay-event', { type: event.event, id: event.payload?.id, dedupeKey });
    await markHandled(dedupeKey);
  } catch {
    return res.sendStatus(503);
  }
  res.sendStatus(200);
});

queue, alreadyHandled and markHandled are placeholders for your queue and dedupe storage. A hash of the body catches identical retries. Modem Pay doesn't say whether a retry is byte-for-byte identical, so make the worker idempotent too. For example, mark an order paid only once, whatever number of charge.succeeded events arrive for its transaction.

Python verification

import hashlib
import hmac
import re

HEX_128 = re.compile(r"[0-9a-fA-F]{128}")


def verify_modem_pay_signature(raw_body: bytes, signature, secret) -> bool:
    if not isinstance(raw_body, bytes) or not signature or not secret:
        return False
    if not HEX_128.fullmatch(signature):
        return False
    expected = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha512).hexdigest()
    return hmac.compare_digest(signature.lower(), expected)

In Flask, pass request.get_data() as raw_body, not request.json re-encoded.

Hookdeck's Modem Pay source checks the same signature over the raw body with the secret you paste, and accepts upper- or lower-case hex. It returns 200 to Modem Pay either way and records any mismatch as failed verification, so those requests never reach your service. Hookdeck forwards the original body and headers, so your service can verify x-modem-signature again with the same code.

Make Modem Pay webhooks production-ready. Hookdeck Event Gateway verifies every Modem Pay delivery, stores it, and retries your service on a schedule you control, so a deploy or outage doesn't cost you a payment event.

Modem Pay webhook limitations and pain points

The documented examples hash a re-serialised body

The Problem: A verifier copied from Modem Pay's docs can reject genuine events, or pass in testing and fail later.

Why It Happens: The examples parse the JSON and serialise it again before hashing. Key order, spacing and number formatting can all change, so the hashed bytes may not be the ones Modem Pay signed.

Workarounds:

  • Read the raw body before any JSON parser runs, and hash those bytes.
  • If you use an SDK, pass the raw body as a string so it isn't re-serialised.

How Hookdeck Can Help: Hookdeck verifies the signature against the raw bytes it received, and keeps them, so you can compare what arrived with what your code hashed.

No timestamp or event ID

The Problem: You can't reject an old request that someone captured and replayed, and there's no ID to deduplicate on.

Why It Happens: The signature covers only the body. Modem Pay doesn't document a timestamp or delivery ID header, and the body has no event ID.

Workarounds:

  • Deduplicate on a hash of the raw body, or on the event type plus payload.id and payload.updatedAt.
  • Make state changes idempotent, and confirm important ones with GET https://api.modempay.com/v1/transactions/{id} before acting.
  • Keep the webhook secret server-side, because anyone who has it can sign a request.

How Hookdeck Can Help: Hookdeck can deduplicate requests before they reach your service, and its request log shows every delivery Modem Pay made.

Three retries, ten minutes apart

The Problem: An outage of around half an hour can lose events.

Why It Happens: Modem Pay retries a failed delivery up to 3 times, 10 minutes apart, and doesn't document anything after that. Timeouts count as failures, but the timeout isn't documented.

Workarounds:

  • Respond with 200 before doing any slow work.
  • Reconcile against the Transactions API after an outage.

How Hookdeck Can Help: Hookdeck answers Modem Pay immediately, so deliveries succeed even while your service is down. It then gives your service its own retries, and issues alert you when deliveries fail.

Gaps in the documentation

The Problem: Some details you'd want for a production receiver aren't written down.

Why It Happens: Modem Pay doesn't document the content type, the timeout, source IP addresses, or the form you use to register the endpoint, and it publishes a sample body only for charge.succeeded.

Workarounds:

  • Trigger each event you handle in test mode and record the request.
  • Parse defensively and ignore fields you don't recognise.

How Hookdeck Can Help: Hookdeck stores every request with its full headers and body, so you can see the exact shape of each event and replay it against your handler while you build it.

Best practices

Verify the raw body

The signature covers the exact bytes. Read the raw body before any JSON parser touches it, and use the secret for the mode you're in.

Make handlers idempotent

Retries can deliver an event more than once, and there's no event ID. Deduplicate, and design each state change so that applying it twice does no harm. See our guide to webhook idempotency.

Acknowledge fast and process asynchronously

Verify, queue and return 200, then act in a worker. See why to process webhooks asynchronously.

Check test_mode

Make sure a test event can't fulfil a live order. Check payload.test_mode and keep test and live secrets apart.

Conclusion

Modem Pay sends customer, payment intent, charge and transfer events as { event, payload } JSON, signed with a hex HMAC-SHA512 of the body in x-modem-signature. Verify the raw bytes rather than re-serialised JSON, return 200 fast, and deduplicate, because a failed delivery is retried up to 3 times and nothing in the request identifies a retry.

Hookdeck Event Gateway verifies Modem Pay deliveries and holds each event until your service has processed it.

Get started with Hookdeck for free and handle Modem Pay webhooks reliably in minutes.


Gareth Wilson

Gareth Wilson

Product Marketing

Multi-time founding marketer, Gareth is PMM at Hookdeck and author of the newsletter, Community Inc.