Take mobile money payments in Kenya through M-Pesa Express (Daraja STK Push). The shopper gets a PIN prompt on their phone and pays there. Safaricom then posts the result to your site.
M-Pesa works differently from a hosted-page gateway in three ways:
- There is no checkout page.
create_paymentsends the PIN prompt to the shopper's phone. The shopper lands on your return page at once, while the payment is still Pending. - You need the shopper's phone number. Pass it as
customer_phone. - Callbacks are not signed. Safaricom takes a callback URL for each request, so BWH Payments puts a secret token in that URL.
Before you start
- A Safaricom Daraja app, with its Consumer Key and Consumer Secret. Sandbox and live apps have separate credentials.
- A Business Shortcode and its Online Passkey (the Lipa Na M-Pesa passkey)
- Payments in KES, in whole shillings. BWH Payments refuses any other currency, and refuses an amount with cents.
- For refunds only: an Initiator Name and a Security Credential. The initiator is an API operator on the M-PESA Org Portal with the reversal role. The security credential is its password encrypted with Safaricom's certificate, as the Daraja portal generates it.
- A site that Safaricom can reach on a public URL
Set up M-Pesa
1. Fill in Mpesa Gateway Settings
| Field | Value |
|---|---|
| Sandbox | On by default. Sends every request to Safaricom's Daraja sandbox. Turn it off when the keys belong to your live Daraja app. |
| Consumer Key, Consumer Secret | From your Daraja app. BWH Payments trims stray spaces from pasted keys. |
| Business Shortcode | The Paybill number. For Buy Goods, the store (head office) number that the passkey belongs to. |
| Transaction Type | Pay Bill (the default) or Buy Goods |
| Till Number | Buy Goods only: the till that receives the money |
| Online Passkey | The passkey for the shortcode |
| Initiator Name, Security Credential | Only for refunds |
| Callback Token | Made for you when you first save. See Callbacks. |
| Callback IP Allowlist | Optional. One IP address for each line. When you set it, callbacks from any other address are refused. Safaricom publishes the addresses its callbacks come from. |
| Success URL | Your confirmation page. ?reference_id=… is added to it. The shopper goes here as soon as the prompt is sent. Required, unless every payment sets redirect_to. |
| Failure URL, Cancelled URL | Your payment-failed page. M-Pesa never redirects here. BWH Payments passes these URLs back to your app, so you can send the shopper there yourself. |
2. Create a Payment Gateway Profile named M-Pesa, set Gateway Settings to Mpesa Gateway Settings, and tick Enabled.
There's no webhook to register in the Daraja portal. BWH Payments sends the callback URL with each request.
How checkout works
create_paymentturns the shopper's phone number into the form Daraja takes (2547…or2541…) and sends an STK Push. The number can be written0712 345 678,712345678or254712345678. Any other number makescreate_paymentthrow.- Daraja returns a
CheckoutRequestID. BWH Payments stores it asorder_ref, and setsorder_urlto your return page. No payment page exists. - You redirect the shopper to
order_url. Their phone shows the prompt, and they enter their M-Pesa PIN. - Safaricom posts one callback for the prompt. BWH Payments marks the request Paid, Not Paid, Cancelled or Expired.
The prompt carries the last 12 characters of the request name as its account reference, because Daraja rejects longer ones. The transaction description is Order payment.
Your return page shows a Pending payment at first. Show a "confirming your payment" state, and ask again after a few seconds. See If the status is still Pending.
BWH Payments sends one prompt for each request. When the shopper dismisses it or it times out, create a new payment.
Callbacks
Daraja does not sign callbacks, so the Callback Token is the shared secret. BWH Payments adds it to the callback URL of every prompt and reversal:
https://your.site/api/method/bwh_payments.bwh_payments.webhook.handle?gateway=<profile name>&token=<Callback Token>
- BWH Payments compares the token in constant time. A delivery with the wrong token gets the same 400 as any other failed check.
- The URL uses the first enabled profile that points at
Mpesa Gateway Settings.create_paymentthrows if no profile that uses these settings is enabled. - With Callback IP Allowlist set, the sender's address must also be on the list.
- To stop accepting callbacks for earlier payments, clear Callback Token and save. BWH Payments makes a new one.
How it behaves
Daraja ResultCode |
Payment status |
|---|---|
0 |
Paid |
1 (insufficient balance), 11, 1001, 1025, 2001 (wrong PIN), 9999 |
Not Paid |
1032 (the shopper dismissed the prompt) |
Cancelled |
1019, 1037 (the phone did not answer) |
Expired |
| Any other code | Pending when asked by get_payment_status. Not Paid in a callback, because a callback comes only once the prompt is over. |
- Callbacks settle the request. The paid callback is the only place that names the M-Pesa receipt number. BWH Payments keeps it as
gateway_transaction_ref. A paid callback without a receipt is refused with a 400. - Status checks ask Daraja with an STK query. Before the shopper answers, Daraja replies with the same
500.001.1001code that it uses for wrong credentials. BWH Payments tells them apart by the message and reads "still processing" as Pending. - Amounts are sent as whole shillings.
49.50KES is refused, not rounded. - Cancelling an open checkout isn't supported.
release_if_unpaid()returnsFalse. - Refunds are transaction reversals against the M-Pesa receipt. See Refunds.
Refunds
A reversal returns the whole payment, so BWH Payments refuses a partial refund. It also refuses a refund for a payment that has no receipt number, for example when the paid callback never arrived. Reverse that payment in the M-PESA Org Portal.
Daraja only queues a reversal. The Gateway Refund starts Pending, and the reversal result callback settles it as Processed or Failed. Daraja has no call that reports a reversal's status, so M-Pesa has no get_refund_status, and sync_refunds cannot settle it.
If the result never arrives, the refund stays Pending and keeps its amount reserved, so it can't be refunded twice. A queue timeout that names no ConversationID also leaves it Pending. To settle it:
- Check the reversal in the M-PESA Org Portal.
- As a System Manager, open
bench consoleand runfrappe.get_doc("Gateway Refund", name).apply_gateway_status("processed"). Use"failed"if the reversal failed. - Run
frappe.db.commit().
Good to know
- Gateway settings are a single document, so a site can hold one shortcode.
- M-Pesa takes KES only.
get_gateway_optionslists it for KES and leaves it out for any other currency. get_gatewaysreports M-Pesa withoutreusable_checkout, because BWH Payments sends one prompt for each request.
Test mode
Leave Sandbox on, and use the keys of your Daraja sandbox app. A webhook only reaches a public URL. To test on your own machine, expose your site through a tunnel, for example cloudflared tunnel --url http://127.0.0.1:8000 --http-host-header your.site.
Next steps
- Return pages: the confirmation page, and the Pending state
- Webhooks and security: gateways that don't sign their webhooks