M-Pesa Payment Integration with FastAPI
======================================
This project provides a robust integration of M-Pesa's Daraja API (STK Push - Lipa na M-Pesa Online) with a FastAPI application in Python. It enables users to initiate payments via an STK Push prompt on their mobile phones and processes callbacks from M-Pesa to confirm transaction status.
## Features
- Generate M-Pesa OAuth access token for secure API authentication.
- Initiate STK Push payment requests to prompt users for payment on their mobile devices.
- Handle M-Pesa callback responses to verify payment success or failure.
- Input validation using Pydantic for secure and reliable request handling.
- Comprehensive error handling for timeouts, network issues, and API errors.
- Logging for debugging and monitoring transaction flow.
- Built with FastAPI for high-performance, modern API development.
## Prerequisites
Before running the application, ensure you have the following:
### M-Pesa Daraja API Credentials:
- Register on the Safaricom Developer Portal.
- Create an app to obtain:
- Consumer Key
- Consumer Secret
- Shortcode (Business Shortcode)
- Passkey (Provided by Safaricom for live apps; use the sandbox passkey for testing).
- For sandbox testing, use test credentials provided by Safaricom (e.g., phone number: 254708374149).
### Python Environment:
- Python 3.8 or higher.
- Install required packages after setting up the project (see Installation).
### Expose Local Server (for Testing):
- Install Ngrok to expose your local server for callback URLs, as M-Pesa requires a publicly accessible HTTPS URL:
- Download and install Ngrok.
- Run `ngrok http 8000` to get a public URL (e.g., `
your-ngrok-url.ngrok.io`).
## Installation
Follow these steps to set up the project:
### Clone the Repository:
```sh
git clone
github.com
cd mpesa_fastapi
```
### Set Up a Virtual Environment (optional but recommended):
```sh
python -m venv venv
source venv …