Skip to content

Build and operate

Webhooks and callbacks

Callbacks and webhooks compared, and a callback endpoint step by step: verify the signature in Node.js, Python, PHP, Go and C#, dedupe on event_id, handle retries, resend and test, and meet the TLS deadline.

Callbacks and webhooks

Moolre can tell your server about results in two ways. Callbacks, described on this page, are one POST per collection, payment link payment or bulk batch, sent to a callback URL: the callback set on the wallet (Create account or Update account), or the one you passed for a payment link or a bulk batch. Webhooks are switched on per wallet, go to webhook_url, and also cover payouts and settlements.

Both are signed, retried and listed in the same way. A callback is a notification, not a command. Your endpoint should prove the request came from Moolre, make sure it has not already handled this event, record it, answer with a 2xx status within a few seconds, and do the slow work afterwards. Anything that is not a 2xx answer within 20 seconds counts as a failed attempt and is retried.

Your endpoint doesBecause
Reads the raw bodyThe signature covers the exact bytes Moolre sent
Verifies X-Moolre-SignatureOnly Moolre knows your wallet secret
Rejects old timestampsStops an attacker replaying a captured request
Dedupes on event_idThe same event can arrive more than once
Answers 2xx fastA slow or failing answer triggers retries
Does the work afterwardsKeeps the endpoint fast and the retries rare

Looking for payout or settlement results?

Single payouts, the payouts of a bulk batch and settlements send no callback. Switch on webhooks (payout.* and settlement.*), or check Transfer Status.

Step by step: build the endpoint

  1. Create a POST route on an HTTPS URL that is reachable from the internet, for example https://shop.example.com/moolre/callback. It must serve a valid public TLS certificate with the full chain (see the TLS deadline below).
  2. Read the request body as raw bytes or an unparsed string. Do not let your framework parse and re-serialise the JSON first: that changes bytes and breaks the signature.
  3. Read the X-Moolre-Signature header. It looks like t=1763200000,v1=095ff674… where t is a Unix time and v1 is a hex HMAC.
  4. Find your wallet secret: the secret field of Create Account and Update Account, or the wallet in the Moolre app. It stays the same when you switch callbacks or API access off and on again.
  5. Compute HMAC-SHA256 with your wallet secret as the key over the text "<t>.<raw body>" (the t value, a dot, then the body). Compare your hex result with v1 using a constant-time comparison.
  6. Check the time: reject the request if t is more than 5 minutes away from your clock.
  7. Parse the JSON. Read event_id, event and data.
  8. Look up event_id in your processed-events table. If it is there, answer 200 and stop: this is a retry or a resend.
  9. Insert event_id and the work to do in one database transaction, answer 200, and process the work (mark the order paid, release goods) after answering, ideally from a queue.
  10. If anything about the signature or the time is wrong, answer 400 and log the request id of your own request, not the body.

Verify the signature: Node.js

Use express.raw so you receive the body untouched.

import crypto from 'node:crypto';import express from 'express';​const SECRET = process.env.MOOLRE_WALLET_SECRET;   // your wallet callback secretconst TOLERANCE_SECONDS = 300;​function verifyMoolreSignature(rawBody, header, secret) {  const parts = Object.fromEntries(    String(header || '').split(',').map((p) => p.trim().split('=', 2)),  );  const t = Number(parts.t);  if (!Number.isInteger(t) || !parts.v1) return false;  if (Math.abs(Date.now() / 1000 - t) > TOLERANCE_SECONDS) return false;   // stale: replay protection​  const expected = crypto.createHmac('sha256', secret).update(t + '.' + rawBody).digest('hex');  const a = Buffer.from(expected);  const b = Buffer.from(parts.v1);  return a.length === b.length && crypto.timingSafeEqual(a, b);}​const app = express();// The signature covers the exact bytes Moolre sent, so read the raw body. Do not parse JSON first.app.post('/moolre/webhook', express.raw({ type: '*/*' }), (req, res) => {  const raw = req.body.toString('utf8');  if (!verifyMoolreSignature(raw, req.get('X-Moolre-Signature'), SECRET)) return res.sendStatus(400);​  const event = JSON.parse(raw);  // Dedupe on event.event_id (it is identical on every retry), then act once.  res.sendStatus(200);   // acknowledge fast, do the slow work afterwards});

