How we integrated M-Pesa STK Push in Laravel — the complete guide

S
Samuel
February 26, 2026 2 min read
How we integrated M-Pesa STK Push in Laravel — the complete guide

If you build software in Kenya, M-Pesa integration is non-negotiable. The STK Push (Lipa na M-Pesa Online) API is what makes the familiar payment prompt appear on a customer's phone. Here is how we build it at VE.KE.

Prerequisites

Before you start, you need a Safaricom Developer account, a shortcode (Paybill or Till), and a passkey. For testing, use the sandbox credentials — but make sure your implementation handles the differences between sandbox and production from day one.

Environment Configuration

Add these to your .env:

MPESA_ENV=sandbox
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your_passkey
MPESA_CALLBACK_URL=https://yourapp.co.ke/api/mpesa/callback

Getting an Access Token

Every M-Pesa API call requires a Bearer token. Generate one by Base64-encoding your consumer key and secret, then hitting the OAuth endpoint.

The STK Push Request

The STK Push payload requires a timestamp, a password (Base64 of shortcode + passkey + timestamp), and the amount and phone number. Phone numbers must be in the format 2547XXXXXXXX — strip leading zeros or the + prefix.

Handling the Callback

Safaricom sends a POST to your callback URL after payment. This is where most implementations fail — the callback can arrive seconds or minutes later, your server needs to be publicly accessible, and you must return a 200 response immediately or Safaricom will retry.

Store the callback data, process it async via a job, and update your transaction record accordingly.

Production Checklist

  • Use HTTPS for the callback URL
  • Idempotency — check if the transaction already exists before processing
  • Log every request and response
  • Handle timeouts gracefully (user may pay but callback is delayed)
  • Test with real amounts before going live

M-Pesa integration is not complicated once you understand the flow. The biggest issues we see are developers not handling the callback correctly and not testing with real transactions before launch. Do both.

Need software built?

Tell us what you need. We respond within 24 hours with a realistic quote.