Skip to content

alphacodeke/alphacode-shop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Alphacode Shop - M-Pesa STK Push Payment System

Django Python HTML5 CSS3 JavaScript SQLite M-Pesa jQuery

License: MIT Maintenance PRs Welcome

Alphacode Shop Banner

✨ A premium, fully-functional M-Pesa STK Push payment system with real-time transaction tracking ✨


📋 Table of Contents


🌟 Overview

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.

Why Alphacode Shop?

  • 🎯 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

✨ Features

Core Functionality

  • 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

User Interface

  • 🎨 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

Security & Validation

  • 🛡️ 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

📸 Screenshots

Desktop View

Desktop View

Mobile View

Mobile View

Payment Flow

Payment Flow


🛠️ Technology Stack

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

📦 Prerequisites

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)

Safaricom Developer Setup

  1. Create an app on Safaricom Developer Portal
  2. Note down your:
    • Consumer Key
    • Consumer Secret
    • Passkey (use test passkey for sandbox)
  3. Subscribe to M-Pesa Sandbox APIs

🚀 Installation

Step 1: Clone the Repository

git clone https://github.com/alphacodeke/alphacode-shop.git
cd alphacode-shop

Step 2: Set Up Virtual Environment

Windows:

python -m venv venv
venv\Scripts\activate

macOS/Linux:

python3 -m venv venv
source venv/bin/activate

Step 3: Install Dependencies

pip install -r requirements.txt

Step 4: Database Setup

python manage.py makemigrations mpesa_app
python manage.py migrate

Step 5: Create Superuser (Optional - for Admin Panel)

python manage.py createsuperuser

⚙️ Configuration

M-Pesa API Configuration

  1. Open alphacode_shop/settings.py

  2. 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'

Callback URL Setup (For Local Testing)

  1. Start Ngrok:
ngrok http 8000
  1. Copy the HTTPS URL (e.g., https://abc123.ngrok.io)

  2. Update callback URL in settings.py:

MPESA_CALLBACK_URL = 'https://abc123.ngrok.io/api/mpesa/callback/'

Production Configuration

For production deployment:

  1. Set DEBUG = False in settings.py
  2. Update ALLOWED_HOSTS with your domain
  3. Use environment variables for sensitive data
  4. Set MPESA_ENVIRONMENT = 'production'
  5. Use production M-Pesa credentials
  6. Ensure HTTPS is enabled for callback URL
  7. Set up a proper database (PostgreSQL recommended)

💻 Usage

Starting the Development Server

python manage.py runserver

Accessing the Application

  1. Open your browser and navigate to http://localhost:8000
  2. The main payment interface will be displayed
  3. Enter a phone number and amount
  4. Click "Send STK Push"
  5. Check the phone for M-Pesa prompt
  6. Enter PIN to complete payment
  7. Transaction status will update automatically

Testing with Sandbox

Test Phone Numbers:

  • Safaricom test number: 254708374149
  • Test PIN: 0000

Test Amounts:

  • Any amount works in sandbox

Admin Panel Access

  1. Navigate to http://localhost:8000/admin
  2. Login with superuser credentials
  3. View and manage transactions
  4. Monitor payment statuses

📡 API Endpoints

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

API Request Examples

Initiate STK Push

POST /api/stk-push/
Content-Type: application/json

{
    "phone_number": "254712345678",
    "amount": 1000
}

Response

{
    "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"
    }
}

🗄️ Database Schema

MpesaTransaction Model

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

📁 Project Structure

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

🧪 Testing

Running Tests

python manage.py test mpesa_app

Test Coverage

To run tests with coverage:

pip install coverage
coverage run manage.py test mpesa_app
coverage report
coverage html  # Generates HTML coverage report

Manual Testing Checklist

  • STK push initiation with valid credentials
  • Phone number format validation
  • Amount validation
  • Callback processing
  • Transaction status updates
  • Error handling scenarios
  • UI responsiveness
  • Database operations

🚢 Deployment

Deploying to PythonAnywhere

  1. Create account at PythonAnywhere

  2. Clone repository:

git clone https://github.com/alphacodeke/alphacode-shop.git
  1. Set up virtual environment and install dependencies

  2. Configure WSGI file

  3. Set up static files

  4. Update ALLOWED_HOSTS and DEBUG settings

Deploying to Heroku

  1. Create Heroku app:
heroku create alphacode-shop
  1. Add Procfile:
web: gunicorn alphacode_shop.wsgi
  1. Set environment variables:
heroku config:set MPESA_CONSUMER_KEY=your_key
heroku config:set MPESA_CONSUMER_SECRET=your_secret
  1. Deploy:
git push heroku main

Production Checklist

  • 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

🔧 Troubleshooting

Common Issues and Solutions

STK Push Not Sending

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

Callback Not Received

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

Database Errors

Issue: Migration errors Solution:

python manage.py migrate --fake
python manage.py makemigrations
python manage.py migrate

Static Files Not Loading

Issue: CSS/JS not loading Solution:

python manage.py collectstatic

🤝 Contributing

Contributions are welcome! Here's how you can help:

Contribution Guidelines

  1. Fork the repository
  2. Create a feature branch:
    git checkout -b feature/amazing-feature
  3. Commit your changes:
    git commit -m 'Add amazing feature'
  4. Push to the branch:
    git push origin feature/amazing-feature
  5. Open a Pull Request

Code Style

  • Follow PEP 8 for Python code
  • Use ESLint configuration for JavaScript
  • Write meaningful commit messages
  • Add comments for complex logic
  • Update documentation as needed

Reporting Issues

Use the GitHub Issues page to report bugs or suggest features.


📄 License

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.

👨‍💻 Author

Anthony Karanja

GitHub LinkedIn Twitter Email

Full-Stack Developer | M-Pesa Integration Specialist


🙏 Acknowledgments

  • 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

📊 Project Status

GitHub stars GitHub forks GitHub watchers


🗓️ Version History

  • v1.0.0 (2026-04-22)
    • Initial release
    • Complete STK push functionality
    • Gold and dark theme UI
    • Transaction management system

⭐ Star this repository if you find it useful! ⭐

Designed & Developed by Anthony Karanja

```

About

A premium, fully-functional Django web application for processing M-Pesa Till payments via STK Push, featuring a sleek gold-and-dark theme and real-time transaction tracking

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages