A Python SDK for integrating M-Pesa services, including STK Push, C2B, and B2C payments, with easy-to-use authentication and transaction handling.
# M-Pesa Python SDK
## Overview
The M-Pesa Python SDK simplifies the integration of your Python applications with the M-Pesa API, enabling seamless access to mobile money services such as payments, payouts, and transaction management. This SDK is designed to accelerate your development by providing a robust interface for M-Pesa’s STK Push, C2B, B2C, and authentication APIs.
## Features
- **Authentication**: Retrieve OAuth2 access tokens.
- **STK Push**: Initiate mobile money payments from customers.
- **Customer to Business (C2B)**: Process customer payments with validation and confirmation callbacks.
- **Business to Customer (B2C)**: Payouts for salaries, rewards, or refunds.
- **Error Handling**: Comprehensive exception management.
- **Logging**: Built-in logging for debugging and monitoring.
## Requirements
- Python 3.7 or higher
- An M-Pesa API developer account
- Consumer Key and Consumer Secret from the M-Pesa API portal
- Publicly accessible callback URLs (for C2B and B2C)
## Installation
Install the SDK using pip:
```bash
pip install mpesa_client
```
## Configuration Guide
### Option 1: Using Environment Variables
This is the recommended approach to keep your credentials and configuration secure and centralized.
1. **Create a `.env` File**
Place a `.env` file in your project root with the following content:
```dotenv
# API Base URL and Endpoints
BASE_URL=
sandbox.safaricom.et
TOKEN_GENERATE_ENDPOINT=/v1/token/generate
STK_PUSH_ENDPOINT=/mpesa/stkpush/v1/processrequest
C2B_REGISTER_URL_ENDPOINT=/mpesa/c2b/v1/registerurl
C2B_PAYMENTS_ENDPOINT=/mpesa/c2b/v1/simulate
B2C_PAYMENT_REQUEST_ENDPOINT=/mpesa/b2c/v1/paymentrequest
# Authentication
CLIENT_KEY=your_client_key
CLIENT_SECRET=your_client_secret
# Logging and Environment
TIMEOUT=30
MPESA_LOG_DIR=./logs
LOG_LEVEL=DEBUG
ENVIRONMENT=DEV # Set to TEST to disable console logging
```
2. **Access Configuration in Code**
The SDK automatically loads these variables using the `dotenv` package …