Verify the signature: Python

In Flask, request.get_data() returns the raw bytes. In Django use request.body, in FastAPI await request.body().

import hashlibimport hmacimport osimport time​from flask import Flask, request​SECRET = os.environ["MOOLRE_WALLET_SECRET"]   # your wallet callback secretTOLERANCE_SECONDS = 300app = Flask(__name__)​​def verify_moolre_signature(raw_body: bytes, header: str, secret: str) -> bool:    parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)    t, v1 = parts.get("t", ""), parts.get("v1", "")    if not t.isdigit() or not v1:        return False    if abs(time.time() - int(t)) > TOLERANCE_SECONDS:   # stale: replay protection        return False    signed = t.encode() + b"." + raw_body    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()    return hmac.compare_digest(expected, v1)​​@app.post("/moolre/webhook")def webhook():    raw = request.get_data()   # the exact bytes Moolre sent, not re-serialised JSON    if not verify_moolre_signature(raw, request.headers.get("X-Moolre-Signature", ""), SECRET):        return "", 400    event = request.get_json()    # Dedupe on event["event_id"] (identical on every retry), then act once.    return "", 200

Verify the signature: PHP

file_get_contents('php://input') returns the raw body. Never use $_POST or a decoded array.

<?php$secret    = getenv('MOOLRE_WALLET_SECRET');   // your wallet callback secret$tolerance = 300;​function verify_moolre_signature(string $rawBody, string $header, string $secret, int $tolerance): bool{    $t = null;    $signatures = [];    foreach (explode(',', $header) as $part) {        $kv = explode('=', trim($part), 2);        if (count($kv) !== 2) { continue; }        if ($kv[0] === 't') { $t = $kv[1]; }        if ($kv[0] === 'v1') { $signatures[] = $kv[1]; }    }    if ($t === null || !ctype_digit($t) || !$signatures) { return false; }    if (abs(time() - (int) $t) > $tolerance) { return false; }   // stale: replay protection​    $expected = hash_hmac('sha256', $t . '.' . $rawBody, $secret);    foreach ($signatures as $signature) {        if (hash_equals($expected, $signature)) { return true; }    }    return false;}​$raw = file_get_contents('php://input');   // the exact bytes Moolre sentif (!verify_moolre_signature($raw, $_SERVER['HTTP_X_MOOLRE_SIGNATURE'] ?? '', $secret, $tolerance)) {    http_response_code(400);    exit;}​$event = json_decode($raw, true);// Dedupe on $event['event_id'] (identical on every retry), then act once.http_response_code(200);

Verify the signature: Go and C#

Go: read r.Body with io.ReadAll before anything else. C#: read the request body stream before model binding.

