The most complete M-Pesa Daraja 2.0 integration for Django — STK Push, C2B, B2C
# django-mpesa
> The most complete M-Pesa Daraja 2.0 integration for Django. STK Push, C2B, B2C — batteries included.
Built and maintained by stickmanKE • Hire me for M-Pesa integration →
---
## Features
- ✅ **STK Push** (Lipa Na M-Pesa Online) — with automatic callback handling
- ✅ **STK Query** — check payment status anytime
- ✅ **C2B** (Paybill / Buy Goods) — URL registration + confirmation
- ✅ **B2C** (Disbursements) — send money to customers/withdrawals
- ✅ **Django Signals** — hook into payment events without modifying library code
- ✅ **Django Admin** — view all transactions out of the box
- ✅ **Token caching** — automatic OAuth token refresh using Django cache
- ✅ **Phone normalisation** — accepts `07xx`, `+254xx`, `254xx`
- ✅ **Full test suite** — pytest with Django
---
## Installation
```bash
pip install django-mpesa
```
Add to `INSTALLED_APPS`:
```python
INSTALLED_APPS = [
...
'django_mpesa',
]
```
Include URLs:
```python
# urls.py
from django.urls import path, include
urlpatterns = [
...
path('mpesa/', include('django_mpesa.urls', namespace='mpesa')),
]
```
Run migrations:
```bash
python manage.py migrate
```
---
## Configuration
Add to your `settings.py`:
```python
MPESA_CONFIG = {
# Daraja credentials (from developer.safaricom.co.ke)
'CONSUMER_KEY': 'your_consumer_key',
'CONSUMER_SECRET': 'your_consumer_secret',
# STK Push / C2B settings
'SHORTCODE': '174379', # Your paybill or till number
'PASSKEY': 'your_lipa_na_mpesa_passkey',
# 'sandbox' or 'production'
'ENVIRONMENT': 'sandbox',
# B2C settings (disbursements)
'INITIATOR_NAME': 'your_initiator_name',
'INITIATOR_PASSWORD': 'your_initiator_password',
'B2C_SHORTCODE': '600000', # Usually same as SHORTCODE
# Callback URLs (must be HTTPS and publicly reachable)
'STK_CALLBACK_URL': '
yourdomain.com',
'C2B_VALIDATION_URL': '
yourdomain.com',
'C2B_CONFIRMATION_URL': '
yourdomain.com …