M-Pesa Express, better known as STK Push, is the smoothest way to take payments in Kenya: your customer enters their phone number, a PIN prompt pops up on their phone, and the payment is done. Getting a demo working takes an afternoon. Getting it reliable in production, where callbacks arrive late, twice or not at all, takes a bit more care. This guide covers both.
How STK Push works
- Your server gets an OAuth access token from Daraja using your app’s consumer key and secret.
- Your server sends an STK Push request with the amount, the customer’s phone number and a callback URL.
- Safaricom shows the customer a PIN prompt on their phone.
- Safaricom sends the result to your callback URL: success, cancelled, timed out, and so on.
The request in step 2 only tells you the prompt was sent. The payment outcome comes later, asynchronously, in step 4. Design around that.
1. Configure your credentials
Create an app on the Safaricom Developer Portal (Daraja) to get a consumer key and consumer secret. For testing, the sandbox gives you a test shortcode (174379) and a passkey on the simulator page. Keep everything in .env, never in code:
MPESA_ENV=sandbox
MPESA_CONSUMER_KEY=your-consumer-key
MPESA_CONSUMER_SECRET=your-consumer-secret
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your-passkey
MPESA_CALLBACK_SECRET=a-long-random-string
Map them in config/services.php:
'mpesa' => [
'base_url' => env('MPESA_ENV') === 'production'
? 'https://api.safaricom.co.ke'
: 'https://sandbox.safaricom.co.ke',
'key' => env('MPESA_CONSUMER_KEY'),
'secret' => env('MPESA_CONSUMER_SECRET'),
'shortcode' => env('MPESA_SHORTCODE'),
'passkey' => env('MPESA_PASSKEY'),
'callback_secret' => env('MPESA_CALLBACK_SECRET'),
],
2. Get (and cache) an access token
Tokens are requested with HTTP Basic auth and last about an hour. Cache them instead of requesting a new one for every payment:
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class MpesaClient
{
private function token(): string
{
return Cache::remember('mpesa_token', now()->addMinutes(55), function () {
return Http::withBasicAuth(config('services.mpesa.key'), config('services.mpesa.secret'))
->get(config('services.mpesa.base_url') . '/oauth/v1/generate', [
'grant_type' => 'client_credentials',
])
->throw()
->json('access_token');
});
}
}
3. Send the STK Push request
The Password is the Base64 encoding of shortcode + passkey + timestamp, and the Timestamp uses the format YmdHis (e.g. 20261106143000). Generate the timestamp once and use the same value in both places, in East Africa Time for consistency.
public function stkPush(string $phone, int $amount, string $reference, string $checkoutId): array
{
$shortcode = config('services.mpesa.shortcode');
$timestamp = now('Africa/Nairobi')->format('YmdHis');
$password = base64_encode($shortcode . config('services.mpesa.passkey') . $timestamp);
return Http::withToken($this->token())
->timeout(30)
->post(config('services.mpesa.base_url') . '/mpesa/stkpush/v1/processrequest', [
'BusinessShortCode' => $shortcode,
'Password' => $password,
'Timestamp' => $timestamp,
'TransactionType' => 'CustomerPayBillOnline',
'Amount' => $amount,
'PartyA' => $phone, // 2547XXXXXXXX
'PartyB' => $shortcode,
'PhoneNumber' => $phone,
'CallBackURL' => route('mpesa.callback', config('services.mpesa.callback_secret')),
'AccountReference' => $reference,
'TransactionDesc' => 'Payment for ' . $reference,
])
->throw()
->json();
}
Normalise phone numbers before sending: 0712 345 678 and +254712345678 must both become 254712345678.
Save the payment before you send the request, with status pending. The response contains a CheckoutRequestID; store it, because it’s how you’ll match the callback to this payment.
4. Handle the callback
Safaricom POSTs the result to your callback URL. Put the route in routes/api.php so it isn’t subject to CSRF checks, and include a secret in the path so random requests are rejected:
Route::post('/mpesa/callback/{secret}', MpesaCallbackController::class)->name('mpesa.callback');
A callback looks like this (simplified):
{
"Body": {
"stkCallback": {
"MerchantRequestID": "29115-34620561-1",
"CheckoutRequestID": "ws_CO_191220191020363925",
"ResultCode": 0,
"ResultDesc": "The service request is processed successfully.",
"CallbackMetadata": {
"Item": [
{ "Name": "Amount", "Value": 1.0 },
{ "Name": "MpesaReceiptNumber", "Value": "NLJ7RT61SV" },
{ "Name": "TransactionDate", "Value": 20191219102115 },
{ "Name": "PhoneNumber", "Value": 254708374149 }
]
}
}
}
}
ResultCode 0 means success. Anything else is a failure; 1032, for example, means the customer cancelled the prompt. Failed callbacks don’t include CallbackMetadata.
class MpesaCallbackController
{
public function __invoke(Request $request, string $secret)
{
abort_unless(hash_equals(config('services.mpesa.callback_secret'), $secret), 404);
$cb = $request->input('Body.stkCallback');
$items = collect(data_get($cb, 'CallbackMetadata.Item', []))->pluck('Value', 'Name');
DB::transaction(function () use ($cb, $items) {
$payment = Payment::where('checkout_request_id', $cb['CheckoutRequestID'])
->lockForUpdate()->first();
// Unknown or already processed: ignore (callbacks can repeat)
if (! $payment || $payment->status !== 'pending') {
return;
}
if ((int) $cb['ResultCode'] === 0 && (int) $items['Amount'] === $payment->amount) {
$payment->update(['status' => 'paid', 'receipt' => $items['MpesaReceiptNumber']]);
// fulfil the order here
} else {
$payment->update(['status' => 'failed', 'failure_reason' => $cb['ResultDesc']]);
}
});
return response()->json(['ResultCode' => 0, 'ResultDesc' => 'Accepted']);
}
}
Three things make this safe:
- Idempotent: a duplicate callback finds the payment already settled and does nothing.
- Locked:
lockForUpdate()stops two simultaneous callbacks from both fulfilling the order. - Verified: the amount must match what you asked for.
5. Don’t rely on the callback alone
Callbacks can be delayed or lost if your server is briefly unavailable. Use Daraja’s STK Push Query endpoint (/mpesa/stkpushquery/v1/query, sent with the shortcode, password, timestamp and CheckoutRequestID) to check payments that are still pending after a minute or two. A scheduled job that runs every few minutes is enough:
Payment::where('status', 'pending')
->where('created_at', '<', now()->subMinutes(2))
->each(fn ($payment) => CheckMpesaPayment::dispatch($payment));
This turns “the callback never arrived” from a support ticket into a non-event.
6. Go-live checklist
- Switch
MPESA_ENVtoproductionand use your live shortcode and passkey (you receive these when your app goes live on Daraja). - Your callback URL must be public and HTTPS.
- Log every request and callback, but never log your consumer secret or passkey.
- Test the unhappy paths: a cancelled prompt, a wrong PIN, insufficient balance and a phone that’s switched off.
- Reconcile daily: compare your
paidpayments against your M-Pesa statement.
Wrapping up
The happy path is a few HTTP calls; production quality comes from handling everything around it: storing before sending, idempotent callbacks, status queries and reconciliation. If you’d rather have it built and tested for you, that’s exactly what our M-Pesa & Payments Integration service does.