package main​import (	"crypto/hmac"	"crypto/sha256"	"encoding/hex"	"io"	"math"	"net/http"	"os"	"strconv"	"strings"	"time")​const toleranceSeconds = 300​func verifyMoolreSignature(raw []byte, header, secret string) bool {	var t, v1 string	for _, part := range strings.Split(header, ",") {		kv := strings.SplitN(strings.TrimSpace(part), "=", 2)		if len(kv) != 2 {			continue		}		switch kv[0] {		case "t":			t = kv[1]		case "v1":			v1 = kv[1]		}	}	ts, err := strconv.ParseInt(t, 10, 64)	if err != nil || v1 == "" {		return false	}	if math.Abs(float64(time.Now().Unix()-ts)) > toleranceSeconds { // stale: replay protection		return false	}	mac := hmac.New(sha256.New, []byte(secret))	mac.Write([]byte(t + "."))	mac.Write(raw)	expected := hex.EncodeToString(mac.Sum(nil))	return hmac.Equal([]byte(expected), []byte(v1))}​func webhook(w http.ResponseWriter, r *http.Request) {	raw, _ := io.ReadAll(r.Body) // the exact bytes Moolre sent	if !verifyMoolreSignature(raw, r.Header.Get("X-Moolre-Signature"), os.Getenv("MOOLRE_WALLET_SECRET")) {		w.WriteHeader(http.StatusBadRequest)		return	}	// Dedupe on event_id (identical on every retry), then act once.	w.WriteHeader(http.StatusOK)}

Step by step: handle each event exactly once

The same event can reach you more than once: a retry after a timeout you did not see, a resend you asked for, or a slow answer. event_id is identical on every attempt, so it is the key for handling an event once.

  1. Create a table webhook_events with event_id as its primary key (unique).
  2. In your handler, insert the event_id first. If the insert fails because it already exists, answer 200 and stop.
  3. Match the payment to your own record with data.externalref.
  4. Apply the change only if the record is not already in its final state, and check the amount matches.
  5. For a high-value action, confirm with Payment Status before you release goods.
  • Return 2xx for an event you already processed, so Moolre stops retrying it.
  • Return 4xx or 5xx only when you really want a retry.
  • Do not rely on arrival order: events for different payments can arrive in any order.

// webhook_events(event_id PRIMARY KEY, received_at, payload)async function handle(event) {  const inserted = await db.query(    'INSERT INTO webhook_events (event_id, received_at, payload) VALUES (?, NOW(), ?) ON DUPLICATE KEY UPDATE event_id = event_id',    [event.event_id, JSON.stringify(event)],  );  if (inserted.affectedRows === 0) return;                    // seen before: acknowledge and ignore​  if (event.event === 'payment.succeeded') {    await db.query("UPDATE orders SET status = 'paid' WHERE externalref = ? AND status <> 'paid'", [event.data.externalref]);  }  if (event.event === 'payment.failed') {    await db.query("UPDATE orders SET status = 'failed', reason = ? WHERE externalref = ? AND status = 'pending'", [event.data.reason, event.data.externalref]);  }}

Step by step: test it

  1. Set the sandbox wallet callback to your public URL (Update Account).
  2. Call Send test webhook. On a wallet without a webhook_url it goes to the callback. data.delivered is true when your endpoint answered 2xx; data.http and data.error say what went wrong otherwise.
  3. Fire real events with the sandbox trigger endpoint (payment.succeeded, payment.failed, bulk_payout.completed).
  4. Break it on purpose: change one character of the secret and confirm you answer 400; send an old timestamp and confirm you reject it; resend the same event with Resend webhook and confirm you ignore the second one.
  5. Open Webhook deliveries to see every attempt, its state (pending, delivered, dead) and the last HTTP answer or error.

Step by step: recover missed events

  1. After an outage of your endpoint, call Webhook deliveries with state dead (and pending) for the period.
  2. For each event, check whether your records already reflect it. If not, call Resend webhook with the event_id. It keeps the same event_id and gets the full retry schedule again.
  3. Because you dedupe on event_id, resending is always safe.
  4. For events older than you can resend, reconcile from the account statement.

Callback events and body

A callback is about one transaction. The fields that were always there (status, code, message, data, go) are unchanged, including data.secret while it is deprecated. Moolre adds event_id, event and created, and a meta object that carries notices (meta.notices), at the end. Callback meta has no requestid. The bulk_payout.completed callback has no data object: the batch summary is at the top level.

Read notices from meta.notices. Collection callbacks also carry the same list as a top-level notices. Payment link, checkout, bulk payout and test callbacks carry meta.notices only.

eventcodeSent when
payment.succeededP01, PV05, PV02A collection succeeded: P01 for mobile money, Payment ID and bank, PV05 for checkout and one-time payment links, PV02 for reusable links. data.txstatus 1.
payment.failedP02A collection attempt failed. data.txstatus 2, and data.reason explains why.
bulk_payout.completedEvery item of a bulk payout batch is final. Sent once, to the batch callback or the wallet callback.
webhook.testWHT00Sent by Send test webhook to a wallet without a webhook_url. Acknowledge and ignore.

{  "status": 1,  "code": "P01",  "message": "Transaction Successful",  "data": {    "txstatus": 1,    "payer": "233XXXXXXXXX",    "accountnumber": "1000000000001",    "amount": "101",    "value": "98.97",    "transactionid": "10000001",    "externalref": "ORDER-1001",    "secret": "YOUR_CALLBACK_SECRET",    "ts": "2026-11-15 09:30:00"  },  "go": null,  "event_id": "evt_0123456789abcdef01234567",  "event": "payment.succeeded",  "created": "2026-11-15T09:30:00Z",  "meta": {    "notices": [      {        "code": "WEBHOOK_SIGNATURE_AVAILABLE",        "message": "Verify the X-Moolre-Signature header instead of data.secret; data.secret will be removed after 2027-03-31.",        "docs": "https://docs.moolre.com/guides/webhooks"      }    ]  }}

Invoices and expired links

Invoices and payment links that expire send nothing. Read Invoice status and List invoices, or Payment status for a link. A payment made through them is a collection like any other.

Request headers

HeaderMeaning
X-Moolre-Signaturet=<unix seconds>,v1=<hex>. v1 is the HMAC-SHA256 of "<t>.<raw body>" keyed with your wallet secret. A new signature is created for every attempt.
X-Moolre-Event-IdThe event id, also in the body: event_id on callbacks, data.event_id on webhooks. It stays the same across retries and resends: dedupe on it.
X-Moolre-EventThe event name, also in the body: event on callbacks, data.event on webhooks.
X-Moolre-Delivery-AttemptAttempt number, starting at 1.
User-AgentMoolre-Webhooks/1
Content-Typeapplication/json

Retries

The first attempt happens when the event occurs. A failed attempt (a non-2xx answer, a timeout after 20 seconds, a connection error or a TLS error) is retried on this schedule, then the event is marked dead. The signature is created fresh for every attempt, so the timestamp is always current.

AttemptWhen
1Immediately, when the event happens
21 minute after attempt 1 failed
35 minutes after attempt 2 failed
430 minutes after attempt 3 failed
52 hours after attempt 4 failed
66 hours after attempt 5 failed
724 hours after attempt 6 failed
848 hours after attempt 7 failed
972 hours after attempt 8 failed. If this one fails too the event is dead

See, resend and test deliveries

Webhook deliveries lists every callback and webhook Moolre recorded for your wallet, with its state: pending (still retrying), delivered or dead. Resend webhook puts one back in the queue with the full retry schedule and the same event_id. Send test webhook posts a signed webhook.test event to your webhook_url (or to your callback URL when the wallet has no webhook_url) immediately and tells you whether your endpoint accepted it, with the HTTP status and how long it took. A test is sent only to https on port 443 (WHT06 otherwise), at most 10 a minute and 100 a day per wallet (WHT07), and the response never includes your endpoint's reply.

All three use your private API key. Use a dead event as the cue to fix your endpoint, then resend it.

TLS requirements

Callback URLs must use HTTPS with a certificate that is valid for the host name, issued by a public certificate authority, with the full chain served. Self-signed, expired or mismatched certificates fail verification.

Until 2026-12-31 Moolre retries a callback once without certificate verification when the first attempt fails TLS verification, and logs the merchant so it can be contacted. From 2027-01-01 a TLS failure is a failed delivery and follows the retry schedule. Fix the certificate before then.

Callback URLs that point to private or loopback addresses, include credentials in the URL, or redirect are refused.

Source IP addresses

Allow-listing Moolre's source addresses is an extra safeguard, never a replacement for signature verification. The canonical list is maintained on one page.

Moving from data.secret to the signature

Today every callback still contains data.secret. Comparing it with your stored secret works, but the secret travels in every request and can leak through logs. Verify X-Moolre-Signature instead, and stop reading data.secret before 2027-03-31, when it is removed. Each callback carries a WEBHOOK_SIGNATURE_AVAILABLE notice as a reminder.

Checklist

  • The endpoint is HTTPS with a valid public certificate and answers within a few seconds.
  • It verifies the signature on the raw body with constant-time comparison and a 5-minute time window.
  • It dedupes on event_id with a unique key in the database.
  • It matches data.externalref to your records and never fulfils from a failed event.
  • It does the slow work after answering 2xx.
  • You do not read data.secret any more (removed after 2027-03-31).
  • You monitor Webhook deliveries for dead events.