Webhooks
Webhooks
Signed HTTPS events with automatic retries.
Add an https endpoint in the dashboard under Webhooks. You are shown a signing secret that starts with whsec_, once.
What we send
{
"id": "evt_Yz81kQm4NbTs",
"type": "payment.completed",
"created": 1831715100,
"data": {
"id": "pay_Qm3x9Tq1LbZa",
"amount": "250.000000",
"paid": "250.000000",
"currency": "USDT",
"settle_to": null,
"reference": "order_1042"
}
}Verify the signature
Every delivery has a ChainPesa-Signature header: t=<unix time>,v1=<signature>. The signature is an HMAC-SHA256, in hex, of the time, a dot, and the raw request body, using your endpoint secret.
const crypto = require("node:crypto");
// rawBody must be the exact bytes we sent, as a string. Parse the JSON only after the check passes.
function verifyChainPesa(rawBody, header, secret, toleranceSeconds = 300) {
const match = /^t=(\d+),v1=([a-f0-9]{64})$/.exec(header || "");
if (!match) return false;
const [, timestamp, signature] = match;
if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;
const expected = crypto.createHmac("sha256", secret).update(timestamp + "." + rawBody).digest("hex");
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature));
}
// Express
app.post("/webhooks/chainpesa", express.raw({ type: "application/json" }), (req, res) => {
const raw = req.body.toString("utf8");
if (!verifyChainPesa(raw, req.get("ChainPesa-Signature"), process.env.CHAINPESA_WEBHOOK_SECRET)) {
return res.sendStatus(400);
}
const event = JSON.parse(raw);
res.sendStatus(200); // answer first, then do the work
});- Use the raw body. Parsing and re-serialising it changes the bytes and the check fails.
- Reject timestamps older than 5 minutes, so a captured request cannot be replayed.
- Compare signatures with a constant-time function.
Respond and retry
Answer with any 2xx within 8 seconds, then do your work. Redirects are not followed. Otherwise we try again after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours: six attempts in all. Deliveries and their responses are listed in the dashboard.
The same event can arrive more than once, and events can arrive out of order. Remember the event id and ignore repeats, and fetch the object if you need its current state.