Appearance
Set up webhooks
MOOKHPay sends a signed POST to your server when a payment, payout, refund or charge settles, and when something happens to an account your platform reaches. You add endpoints in the hub, choose the events each one receives, and verify every delivery with the endpoint's secret.
A webhook tells you that something changed. It is not the only way to find out, and it is not always the last word:
- For a hosted checkout,
GET /checkouts/:idis still the check before you fulfil. See Confirming payments. - For a direct charge, act on the webhook, then read the charge before you fulfil: a charge can succeed after it expired, so the object, not the order of events, says what is true. See Confirming payments.
- Deliveries can repeat and arrive out of order. See Retries and ordering.
Add an endpoint
- Open the hub while acting for your organisation. Open API Integrations, then the Webhooks tab. Endpoints are in the Webhooks card.
- Choose Add Endpoint, enter the endpoint's URL and choose the events it should receive. See the event catalogue.
- Copy the signing secret and store it on your server, for example as
MOOKHPAY_WEBHOOK_SECRET. It starts withwhsec_. - Choose Send Test and check your server answers
2xx.
In the hub, API Integrations is part of an organisation's account: a personal account sees a note that it is for organisations. An endpoint belongs to the organisation.
Rules for an endpoint
| Rule | Detail |
|---|---|
| Scheme | https only |
| Credentials | A URL with a user name or password in it is refused |
| Address | Must be on the public internet. A literal private, loopback, link-local or carrier-grade NAT address is refused, and so is a single-label name (ledger) or a name ending in localhost, local, localdomain, internal, home.arpa, lan or svc |
| Resolution | Checked again before every delivery. A name that now resolves to a private address fails that delivery at once, with no retry |
| Length | Up to 2,048 characters |
| Endpoints | At most 5 per account. A sixth is refused with 409 and code 2812 |
| Events | At least one, each listed once. An endpoint receives only the events it chose |
| Secret | One per endpoint, made by MOOKHPay. It can be rotated in the hub, and the old one keeps signing for 24 hours. See Rotate the secret |
The events you can choose depend on the deployment:
| Events | Offered |
|---|---|
payment.succeeded, payment.failed, payout.paid, payout.failed, refund.succeeded, refund.declined, refund.failed | Always |
charge.expired, charge.cancelled | Where direct charges are switched on |
account.created, account.updated, account.linked, account.claimed, account.disconnected | Where the platform API is switched on |
The secret
The secret is shown when you add the endpoint, and again whenever someone who can manage webhooks opens that one endpoint in the hub. It is never in the list of endpoints. Anyone holding it can sign a payment.succeeded your server will believe, so keep it in the same place as your secret key.
Rotate the secret
Rotate a secret when it may have leaked, when someone who saw it leaves, or on your own schedule. Rotating does not stop deliveries.
- In the Webhooks card, choose Rotate Secret on the endpoint and confirm.
- Copy the new secret. The endpoint row then says until when the old secret still works.
- For the next 24 hours every delivery to the endpoint carries two signatures, one made with each secret, newest first. A receiver that accepts any one matching signature keeps working on either secret. See Verify signatures.
- Deploy the new secret to the server that receives the webhooks, inside those 24 hours.
- After 24 hours deliveries carry one signature again, made with the new secret, and the old one stops working.
Rotating again inside the 24 hours makes another new secret, and the secret from before the first rotation stops signing at once: a delivery never carries more than two signatures. Rotating takes no PIN, the same as adding an endpoint or reading its secret. An account can rotate 10 times an hour.
An endpoint a Developer adds
In an organisation, an endpoint added by a member with the Developer role starts switched off. It receives nothing until an Owner switches it on in the hub. Only an Owner can do that (403 and code 2813 for anyone else). A deployment can turn this rule off.
Test events
The hub can post a sample of any event your endpoint is offered. The sample is signed like a real delivery and has "test": true with made-up ids such as cs_test_…, ch_test_… and acct_test_…. See test events for what each sample holds.
- 20 test sends an hour per account.
- A test send is one attempt. It is not retried.
- It goes to the endpoint you picked, even one that is switched off or not subscribed to that event.
- On a deployment that takes no mobile-money payments, a test send is refused with
422and code2721.
Deliveries
The Deliveries card on API Integrations, Webhooks lists every delivery from the last 30 days, newest first, a page at a time; Load More shows older ones. Each row shows the event, its id, the endpoint, what it was about (subject_id), whether it was a test, its status (pending, delivered or failed), the number of attempts, the last response code or error, and when it was last resent.
A delivery that has been delivered or has failed is removed 30 days after it was first sent. One that is still pending stays until its retries end.
Resend a delivery
Resend on a delivered or failed delivery sends it again to the same endpoint, now:
- The body is the same event, with the same
id, so a receiver that deduplicates onidtreats it as a repeat. - It is one attempt, signed with a fresh timestamp and the endpoint's current secrets. A resend that fails is not retried, and it does not send the failing-endpoint email.
- It cannot be used on a delivery that is still
pending(409, code2816), on one whose endpoint is switched off (409, code2817), or on one that is gone after 30 days (404, code2815). - An account can resend 30 times an hour, and one delivery once a minute.
Use it after you fix a receiver that was refusing events, or to replay one event into a new environment. To recover many events at once, read the objects instead; see Retries and ordering.
What a delivery looks like
http
POST /mookhpay/webhooks HTTP/1.1
Host: yourshop.example
Content-Type: application/json
X-Mookh-Event-Id: evt_4b7e1c9a2d5f80e3a6c1b0d7
X-Mookh-Timestamp: 1763635200
X-Mookh-Signature: sha256=7ab6a0cf9a774ccfe177fd9814d5d10e4db972b4e0a46374bacefc28586e9480
{"id":"evt_4b7e1c9a2d5f80e3a6c1b0d7","event":"payment.succeeded","checkout_id":"cs_ke_3f9a1c7e5b2d4a8e6c0b91d7","intent_id":"pi_8c1e4f0a7b3d92e5a6f01c48","amount":"150000","currency":"KES","reference":"order-1042","rail":"mpesa","provider_receipt":"TKJ8X2M4PQ","ledger_reference":"SMK4H2PL9Q","test":false,"created_at":"2026-11-20T09:14:02.000Z"}| Header | Value |
|---|---|
Content-Type | application/json |
X-Mookh-Event-Id | The event's id, the same as the id field in the body |
X-Mookh-Timestamp | Unix time in seconds when this attempt was sent. Each retry has a new one |
X-Mookh-Signature | sha256= and the lowercase hex HMAC-SHA256 of the timestamp, a ., and the raw body, keyed with the endpoint secret. For 24 hours after a rotation, two of them separated by , , newest first. See Verify signatures |
The body is a flat JSON object. id names this event, evt_…, and stays the same on every retry, on every endpoint of your account that receives it, and on a resend: deduplicate on it. event names the event type. The other fields depend on the event; see the event catalogue and duplicates.
How to answer
- Answer with any
2xxstatus. MOOKHPay does not read the body of your answer. - Answer within 8 seconds. A slower answer is a failed attempt and is retried.
- Do not redirect. MOOKHPay does not follow a redirect, and a
3xxis a failed attempt. - Verify the signature first, then record the event, then answer. Do slow work, such as sending emails or calling MOOKHPay back, after you have answered or in a queue.
- Answer
2xxfor an event you do not handle, so it is not retried.
A minimal receiver
Each sample reads the raw body, verifies the signature (accepting any one of the signatures in the header, so it keeps working through a rotation), refuses a timestamp more than 5 minutes from the server clock, answers 200, and only then does the work. The work itself should skip an id it has already handled.
sh
# Send yourself a signed sample to test your receiver locally.
SECRET="$MOOKHPAY_WEBHOOK_SECRET"
BODY='{"id":"evt_4b7e1c9a2d5f80e3a6c1b0d7","event":"payment.succeeded","checkout_id":"cs_ke_3f9a1c7e5b2d4a8e6c0b91d7","intent_id":"pi_8c1e4f0a7b3d92e5a6f01c48","amount":"150000","currency":"KES","reference":"order-1042","rail":"mpesa","provider_receipt":"TKJ8X2M4PQ","ledger_reference":"SMK4H2PL9Q","test":true,"created_at":"2026-11-20T09:14:02.000Z"}'
TS=$(date +%s)
SIG="sha256=$(printf '%s' "$TS.$BODY" | openssl dgst -sha256 -hmac "$SECRET" | sed 's/^.* //')"
curl -X POST http://localhost:3000/mookhpay/webhooks \
-H "Content-Type: application/json" \
-H "X-Mookh-Timestamp: $TS" \
-H "X-Mookh-Signature: $SIG" \
--data-binary "$BODY"js
import { createServer } from "node:http";
import { createHmac, timingSafeEqual } from "node:crypto";
const secret = process.env.MOOKHPAY_WEBHOOK_SECRET;
function verify(rawBody, timestamp, header) {
if (!/^\d+$/.test(timestamp ?? "")) return false;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
const expected = Buffer.from(
"sha256=" +
createHmac("sha256", secret)
.update(`${timestamp}.`)
.update(rawBody)
.digest("hex"),
);
return (header ?? "")
.split(",")
.map((part) => Buffer.from(part.trim()))
.some((got) => got.length === expected.length && timingSafeEqual(got, expected));
}
async function handle(event) {
console.log("received", event.event);
}
createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/mookhpay/webhooks") {
res.writeHead(404).end();
return;
}
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const rawBody = Buffer.concat(chunks);
const ok = verify(
rawBody,
req.headers["x-mookh-timestamp"],
req.headers["x-mookh-signature"],
);
if (!ok) {
res.writeHead(400).end();
return;
}
const event = JSON.parse(rawBody.toString("utf8"));
res.writeHead(200).end();
handle(event).catch((err) => console.error(err));
});
}).listen(3000);python
import hashlib
import hmac
import json
import os
import threading
import time
from flask import Flask, request
app = Flask(__name__)
SECRET = os.environ["MOOKHPAY_WEBHOOK_SECRET"].encode()
def verify(raw_body: bytes, timestamp: str, header: str) -> bool:
if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
return False
expected = "sha256=" + hmac.new(
SECRET, timestamp.encode() + b"." + raw_body, hashlib.sha256
).hexdigest()
matched = False
for part in header.split(","):
if hmac.compare_digest(expected, part.strip()):
matched = True
return matched
def handle(event: dict) -> None:
print("received", event["event"])
@app.post("/mookhpay/webhooks")
def webhook():
raw_body = request.get_data()
timestamp = request.headers.get("X-Mookh-Timestamp", "")
signature = request.headers.get("X-Mookh-Signature", "")
if not verify(raw_body, timestamp, signature):
return "", 400
event = json.loads(raw_body)
threading.Thread(target=handle, args=(event,)).start()
return "", 200php
<?php
$secret = getenv('MOOKHPAY_WEBHOOK_SECRET');
$rawBody = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_MOOKH_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_MOOKH_SIGNATURE'] ?? '';
$fresh = ctype_digit($timestamp) && abs(time() - (int) $timestamp) <= 300;
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
$matched = false;
foreach (explode(',', $signature) as $part) {
if (hash_equals($expected, trim($part))) {
$matched = true;
}
}
if (!$fresh || !$matched) {
http_response_code(400);
exit;
}
$event = json_decode($rawBody, true);
http_response_code(200);
header('Content-Length: 0');
header('Connection: close');
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
error_log('received ' . $event['event']);The Python sample uses Flask (pip install flask). In production, put the event on a real queue rather than a thread, so a restart does not lose it.