A production-hardened Django app for Safaricom's Daraja M-PESA API — STK Push, C2B, B2C, idempotent callbacks, and more.
# mainfinity-django-mpesa
A production-hardened Django app for Safaricom's Daraja M-PESA API.
Extracted from production use in Zaruni and packaged for reuse across any Django project that needs to collect or send money via M-PESA.
---
## Features
- **STK Push** — trigger the M-PESA PIN prompt on a customer's phone
- **C2B** — receive paybill/till payments with validation and confirmation callbacks
- **B2C** — send payouts, salaries, or refunds to phone numbers
- **Transaction Status** — query stuck payments for reconciliation
- **Account Balance** — check your M-PESA business account balance
- **Reversal** — reverse a transaction programmatically
- **Idempotent callbacks** — Safaricom retries are handled safely; a payment is settled exactly once
- **IP allowlist middleware** — rejects callbacks from non-Safaricom sources
- **Mock client** — full test suite runs with zero network access; ships a `MockDarajaClient` for your own tests
- **Swappable models** — subclass the abstract models and add your own fields (orders, users, wallets)
- **Django signals** — hook into `payment_confirmed`, `payout_completed`, etc. without modifying library code
## Requirements
- Python 3.10, 3.11, or 3.12
- Django 4.2 or 5.1
- djangorestframework ≥ 3.14
- requests ≥ 2.31
- Celery ≥ 5.3 *(optional — set `USE_CELERY=False` for synchronous processing)*
## Installation
```bash
pip install mainfinity-django-mpesa
# With Celery support:
pip install mainfinity-django-mpesa[celery]
```
## Quick start
See the full quickstart guide to go from install to a working STK Push in under 10 minutes.
```python
# 1. Add to INSTALLED_APPS
INSTALLED_APPS = [
...
"django_mpesa",
]
# 2. Configure
MPESA = {
"ENV": "sandbox",
"CONSUMER_KEY": lambda: os.environ["MPESA_CONSUMER_KEY"],
"CONSUMER_SECRET": lambda: os.environ["MPESA_CONSUMER_SECRET"],
"SHORTCODE": "174379",
"PASSKEY": lambda: os.environ["MPESA_PASSKEY"],
"STK_CALLBACK_URL": "
yourapp.com",
"TRANSACTION_ …