Logo Lanfrica

devmoseslabs/payhero_flask_mpesa

Domaine:

digital infrastructure

Type de record:

software
Créateur:
dev
Hôte:
A lightweight Flask app for initiating M-Pesa STK push payments via PayHero, handling callbacks, and tracking payment status in real time. Ideal for developers building payment-enabled applications or testing M-Pesa integration. # PayHero Flask M-Pesa Integration A Flask application for integrating **PayHero M-Pesa STK Push** with callback handling, transaction storage, and reconciliation. --- ## Features - M-Pesa STK Push via PayHero API - Strict Kenyan phone number validation (2547XXXXXXXX / 2541XXXXXXXX) - SQLite database for transaction tracking - Reliable callback processing - Manual payment reconciliation endpoint - Callback logging for audits and debugging - Environment-based configuration --- ## Project Structure ``` payhero_flask_mpesa/ ├── app.py ├── requirements.txt ├── README.md ├── LICENSE ├── .env └── templates/ └── index.html ``` --- ## Requirements - Python 3.8+ - PayHero API credentials - Internet access --- ## Installation ### Clone the repository ``` git clone github.com cd payhero_flask_mpesa ``` ### Create and activate virtual environment ``` python3 -m venv venv source venv/bin/activate ``` ### Install dependencies ``` pip install -r requirements.txt ``` --- ## Environment Configuration Create a `.env` file in the project root: ``` SECRET_KEY=dev_secret_key DATABASE=transactions.db PAYHERO_BASE_URL=backend.payhero.co.ke PAYHERO_CHANNEL_ID=your_channel_id PAYHERO_PROVIDER=m-pesa API_USERNAME=your_payhero_api_username API_PASSWORD=your_payhero_api_password CALLBACK_URL=your_domain.com ``` ### Notes - `CALLBACK_URL` must be publicly accessible - Use Ngrok during development - Do not commit `.env` to GitHub --- ## Running the Application ``` python app.py ``` The app runs on: ``` localhost ``` On startup: - SQLite database is created automatically - Payments table is initialized --- ## API Endpoints ### `/` Displays the payment page. ### `/pay` (POST) Initiates M-Pesa STK Push. Required fields: - amount (minimum 1 KES) - phone_number (2547XXXXXXXX) - external_reference (exactly 8 characters) ### `/callback` (POST / GET) Handles PayHero payment callbac …