惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
小众软件
小众软件
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
博客园_首页
T
Tailwind CSS Blog
The Cloudflare Blog
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
U
Unit 42
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
腾讯CDC
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
MpesaBooks — devto
sharkflow ltd · 2026-06-03 · via DEV Community

sharkflow ltd

{
  "title": "How to Track M-Pesa Transactions for Business: Building Accounting Systems for African Mobile Money",
  "content": "# How to Track M-Pesa Transactions for Business: Building Accounting Systems for African Mobile Money\n\nIf you're a Kenyan developer working with SMEs, you've probably heard this: \"We receive money on M-Pesa, but our accounting is a nightmare.\" With M-Pesa processing over $320 billion annually in Kenya alone, and 60M+ mobile money users across East Africa, the gap between transaction velocity and accounting clarity is *massive*. This is where systems like MpesaBooks come in—and understanding how they work technically can teach us a lot about building financial infrastructure for Africa.\n\nLet's talk about the engineering challenges, architectural decisions, and practical solutions for tracking M-Pesa transactions at scale.\n\n## The Problem: Why M-Pesa Accounting is Hard\n\nHere's what happens in reality:\n\n1. A customer pays 15,000 KES via M-Pesa\n2. The SME owner sees it on their phone\n3. Three other payments come in\n4. By end of day, they have no idea which customer paid for what\n5. Their accountant is manually cross-referencing M-Pesa statements with invoices\n\nFor a business doing 50+ transactions daily, this is 2-3 hours of busywork. For one doing 500+ transactions, it's unworkable without automation.\n\nThe technical solution requires three components:\n- **Real-time transaction capture** from M-Pesa\n- **Intelligent matching** of payments to invoices/customers\n- **Scalable storage** that handles spike traffic on mobile networks\n\n## API Design: Connecting to M-Pesa\n\nM-Pesa exposes two main integration points for businesses: **STK Push** (for initiating payments) and **B2B API** (for receiving payments). For accounting, we care primarily about inbound tracking.\n\nSafaricom provides callback webhooks when money comes in. Here's how a basic receiver might look:\n\n```

python\nfrom fastapi import FastAPI, Request\nfrom datetime import datetime\nimport hashlib\nimport json\n\napp = FastAPI()\n\n# M-Pesa sends callbacks with transaction details\n@app.post(\"/api/mpesa/callback\")\nasync def mpesa_callback(request: Request):\n    \"\"\"\n    M-Pesa sends JSON like:\n    {\n        \"TransactionType\": \"Pay Bill Online\",\n        \"TransID\": \"OHI20D5N6Y\",\n        \"TransTime\": \"20231215143521\",\n        \"TransAmount\": 15000,\n        \"BusinessShortCode\": \"174379\",\n        \"BillRefNumber\": \"INV-2023-001\",\n        \"InvokedParty\": \"254712345678\",\n        \"OriginatorPartyCode\": \"254700000000\",\n        \"OriginatedParty\": null,\n        \"FirstName\": \"John\",\n        \"MiddleName\": \"\",\n        \"LastName\": \"Doe\"\n    }\n    \"\"\"\n    \n    body = await request.json()\n    \n    try:\n        # Extract key data\n        trans_id = body.get(\"TransID\")\n        amount = body.get(\"TransAmount\")\n        phone = body.get(\"OriginatorPartyCode\")\n        ref = body.get(\"BillRefNumber\")  # Critical: customer reference\n        trans_time = body.get(\"TransTime\")\n        \n        # Verify callback authenticity (Safaricom sends validation tokens)\n        if not verify_mpesa_signature(body):\n            return {\"ResultCode\": 1, \"ResultDesc\": \"Invalid signature\"}\n        \n        # Store immediately (idempotent key = trans_id)\n        transaction = await db.transactions.insert_one({\n            \"mpesa_id\": trans_id,\n            \"amount\": amount,\n            \"phone\": phone,\n            \"reference\": ref,\n            \"timestamp\": datetime.strptime(trans_time, \"%Y%m%d%H%M%S\"),\n            \"status\": \"pending\",\n            \"created_at\": datetime.utcnow()\n        })\n        \n        # Queue for matching (async job)\n        await queue.enqueue(\n            \"match_transaction\",\n            transaction_id=str(transaction.inserted_id),\n            reference=ref,\n            phone=phone\n        )\n        \n        # Acknowledge immediately to M-Pesa\n        return {\n            \"ResultCode\": 0,\n            \"ResultDesc\": \"Accepted\"\n        }\n    \n    except Exception as e:\n        logger.error(f\"Callback processing failed: {e}\")\n        # Don't crash—M-Pesa will retry\n        return {\"ResultCode\": 0, \"ResultDesc\": \"Accepted\"}\n\n\ndef verify_mpesa_signature(body: dict) -> bool:\n    # Safaricom provides a validation field in callbacks\n    # In production, validate with their public key\n    return True  # Placeholder\n

```\n\nKey design decisions here:\n\n1. **Idempotent storage**: M-Pesa callbacks can retry. Using `mpesa_id` as a unique key prevents duplicate entries.\n2. **Async processing**: We acknowledge to M-Pesa immediately, then do matching in background. Mobile networks in Kenya are unpredictable—don't block on slow database writes.\n3. **Reference extraction**: SMEs pass invoice numbers in `BillRefNumber`. This is gold for auto-matching.\n\n## Database Schema: What Actually Scales\n\nAfter processing millions of transactions, here's what works:\n\n```

javascript\n// MongoDB schema for