
1. Setting Up the Environment
Goal: Prepare a development environment tailored to the backend framework you choose.
Steps:
-
Install a Backend Framework:
- For PHP: Use a framework like Laravel for ease of development and MVC architecture.
- Install Laravel:
composer create-project laravel/laravel my-project
- Install Laravel:
- For Node.js: Use Express.js to build APIs.
- Install Express:
mkdir my-project && cd my-project npm init -y npm install express
- Install Express:
- For Python: Use Flask or Django for robust API building.
- Install Flask:
pip install flask
- Install Django:
pip install django
- Install Flask:
- For PHP: Use a framework like Laravel for ease of development and MVC architecture.
-
Dependencies and Tools:
- Ensure you have tools like Postman (for API testing) and Ngrok (for exposing local servers).
- Install required libraries or modules for handling API requests.
- PHP: Guzzle HTTP Client (
composer require guzzlehttp/guzzle
) - Node.js: Axios or Node-Fetch (
npm install axios
) - Python: Requests library (
pip install requests
)
- PHP: Guzzle HTTP Client (
2. Folder Structure
Goal: Maintain organized and scalable code by structuring project files systematically.
Example Folder Structure:
project-root/
├── controllers/ # Contains API logic
├── routes/ # Defines API routes
├── config/ # Stores configuration files (e.g., API keys, environment variables)
├── utils/ # Helper functions or utilities
├── tests/ # Unit and integration tests
└── main entry file # app.js (Node.js), index.php (PHP), etc.
Benefits:
- Easy navigation and debugging.
- Separation of concerns ensures better maintainability.
3. Setting Up Routes
Goal: Define endpoints for handling specific API operations like token generation and transaction initiation.
Implementation Example:
-
In PHP (Laravel):
Route::get('/generate-token', [MpesaController::class, 'generateToken']); Route::post('/initiate-transaction', [MpesaController::class, 'initiateTransaction']);
-
In Node.js (Express):
const express = require('express'); const app = express(); app.get('/generate-token', (req, res) => { // Call token generation logic res.send("Token Generated"); }); app.post('/initiate-transaction', (req, res) => { // Call transaction logic res.send("Transaction Initiated"); }); app.listen(3000, () => console.log('Server running on port 3000'));
-
In Python (Flask):
from flask import Flask app = Flask(__name__) @app.route('/generate-token', methods=['GET']) def generate_token(): return "Token Generated" @app.route('/initiate-transaction', methods=['POST']) def initiate_transaction(): return "Transaction Initiated" if __name__ == "__main__": app.run(debug=True)
4. Configuration Files
Goal: Securely store sensitive information like consumer keys, secrets, and callback URLs.
Best Practices:
- Use environment variables to store sensitive data.
- PHP: Use
.env
file withdotenv
package.MPESA_CONSUMER_KEY=your_consumer_key MPESA_CONSUMER_SECRET=your_consumer_secret CALLBACK_URL=https://yourdomain.com/callback
- Node.js: Use
dotenv
package.MPESA_CONSUMER_KEY=your_consumer_key MPESA_CONSUMER_SECRET=your_consumer_secret CALLBACK_URL=https://yourdomain.com/callback
Code to load:
require('dotenv').config(); const consumerKey = process.env.MPESA_CONSUMER_KEY;
- Python: Use
os
ordotenv
library.import os from dotenv import load_dotenv load_dotenv() consumer_key = os.getenv("MPESA_CONSUMER_KEY")
- PHP: Use
5. Testing the Backend
Goal: Verify that the backend endpoints work as expected before integrating them with Mpesa APIs.
Steps:
-
Install Postman: Use Postman to send requests to your backend.
- GET Request: Test the
/generate-token
endpoint to verify token generation logic. - POST Request: Test
/initiate-transaction
with required parameters like amount and phone number.
- GET Request: Test the
-
Use Ngrok: Expose your local server to the internet to test callbacks from Mpesa.
- Install Ngrok:
npm install -g ngrok
or download it from Ngrok’s website. - Start Ngrok:
ngrok http 3000
- Use the generated URL (e.g.,
https://abcd1234.ngrok.io
) as your callback URL in Mpesa configurations.
- Install Ngrok:
-
Debug Errors:
- Use logs in your code to troubleshoot any issues.
- PHP: Use
Log::info("Message")
. - Node.js: Use
console.log("Message")
. - Python: Use
print("Message")
.
- PHP: Use
- Use logs in your code to troubleshoot any issues.