Skip to main content
All posts

Web Development

How I Built an M-Pesa Integration for a Nairobi Retailer

6 min read

Commerce dashboard and mobile checkout interface shown on modern devices

A Nairobi clothing retailer was managing orders via WhatsApp. Payments were disputed. Inventory was invisible. The fix was a full-stack e-commerce platform with Safaricom's Daraja API at the core.

The Challenge

The Daraja API documentation is thorough but the sandbox environment is fragile. The main gotchas I hit:

  • STK Push callbacks don't fire in sandbox — you need to simulate them manually
  • Timestamps must be in YYYYMMDDHHmmss format in East Africa Time, not UTC
  • Passkey rotation happens monthly in production — build for it

The Architecture

I used Next.js API routes as the backend layer. Each M-Pesa request flows through three steps:

  1. Initiate — client calls /api/mpesa/initiate, which hits the Daraja STK Push endpoint
  2. Callback — Safaricom POSTs the result to /api/mpesa/callback
  3. Verify — client polls /api/mpesa/status/[checkoutId] until confirmed

The callback URL must be publicly accessible. I used ngrok in development.

The Result

Order processing time dropped by 40%. Zero payment disputes in the first 3 months. The owner now has a real-time dashboard.

Chat with me