- Overview
- Features
- Screenshots
- Technology Stack
- Prerequisites
- Installation
- Configuration
- Usage
- API Endpoints
- Database Schema
- Project Structure
- Testing
- Deployment
- Troubleshooting
- Contributing
- License
- Author
- Acknowledgments
Alphacode Shop is a sophisticated M-Pesa payment integration system built with Django. It provides a seamless way to accept M-Pesa payments through STK Push, featuring a stunning gold and dark theme UI, real-time transaction monitoring, and comprehensive payment tracking.
The application leverages Safaricom's Daraja API to initiate STK Push requests, process payment callbacks, and maintain a detailed transaction history in an SQLite database.
- 🎯 Production-Ready: Complete STK push implementation with proper error handling
- 🎨 Beautiful UI: Premium gold and dark theme with smooth animations
- ⚡ Real-Time Updates: Automatic transaction status checking and live updates
- 🔒 Secure: Proper validation, CSRF protection, and secure API communication
- 📱 Responsive: Works flawlessly on desktop, tablet, and mobile devices
-
✅ M-Pesa STK Push Integration
- Initiate STK push to customer phones
- Support for multiple phone number formats (07xx, 2547xx, +2547xx)
- Sandbox and production environment support
-
✅ Payment Processing
- Real-time callback handling from Safaricom
- Automatic transaction status verification
- Transaction timeout handling (120 seconds)
-
✅ Transaction Management
- Complete transaction history with SQLite storage
- Real-time status updates (Pending, Completed, Failed, Cancelled)
- Transaction receipt tracking
-
🎨 Premium Design
- Gold and dark theme with gradient effects
- Smooth animations and transitions
- Glassmorphism card designs
- Custom scrollbar styling
-
📱 Responsive Components
- Mobile-first approach
- Adaptive grid layouts
- Touch-friendly buttons
-
🔄 Interactive Elements
- Amount preset buttons (100, 500, 1000, 5000 KES)
- Real-time status messages
- Loading spinners and overlays
- Auto-refresh transaction list
-
🛡️ Input Validation
- Phone number format validation
- Amount validation (minimum KES 1)
- CSRF protection
-
🔐 API Security
- OAuth 2.0 authentication with Safaricom
- Secure credential management
- Base64 password encoding
| Technology | Version | Purpose |
|---|---|---|
| Django | 4.2.7 | Backend framework |
| Python | 3.8+ | Programming language |
| HTML5 | - | Structure and markup |
| CSS3 | - | Styling and animations |
| JavaScript | ES6+ | Client-side functionality |
| jQuery | 3.7.1 | AJAX requests and DOM manipulation |
| SQLite3 | - | Database |
| Requests | 2.31.0 | HTTP client for API calls |
| python-decouple | 3.8 | Environment variable management |
| Font Awesome | 6.4.0 | Icons and visual elements |
| Google Fonts | - | Inter font family |
Before you begin, ensure you have the following:
- Python 3.8 or higher installed
- pip (Python package manager)
- Git (for version control)
- A Safaricom Developer Account (Register here)
- Ngrok account (for local testing callbacks) (Sign up here)
- Create an app on Safaricom Developer Portal
- Note down your:
- Consumer Key
- Consumer Secret
- Passkey (use test passkey for sandbox)
- Subscribe to M-Pesa Sandbox APIs
git clone https://github.com/alphacodeke/alphacode-shop.git
cd alphacode-shopWindows:
python -m venv venv
venv\Scripts\activatemacOS/Linux:
python3 -m venv venv
source venv/bin/activatepip install -r requirements.txtpython manage.py makemigrations mpesa_app
python manage.py migratepython manage.py createsuperuser-
Open
alphacode_shop/settings.py -
Update the following M-Pesa configuration variables:
# M-Pesa Configuration
MPESA_ENVIRONMENT = 'sandbox' # Change to 'production' for live
MPESA_CONSUMER_KEY = 'your_consumer_key_here'
MPESA_CONSUMER_SECRET = 'your_consumer_secret_here'
MPESA_PASSKEY = 'bfb279f9aa9bdbcf158e97dd71a467cd2e0c893059b10f78e6b72ada1ed2c919' # Sandbox passkey
MPESA_SHORTCODE = '174379' # Sandbox shortcode
MPESA_BUSINESS_SHORTCODE = '174379'
MPESA_ACCOUNT_REFERENCE = 'Alphacode Shop'
MPESA_TRANSACTION_DESC = 'Payment for goods'- Start Ngrok:
ngrok http 8000-
Copy the HTTPS URL (e.g.,
https://abc123.ngrok.io) -
Update callback URL in settings.py:
MPESA_CALLBACK_URL = 'https://abc123.ngrok.io/api/mpesa/callback/'For production deployment:
- Set
DEBUG = Falsein settings.py - Update
ALLOWED_HOSTSwith your domain - Use environment variables for sensitive data
- Set
MPESA_ENVIRONMENT = 'production' - Use production M-Pesa credentials
- Ensure HTTPS is enabled for callback URL
- Set up a proper database (PostgreSQL recommended)
python manage.py runserver- Open your browser and navigate to
http://localhost:8000 - The main payment interface will be displayed
- Enter a phone number and amount
- Click "Send STK Push"
- Check the phone for M-Pesa prompt
- Enter PIN to complete payment
- Transaction status will update automatically
Test Phone Numbers:
- Safaricom test number:
254708374149 - Test PIN:
0000
Test Amounts:
- Any amount works in sandbox
- Navigate to
http://localhost:8000/admin - Login with superuser credentials
- View and manage transactions
- Monitor payment statuses
| Endpoint | Method | Description |
|---|---|---|
/ |
GET | Main payment interface |
/api/stk-push/ |
POST | Initiate STK push request |
/api/mpesa/callback/ |
POST | M-Pesa payment callback handler |
/api/transaction/<uuid:id>/ |
GET | Check transaction status |
/api/transactions/ |
GET | Retrieve recent transactions |
POST /api/stk-push/
Content-Type: application/json
{
"phone_number": "254712345678",
"amount": 1000
}{
"success": true,
"message": "STK push sent successfully. Please check your phone.",
"transaction_id": "550e8400-e29b-41d4-a716-446655440000",
"data": {
"MerchantRequestID": "abc-123",
"CheckoutRequestID": "ws_CO_123",
"ResponseCode": "0",
"ResponseDescription": "Success. Request accepted for processing",
"CustomerMessage": "Success. Request accepted for processing"
}
}| Field | Type | Description |
|---|---|---|
id |
UUID | Primary key |
phone_number |
CharField(15) | Customer phone number |
amount |
DecimalField | Transaction amount |
account_reference |
CharField(20) | Payment reference |
transaction_desc |
CharField(50) | Transaction description |
merchant_request_id |
CharField(100) | Merchant request ID from M-Pesa |
checkout_request_id |
CharField(100) | Checkout request ID |
response_code |
CharField(10) | STK push response code |
response_description |
TextField | Response description |
customer_message |
TextField | Message to customer |
result_code |
CharField(10) | Final result code |
result_desc |
TextField | Result description |
mpesa_receipt_number |
CharField(50) | M-Pesa receipt number |
transaction_date |
DateTimeField | M-Pesa transaction timestamp |
status |
CharField(20) | Transaction status |
created_at |
DateTimeField | Record creation timestamp |
updated_at |
DateTimeField | Record update timestamp |
alphacode_shop/
│
├── alphacode_shop/ # Project configuration
│ ├── __init__.py
│ ├── settings.py # Django settings
│ ├── urls.py # Main URL routing
│ └── wsgi.py # WSGI configuration
│
├── mpesa_app/ # Main application
│ ├── __init__.py
│ ├── admin.py # Admin interface
│ ├── apps.py # App configuration
│ ├── models.py # Database models
│ ├── views.py # View logic
│ ├── urls.py # App URL routing
│ ├── mpesa_credentials.py # M-Pesa auth handling
│ ├── mpesa_api.py # M-Pesa API integration
│ │
│ └── templates/ # HTML templates
│ └── mpesa_app/
│ └── index.html # Main payment page
│
├── static/ # Static files
│ └── css/
│ └── style.css # Main stylesheet
│
├── db.sqlite3 # SQLite database
├── manage.py # Django management script
├── requirements.txt # Python dependencies
└── README.md # Project documentation
python manage.py test mpesa_appTo run tests with coverage:
pip install coverage
coverage run manage.py test mpesa_app
coverage report
coverage html # Generates HTML coverage report- STK push initiation with valid credentials
- Phone number format validation
- Amount validation
- Callback processing
- Transaction status updates
- Error handling scenarios
- UI responsiveness
- Database operations
-
Create account at PythonAnywhere
-
Clone repository:
git clone https://github.com/alphacodeke/alphacode-shop.git-
Set up virtual environment and install dependencies
-
Configure WSGI file
-
Set up static files
-
Update ALLOWED_HOSTS and DEBUG settings
- Create Heroku app:
heroku create alphacode-shop- Add Procfile:
web: gunicorn alphacode_shop.wsgi
- Set environment variables:
heroku config:set MPESA_CONSUMER_KEY=your_key
heroku config:set MPESA_CONSUMER_SECRET=your_secret- Deploy:
git push heroku main- Set
DEBUG = False - Update
SECRET_KEY - Configure production database
- Set up HTTPS/SSL
- Update callback URL to production domain
- Use production M-Pesa credentials
- Enable security middleware
- Set up error monitoring
- Configure backup system
Issue: STK push request fails Solution:
- Verify consumer key and secret are correct
- Check if ngrok URL is properly set in callback
- Ensure phone number is in correct format
- Check Safaricom API status
Issue: M-Pesa callback not reaching application Solution:
- Verify callback URL is accessible (use ngrok inspect)
- Check if URL is HTTPS (required for production)
- Ensure firewall isn't blocking requests
- Check server logs for incoming requests
Issue: Migration errors Solution:
python manage.py migrate --fake
python manage.py makemigrations
python manage.py migrateIssue: CSS/JS not loading Solution:
python manage.py collectstaticContributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch:
git checkout -b feature/amazing-feature
- Commit your changes:
git commit -m 'Add amazing feature' - Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
- Follow PEP 8 for Python code
- Use ESLint configuration for JavaScript
- Write meaningful commit messages
- Add comments for complex logic
- Update documentation as needed
Use the GitHub Issues page to report bugs or suggest features.
This project is licensed under the MIT License - see the LICENSE file for details.
MIT License
Copyright (c) 2026 Anthony Karanja
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
- Safaricom - For providing the Daraja API
- Django Community - For the amazing framework
- Font Awesome - For beautiful icons
- Google Fonts - For the Inter font family
- All Contributors - Who help improve this project
- v1.0.0 (2026-04-22)
- Initial release
- Complete STK push functionality
- Gold and dark theme UI
- Transaction management system
```