M-Pesa is Safaricom’s mobile-money service, used across Kenya and Tanzania to send money and pay businesses. Lipa na M-Pesa Online (the STK-push API) lets your website or app request a payment that the customer approves with a PIN prompt on their phone. This guide explains how that integration works, step by step.
How the STK-push flow works
- Get an access token. Your server calls the OAuth endpoint with your app’s Consumer Key and Secret and receives a short-lived bearer token.
- Send the STK push. Your server posts the amount, the customer’s phone number, your shortcode and a callback URL to the STK Push endpoint.
- Customer approves. The customer gets a PIN prompt on their handset and confirms.
- Receive the callback. Safaricom posts the result to your callback URL; only when that says success do you mark the order paid.
What you’ll need
- A Daraja developer account and a sandbox app (Consumer Key & Secret)
- A business shortcode and passkey (sandbox values for testing)
- A publicly reachable HTTPS callback URL
Why the callback matters most
Never trust the immediate API response to confirm payment — it only means the request was accepted. The real confirmation arrives asynchronously at your callback. Building your order logic around that callback is the single most important habit this tutorial teaches, and it applies to every payment gateway.
Frequently asked questions
Can I test without real money?
Yes — Daraja provides a full sandbox with test credentials and test phone numbers.
Why is my callback never called?
Almost always because the callback URL is not publicly reachable over HTTPS. During local development, tunnel it with a service like ngrok.
A note on using this project
Use this PHP project as a learning reference: read the code, run it locally, and adapt it to your own requirements rather than deploying it unchanged. If you reuse third-party components, check their licences first.