Fintech & Payments
Integrating M-Pesa Daraja the Right Way: Callbacks, Idempotency and Reconciliation
Getting an STK Push to fire takes ten minutes. Making it reliable at scale, when callbacks arrive late, twice or never, is the real work. A developer’s guide with working code.
By Philip Mutuku · Published · Updated · 7 min read
If you build software in Kenya, sooner or later someone will say, “just add M-Pesa.” Safaricom's Daraja APIs make the happy path straightforward: your server asks Daraja to prompt the customer's phone, the customer enters their PIN, and Daraja calls your server back with the result.[1]
The trouble is everything outside the happy path. Customers cancel. Phones are off. Callbacks arrive late, twice, or not at all. This guide covers the patterns we use so a payment is never lost, never double-counted and always reconcilable.
The STK Push flow in four steps
- Authenticate. Exchange your consumer key and secret for a short-lived OAuth access token.
- Initiate. POST to the STK Push endpoint with the amount, phone number, an account reference and your callback URL.
- Customer approves. A prompt appears on their phone; they enter their M-Pesa PIN.
- Callback. Daraja POSTs the outcome to your callback URL. This, not the initiation response, is the source of truth.
Initiating the request
The password is the Base64 of your business shortcode, your passkey and a timestamp. Create a local payment record first, with a unique ID and a pending status, so every Daraja response can be matched to something you own.
const axios = require('axios');
const BASE = process.env.MPESA_BASE_URL; // sandbox or production host
async function getToken() {
const auth = Buffer.from(
process.env.MPESA_CONSUMER_KEY + ':' + process.env.MPESA_CONSUMER_SECRET
).toString('base64');
const { data } = await axios.get(BASE + '/oauth/v1/generate?grant_type=client_credentials', {
headers: { Authorization: 'Basic ' + auth },
});
return data.access_token;
}
function timestamp() {
// YYYYMMDDHHmmss in East Africa Time (UTC+3, no daylight saving)
const eat = new Date(Date.now() + 3 * 60 * 60 * 1000);
return eat.toISOString().replace(/[-:T.Z]/g, '').slice(0, 14);
}
async function stkPush({ paymentId, phone, amount }) {
const ts = timestamp();
const password = Buffer.from(
process.env.MPESA_SHORTCODE + process.env.MPESA_PASSKEY + ts
).toString('base64');
const { data } = await axios.post(
BASE + '/mpesa/stkpush/v1/processrequest',
{
BusinessShortCode: process.env.MPESA_SHORTCODE,
Password: password,
Timestamp: ts,
TransactionType: 'CustomerPayBillOnline',
Amount: amount, // whole shillings
PartyA: phone, // 2547XXXXXXXX
PartyB: process.env.MPESA_SHORTCODE,
PhoneNumber: phone,
CallBackURL: process.env.MPESA_CALLBACK_URL + '/' + process.env.MPESA_CALLBACK_SECRET,
AccountReference: 'ORDER-' + paymentId,
TransactionDesc: 'Payment',
},
{ headers: { Authorization: 'Bearer ' + (await getToken()) } }
);
// Store CheckoutRequestID: it's the key that links the callback back to our record.
await db.payments.update(paymentId, {
checkoutRequestId: data.CheckoutRequestID,
status: 'pending',
});
return data;
}
Handling the callback safely
Your callback endpoint is a public URL that can move money states in your database, so treat it like an attack surface. Three rules:
- Respond fast. Acknowledge with HTTP 200 immediately and process asynchronously. Slow responses invite retries.
- Make it idempotent. The same callback may arrive twice. Processing it twice must not credit a customer twice.[2]
- Don't trust the body blindly. Match on
CheckoutRequestID, verify the amount equals what you expected, and consider a secret path segment (as above) and IP restrictions to Safaricom's published ranges where your hosting allows.[3]
router.post('/mpesa/callback/:secret', async (req, res) => {
if (req.params.secret !== process.env.MPESA_CALLBACK_SECRET) {
return res.sendStatus(404);
}
// Acknowledge immediately; do the work after.
res.json({ ResultCode: 0, ResultDesc: 'Accepted' });
const cb = req.body?.Body?.stkCallback;
if (!cb) return;
const payment = await db.payments.findByCheckoutId(cb.CheckoutRequestID);
if (!payment) return logger.warn('Callback for unknown payment', cb);
// Idempotency: ignore anything already finalised.
if (payment.status !== 'pending') return;
if (cb.ResultCode === 0) {
const items = cb.CallbackMetadata?.Item || [];
const get = (name) => items.find((i) => i.Name === name)?.Value;
if (Number(get('Amount')) !== Number(payment.amount)) {
return db.payments.update(payment.id, { status: 'amount_mismatch', raw: cb });
}
await db.payments.update(payment.id, {
status: 'paid',
mpesaReceipt: get('MpesaReceiptNumber'),
paidAt: new Date(),
raw: cb,
});
await orders.markPaid(payment.orderId);
} else {
// e.g. 1032 = cancelled by user, 1 = insufficient balance
await db.payments.update(payment.id, { status: 'failed', failureCode: cb.ResultCode, raw: cb });
}
});
When the callback never arrives
Networks fail, and your server may be mid-deploy when Safaricom calls. Don't leave a payment in limbo. Run a small background job that finds payments still pending after about two minutes and asks Daraja directly using the STK Push Query endpoint, passing the stored CheckoutRequestID.[1] Combine that with a daily reconciliation against your M-Pesa statement, and you'll catch the rare stragglers.
| Situation | What you see | What to do |
|---|---|---|
| Customer cancels the prompt | Callback with a non-zero result (e.g. 1032) | Mark failed; let them retry with a new payment record |
| Customer ignores the prompt | Callback with a timeout result, or none | Query status after ~2 min; then expire the payment |
| Callback delivered twice | Same CheckoutRequestID again | Ignore: payment is no longer pending |
| Callback never delivered | Payment pending indefinitely | Background STK Query + daily statement reconciliation |
| Wrong amount recorded | Amount differs from the order | Flag for manual review; never auto-fulfil |
Sandbox to production: what changes
The sandbox is forgiving, and production is not. Teams commonly discover differences only on launch day, so plan for them early. In production you need your own shortcode (Paybill or Till), a Go-Live approval through the Daraja portal, production consumer key and secret, and a publicly reachable HTTPS callback URL with a valid certificate.
- Callback URLs must be public and stable. Safaricom cannot reach
localhost. Use a tunnel for development and a real domain for production, and avoid putting words like “mpesa” or “safaricom” in the callback path, because some gateways reject them. - Different credentials per environment. Keep consumer key, secret and passkey in environment variables, and make it impossible to point a staging build at production credentials by accident.
- Cache the access token. Tokens last about an hour. Fetch one, store it with its expiry, and refresh shortly before it lapses instead of requesting a new one for every payment.
- Rate limits and timeouts exist. Set a sensible HTTP timeout on every Daraja call and treat a timeout as “unknown”, not “failed”. The request may still have succeeded.
Model payments as a ledger, not a flag
A boolean paid column on an order is where reconciliation problems begin. Store every payment attempt as its own row with a status that moves through a small, well-defined set of states, and keep the raw callback payload next to it. When a customer calls to say they paid and the order shows unpaid, you can answer in one query.
| Field | Why you store it |
|---|---|
| Order ID and amount expected | To compare against what Safaricom reports |
| MerchantRequestID and CheckoutRequestID | To match the callback and to query status later |
| Phone number (normalised) | To support customers and detect repeated failures |
| M-Pesa receipt number | The proof of payment that finance will reconcile against |
| Status and timestamps | To drive the UI and spot payments stuck in pending |
| Raw callback JSON | For disputes and debugging, stored securely |
Treat refunds and reversals as their own records too, linked to the original payment. Never edit history; add a new row. That gives finance an audit trail and protects you when amounts do not match.
Troubleshooting the problems you will actually meet
- Callbacks never arrive. Check that the URL is HTTPS, publicly reachable and returns a 200 quickly. Firewalls, redirects from
httptohttps, and slow database work inside the handler are the usual causes. - “Invalid access token” errors. Usually an expired cached token or the wrong environment’s credentials. Log which environment each request used.
- Prompt does not reach the phone. Confirm the number is in 2547XXXXXXXX or 2541XXXXXXXX format, the line is active and the handset can receive SIM toolkit prompts.
- Customer paid but the order is pending. Run the STK Query for the CheckoutRequestID before telling them to pay again. Double-charging customers is the fastest way to lose trust.
Frequently asked questions
Should we use STK Push, C2B or a payment aggregator?
STK Push suits checkout flows where the customer is on your site and you know the amount. C2B suits customers paying your Paybill or Till from their own menu, with reconciliation by account reference. An aggregator adds cards and other wallets and shortens integration, at the price of fees and less control. Many businesses use a direct integration for M-Pesa and an aggregator for cards.
How long does Go-Live approval take?
It varies, so do not schedule a launch date until you have the production credentials in hand. Prepare your shortcode details, test evidence and callback URLs in advance so there is nothing to chase once you apply.
Is it safe to store phone numbers?
A phone number is personal data under Kenya’s Data Protection Act, so collect only what you need, tell customers why, restrict who can see it, and delete it when you no longer have a lawful reason to keep it.
Pre-launch checklist
- Sandbox and production credentials live in environment variables, never in the repo.
- Phone numbers normalised to the 2547XXXXXXXX format before sending.
- A unique local payment record exists before the STK Push is sent.
- Callback is idempotent, validates the amount and returns 200 fast.
- A background job queries stuck payments, and finance has a reconciliation report.
- Customers get clear states in the UI: “Check your phone”, “Payment received” and “Payment failed, try again”.
None of this is glamorous, but it's the difference between a payment feature and a trusted payment feature. Customers forgive slow pages; they don't forgive paying twice or paying and getting nothing.
References & further reading
- Safaricom, Daraja developer portal: API documentation for M-PESA APIs (OAuth, Lipa na M-PESA Online / STK Push, callbacks). https://developer.safaricom.co.ke
- Stripe, “Idempotent requests” (the general pattern for safely retrying payment operations). https://docs.stripe.com/api/idempotent_requests
- OWASP Foundation, “Server-Side Request Forgery Prevention” and general input-validation cheat sheets, applicable to webhook endpoints. https://cheatsheetseries.owasp.org/