A Python SDK for integrating Safaricom M-Pesa services into Python applications.
# M-Pesa Python Integration Library
A simple Python library for integrating M-Pesa STK Push (Lipa Na M-Pesa Online) payments into your applications.
## Features
- Easy STK Push integration
- Automatic phone number validation and formatting
- Secure token management with auto-refresh
- Amount validation with M-Pesa limits
- Comprehensive error handling
- Kenyan phone number support
## Installation
```bash
pip install python-mpesa-daraja
```
## Requirements
- Python 3.8+
- requests
- phonenumbers
## Quick Start
```python
from python_mpesa import MpesaGateway
# Initialize the gateway
mpesa = MpesaGateway(
business_shortcode="your_business_shortcode",
consumer_key="your_consumer_key",
consumer_secret="your_consumer_secret",
pass_key="your_pass_key",
access_token_url="
sandbox.safaricom.co.ke", # Use production URL in live environment
stk_push_url="
sandbox.safaricom.co.ke" # Use production URL in live environment
)
# Initiate STK Push
response = mpesa.stk_push(
phone_number="0712345678",
amount=100,
account_reference="account_reference", # e.g., invoice number
transaction_type="CustomerPayBillOnline", # or "CustomerBuyGoodsOnline" for Till
transaction_desc="Payment description", # e.g., "Payment for Order #12345"
callback_url="your_callback_url" # e.g., "
yourdomain.com"
)
print(response)
```
## Configuration
### Sandbox Environment
```python
ACCESS_TOKEN_URL = "
sandbox.safaricom.co.ke"
STK_PUSH_URL = "
sandbox.safaricom.co.ke"
```
### Production Environment
```python
ACCESS_TOKEN_URL = "
api.safaricom.co.ke"
STK_PUSH_URL = "
api.safaricom.co.ke"
```
## API Reference
### MpesaGateway
The main class for interacting with the M-Pesa API.
#### Initializa …