Investment Portfolio / M-Pesa Financial Infrastructure
๏ฟฝ Financial Infrastructure ยท Transaction Systems

M-Pesa Institutional Payment Infrastructure

Production-grade payment backbone enabling green ventures to scale across African markets. Bank-grade security controls, comprehensive audit trails, and regulatory compliance meeting institutional investor requirements โ€” facilitating $2M+ in transaction value for sustainable investments.

Role Financial Infrastructure Architect
Duration 2 Months
Category Digital Financial Services / Transaction Infrastructure
Status Institutional-Grade Production
๐Ÿš€ Visit Live Infrastructure โ†—

Bank-grade controls for institutional capital.

M-Pesa integration is deceptively complex.

The Safaricom Daraja API documentation is extensive but the real-world implementation has numerous edge cases: token expiry during peak load, callback URL validation quirks, phone number format inconsistencies, sandbox vs. production behavioral differences, and the need for idempotent transaction handling.

Many Kenyan startups ship insecure M-Pesa integrations with hardcoded credentials, no rate limiting, and no callback verification โ€” creating vulnerability surfaces that put user financial data at risk.

A production-hardened payment backbone.

This gateway abstracts the complexity of Daraja API into a clean, documented REST API. OAuth 2.0 tokens are managed with automatic refresh (maintaining a 5-minute buffer before expiry). STK Push requests are initiated with comprehensive phone number normalization supporting all Kenyan formats.

Transaction results are cached with 1-hour TTL for idempotent retries. Callbacks are verified against Safaricom's IP ranges. Every sensitive parameter is masked in logs. The entire system switches between sandbox and production with a single environment variable.

Request lifecycle.

๐Ÿ“ฑ

Client Request

React frontend sends payment initiation request with amount, phone number, and transaction reference. CORS and rate limiting applied immediately.

๐Ÿ”

Token Management

OAuth 2.0 bearer token checked against cache. If expired or within 5-minute buffer, auto-refresh from Daraja API before proceeding.

๐Ÿ“ค

STK Push Initiation

Phone number normalized (07XX, 01XX, +254XX, 254XX all handled). STK Push request sent to Safaricom. Transaction ID logged and cached.

๐Ÿ“ฅ

Callback Processing

Safaricom POSTs result to callback URL. IP verified against allowlist. Transaction status updated. Client notified via polling or WebSocket.

What makes it work.

  • ๐Ÿ”‘ OAuth 2.0 auto-refresh โ€” Token lifecycle managed transparently. Pre-emptive refresh prevents auth failures during active transactions.
  • ๐Ÿ“ฑ Phone number normalization โ€” Accepts 07XX, 01XX, +254XX, 254XX formats. Validates against Safaricom number ranges before API call.
  • ๐Ÿ’พ Transaction caching โ€” 1-hour TTL cache ensures idempotent status queries. Prevents duplicate charges on retry scenarios.
  • ๐Ÿ”„ Environment switching โ€” Single env variable switches entire system between sandbox and production. API URLs, credentials, and behaviors adjust automatically.
  • ๐Ÿ›ก๏ธ Helmet.js hardening โ€” HTTP security headers including CSP, HSTS, X-Content-Type-Options, and referrer policy configured for financial-grade compliance.
  • ๐Ÿšฆ Rate limiting โ€” Per-IP and per-endpoint rate limiting prevents abuse. Configurable thresholds for different route sensitivity levels.
  • ๐Ÿ“‹ Audit logging โ€” Every transaction state change logged with timestamps, request metadata, and sanitized payloads for compliance and debugging.
  • ๐Ÿ” Transaction status API โ€” Clients can poll for payment completion status. Returns structured response with result code, description, and receipt number.

Built with purpose.

๐Ÿ–ฅ๏ธ Backend

Express.js 5 with middleware chain: CORS โ†’ Rate Limit โ†’ Helmet โ†’ Auth โ†’ Route handlers. Clean separation of concerns.

Express.js 5 Node.js Helmet.js

โš›๏ธ Frontend

React + Vite checkout interface with real-time payment status polling and user-friendly error messaging.

React Vite Axios

๐Ÿ’ณ Payment API

Safaricom Daraja API with STK Push, OAuth 2.0, callback processing, and B2C disbursement endpoints.

Daraja API STK Push OAuth 2.0

๐Ÿ”’ Security

Multi-layered security: HTTP headers, rate limiting, CORS, IP allowlisting, input sanitization, and credential masking.

Helmet.js Rate Limiting CORS

Hard-won insights.

๐Ÿ”„

Sandbox vs. Production Drift

Daraja sandbox behavior diverges from production in subtle ways โ€” different response codes, timing, and callback formats. Required building a comprehensive test harness with mock responses.

โฑ๏ธ

Token Race Conditions

Under high concurrency, multiple requests could trigger simultaneous token refreshes. Implemented a mutex-based token manager ensuring exactly one refresh at a time with queued waiters.

๐Ÿ“ฑ

Phone Format Diversity

Kenyan phone numbers arrive in 7+ formats. Building a normalizer that handles every variation (including copy-paste artifacts with spaces and hyphens) required extensive field testing.

Need M-Pesa integration for your platform?

I've built production payment infrastructure handling real money. Let's talk security and scalability.

Start a Conversation โ†—