Course Content
Building Your First Mpesa Integration
This topic focuses on guiding you through the process of building a functional Mpesa integration from scratch. You will learn how to set up a backend for handling API requests, generate secure access tokens for authentication, and implement an STK Push transaction to facilitate payments. By the end of this topic, you will have a working example of Mpesa integration.
0/3
C2B and B2C Integrations
In this topic, learners will explore the core concepts of integrating Mpesa's Customer-to-Business (C2B) and Business-to-Customer (B2C) payment functionalities. The lessons will cover configuring C2B payments to enable customers to pay businesses and using B2C for disbursing funds to customers. Additionally, the topic will explain how to implement real-time transaction status updates to ensure seamless payment tracking and reconciliation.
0/3
Testing and Debugging
This topic focuses on ensuring the reliability and correctness of Mpesa integrations by testing in the sandbox environment, debugging using logs and tools like Postman, and eventually transitioning to the production environment. By the end of this topic, learners will be equipped with practical knowledge of testing and debugging their integration effectively.
0/3
Security and Best Practices
This topic covers the critical aspects of securing your Mpesa integration by properly managing API keys and tokens, handling errors in a way that improves the user experience, and complying with Mpesa’s integration guidelines. Following these practices ensures that your integration is secure, reliable, and in line with best practices, minimizing the risk of fraud and ensuring smooth operations.
0/3
Real-World Application
This topic explores how Mpesa can be seamlessly integrated into real-world applications, particularly e-commerce platforms. It covers integrating payment systems, customizing user experiences to enhance payment flows, and using analytics for business insights. By the end of this topic, learners will understand how to leverage Mpesa for creating smoother and more efficient payment processes, as well as tracking transactions for actionable insights.
0/3
Build a Payment Gateway with Mpesa
In this project, learners will apply the skills acquired throughout the course to build a functional payment gateway integrated with Mpesa. The project will walk through the entire process, from backend setup and API integration to handling transactions and user feedback. By the end of this topic, learners will have developed a working payment gateway and be ready to present their projects for review and feedback.
0/3
Introduction to Mpesa Integration
Gain an understanding of Mpesa’s role in facilitating mobile payments. Learn about its features, real-world applications, and benefits in businesses. This module covers the prerequisites for starting your Mpesa integration journey.
0/2
Setting Up The Environment
In this topic, you learned how to set up the environment for Mpesa integration. This includes registering on the Mpesa Daraja Portal, acquiring API credentials, and using tools like Postman and Ngrok for development and testing. You also set up a local server, configured callback URLs, and simulated transactions in the sandbox environment. Finally, you prepared for production by understanding the approval process and transitioning to live operations. These steps form the foundation for successfully integrating Mpesa APIs into your application.
0/4
Understanding Mpesa APIs
This topic provides an overview of the various Mpesa APIs available for integration. You will learn about the key API services that facilitate mobile money transactions, such as the STK Push, C2B, B2C, and Account Balance APIs. Understanding how each API works will help you design robust and efficient payment systems, and ensure seamless transactions between businesses and customers.
0/3
Mpesa Integration – Daraja API :Crash Course
Applying the skills acquired throughout the course, the video below will guide you to build a functional payment gateway integrated with Mpesa. The project will walk through the entire process, from backend setup and API integration to handling transactions and user feedback. By the end of this topic, you will have developed a working payment gateway and be ready to present your projects for review and feedback.
0/2
M-Pesa Integration MasterClass
About Lesson

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
    • For Node.js: Use Express.js to build APIs.
      • Install Express:
        mkdir my-project && cd my-project
        npm init -y
        npm install express
        
    • For Python: Use Flask or Django for robust API building.
      • Install Flask: pip install flask
      • Install Django: pip install django
  • 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)

 

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 with dotenv 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 or dotenv library.
      import os
      from dotenv import load_dotenv
      
      load_dotenv()
      consumer_key = os.getenv("MPESA_CONSUMER_KEY")
      

 

 

5. Testing the Backend

Goal: Verify that the backend endpoints work as expected before integrating them with Mpesa APIs.

Steps:

  1. 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.
  2. 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.
  3. 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").