How payment webhooks work: a developer's guide
A payment webhook is a message a payment provider sends to your server when something happens, such as a customer paying. Instead of your code asking again and again whether a Mobile Money prompt was approved, berrapay calls an address you give it. Your job is to check the message is genuine, act on it once, and answer quickly.
Step by step
- 1
Give berrapay an address
It must be https. Add it under Settings, then Connections, then berrapay API, and choose which events to receive.
- 2
Verify the signature
Each message carries a Berrapay-Signature header: a time and a code made from the body and your secret. Reject anything that doesn't match or is more than five minutes old.
- 3
Use the raw body
Check the signature against the body exactly as it arrived, before parsing it.
- 4
Act once
The same event can arrive more than once. Keep the event id and ignore one you have already handled.
- 5
Answer 200 fast
Do slow work afterwards. If you don't answer, berrapay retries over about a day.
Receive and verify a webhook
// Node.js with Express
import crypto from "node:crypto";
function fromBerrapay(raw, header, secret) {
const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
if (Math.abs(Date.now() / 1000 - Number(t)) > 300) return false; // older than 5 minutes
const expected = crypto.createHmac("sha256", secret).update(t + "." + raw).digest("hex");
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}
app.post("/berrapay", express.raw({ type: "application/json" }), (req, res) => {
const raw = req.body.toString();
if (!fromBerrapay(raw, req.get("Berrapay-Signature"), process.env.BERRAPAY_WEBHOOK_SECRET)) return res.sendStatus(400);
const event = JSON.parse(raw);
if (alreadyHandled(event.id)) return res.sendStatus(200); // the same event can arrive twice
if (event.type === "checkout.paid") markOrderPaid(event.data.object.reference);
res.sendStatus(200);
});Events berrapay sends
| Event | When |
|---|---|
| payment.succeeded | A customer paid you, whatever it was for |
| checkout.paid | A checkout has been paid |
| invoice.paid | An invoice has been paid in full |
| subscription.created | A customer signed up to a plan |
| subscription.cancelled | A subscription ended |
| charge.failed | A phone charge wasn't approved |
| payment.refunded | berrapay refunded a payment |
Common questions
What if my server is down?
berrapay retries after 5 minutes, 30 minutes, 2 hours, 12 hours and 24 hours. You can also resend a delivery by hand from the API screen.
Can someone fake a webhook?
Not if you check the signature. Without your secret they can't produce a matching code.
Do I still need to read the payment status?
It is a good backstop. If a webhook never arrives, reading the checkout or charge gives you the truth.
Ask an AI assistant about this
Opens the assistant in a new tab with a question about this page already typed. You can change it before sending.