Payments
M-Pesa in production: what we learned building AutoPayKe
Lost callbacks, duplicate payments, result codes, ledgers, B2C payouts and go-live. The parts of M-Pesa Daraja integration that tutorials skip.
Getting an STK Push to pop up on your own phone in the Safaricom sandbox takes an afternoon. Running M-Pesa payments for real customers, where every shilling has to be accounted for, takes a lot more care. We learned most of that while building AutoPayKe, our phone-first payments product, which has now settled more than KES 2.5 million. Cooperatives use it to pay farmers straight to M-Pesa or a bank, with an SMS receipt for every lot.
This post covers what we wish someone had told us on day one. It is written for developers and for the founders who hire them.
The happy path is about 20% of the work
The basic Lipa na M-Pesa Online flow looks simple:
- 1Your server gets an OAuth token from Daraja.
- 2You send an STK Push request with the phone number, amount, your shortcode and a callback URL.
- 3The customer sees a prompt on their phone and enters their PIN.
- 4Safaricom calls your callback URL with the result.
Most tutorials stop there. In production, almost everything interesting happens around steps 3 and 4.
Never trust that the callback will arrive
Callbacks get lost. Your server might be deploying when it arrives, a load balancer might time out, or the request just never comes. If your system only marks an order as paid when the callback lands, some customers will pay and still see "pending".
What we do instead:
- Save the CheckoutRequestID and MerchantRequestID the moment the STK Push request succeeds, together with the order, amount and phone number.
- Treat the callback as one signal, not the only signal.
- Run a background job that uses the STK Push Query API for anything still pending after a minute or two. If that is not conclusive, fall back to the Transaction Status API.
- Only move an order to "paid" from a single place in the code, whichever signal arrives first.
That last point matters. If the callback handler and the polling job can both mark an order as paid, sooner or later they will both do it, and you will send two receipts or release goods twice.
Make every handler idempotent
Safaricom can send the same callback more than once, and your own retry logic will do the same. Every step that moves money or changes a balance should be safe to run twice.
In practice that means a unique constraint on the M-Pesa receipt number (the MpesaReceiptNumber in the callback), and writing the payment and updating the order in one database transaction. If the insert fails because the receipt already exists, you return success and do nothing else. Simple, boring and very effective.
Read the result codes properly
A failed payment is not one thing. The codes we see most often are:
- 0: success.
- 1032: the customer cancelled the prompt.
- 1037: the phone could not be reached, often because it was off or out of signal.
- 1: insufficient balance.
- 2001: wrong PIN.
Each one deserves a different message. "Payment failed" for a cancelled prompt makes people think your system is broken. "You cancelled the payment. Tap to try again" gets them to pay.
Use a ledger, not a balance column
As soon as money flows in more than one direction (customers paying in, you paying farmers or vendors out, fees, reversals), a single balance column on a user record will betray you. Two requests at the same moment, one partial failure, and the numbers no longer add up.
AutoPayKe records every movement as a ledger entry: what came in, what went out, and why. A balance is just the sum of entries. When a cooperative manager asks why a farmer received KES 3,420 and not KES 3,500, we can show the exact deductions in seconds. We used the same double-entry approach in AvaRamp, our crypto-to-mobile-money gateway, where USDC payments settle out to M-Pesa, MTN MoMo and Airtel Money.
Reconcile every day
Even with all of the above, check your records against Safaricom's. Pull the statement for your shortcode, match each receipt number against your ledger, and flag anything that does not line up. Most days nothing comes up. The day something does, you find it in hours rather than at month end when an accountant is asking questions.
Paying out is harder than collecting
B2C payments (sending money from your shortcode to a customer) come with extra requirements: an initiator name, an encrypted security credential, a queue timeout URL and a result URL. B2C results arrive asynchronously too, so all of the advice above applies twice.
Two more things to plan for:
- Float. A B2C shortcode can only pay out what is in its utility account. Build alerts for low balance before a payroll run, not after.
- Limits. M-Pesa has per-transaction and daily limits. If you pay large amounts, you need to split them or route them to a bank instead. AutoPayKe can pay out to 40 Kenyan banks and SACCOs for exactly this reason.
Going live takes longer than you think
Moving from sandbox to production means getting a paybill or till number, submitting the go-live request on the Daraja portal, and testing with real money. Start this in the first week of the project, not the last. We have seen launches slip by two weeks waiting for production credentials alone.
Also: your callback URL must be public, use HTTPS, and respond fast. Do the heavy work in a background job and return a 200 straight away.
Security basics that get skipped
- Keep your consumer key, secret and passkey in environment variables or a secrets manager, never in the repository.
- Never let the client app send the amount to charge. Look the amount up on the server from the order.
- Validate that a callback matches a request you actually made before acting on it.
- Log every request and response, with sensitive values masked, so you can answer "what happened to this payment?" months later.
If you are hiring someone to do this
Ask them how they handle a missing callback, a duplicate callback and a customer who pays twice. If the answers sound like the sections above, you are in good hands. If they say "the callback tells us it worked", keep looking.
We build M-Pesa, card and mobile money integrations as part of our API development and integration service, and we teach this material in our payments training track for teams that would rather build it themselves.
Have a project like this in mind?
Elom Labs is a Nairobi software studio. We have delivered 68 projects since 2023, and first-time clients get 20% off their first project.