Flask app integrating Safaricom Daraja API β STK Push, C2B, B2C payments, callback handling & transaction tracking. Built for Kenyan fintech workflows
# π’ M-Pesa Daraja API Integration
> A full Flask web application integrating Safaricom's Daraja API β STK Push, C2B, B2C, callbacks, and real-time transaction tracking.
---
## β¨ Features
| Feature | Description |
|---|---|
| π² **STK Push** | Prompt customer's phone to enter M-Pesa PIN and pay |
| π¦ **C2B** | Register Paybill/Till callbacks, validate & confirm payments |
| πΈ **B2C** | Send money from business to customer (salaries, refunds) |
| π **Callbacks** | Full Safaricom callback handling with parsed results |
| π **Transaction Log** | Real-time log of all payment attempts and outcomes |
| π§ͺ **Unit Tests** | Tests for phone formatting, callback parsing, password generation |
---
## π Quick Start
```bash
git clone
github.com
cd mpesa-daraja-integration
pip install -r requirements.txt
# Set up credentials
cp .env.example .env
# Edit .env with your Daraja API keys
python run.py
```
Open **
http://127.0.0.1:5000**
---
## π Getting Daraja Credentials
1. Go to **
developer.safaricom.co.ke**
2. Create an account and log in
3. Go to **My Apps β Add New App**
4. Select **Lipa Na M-Pesa Sandbox**
5. Copy your **Consumer Key** and **Consumer Secret**
6. Paste them into your `.env` file
---
## π Exposing Callbacks with ngrok (Testing)
Safaricom needs a public URL to send callbacks. Use ngrok for local testing:
```bash
# Install ngrok from ngrok.com, then:
ngrok http 5000
```
Copy the HTTPS URL (e.g. `
abc123.ngrok.io`) and set in `.env`:
```
MPESA_CALLBACK_URL=
abc123.ngrok.io
```
---
## π Project Structure
```
mpesa-daraja-integration/
βββ run.py # Entry point
βββ .env.example # Credentials template
βββ requirements.txt
βββ app/
β βββ __init__.py # Flask factory
β βββ mpesa.py # β Core Daraja API client
β βββ routes/
β βββ main.py # UI routes (STK, C2B, B2C)
β β β¦