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. STK Push Overview

Objective: Understand how the STK Push process facilitates seamless payment initiation.

  • What is an STK Push?
    STK Push (Sim Toolkit Push) is a payment request sent to a user’s phone via Mpesa, prompting them to enter their PIN to approve the transaction.

  • Why Use STK Push?
    It provides a secure and user-friendly way to collect payments, especially in e-commerce, donations, or service payments.

  • Workflow:

    1. The system sends a payment request to the user’s phone.
    2. The user confirms the transaction by entering their PIN.
    3. The response indicates the success or failure of the request.

2. API Endpoint

Objective: Learn the endpoint used to initiate STK Push transactions.

  • STK Push Endpoint:

    https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest
    
  • HTTP Method:
    Use the POST method to send data.

3. Required Parameters

Objective: Familiarize yourself with the necessary parameters for an STK Push request.

Below is a list of critical parameters and their roles:

  • BusinessShortCode:
    A unique short code (till number) provided by Mpesa for your business.
    Example: 174379 (for testing).

  • Password:
    A base64-encoded string of the BusinessShortCode, Passkey, and Timestamp.

    • Formula:
      Password = Base64Encode(BusinessShortCode + Passkey + Timestamp)
      
    • Example in PHP:
      $password = base64_encode($businessShortCode . $passkey . $timestamp);
      
  • Timestamp:
    A string representing the current time in the format YYYYMMDDHHMMSS.

    • Example in Node.js:
      const timestamp = new Date().toISOString().replace(/[-:T.]/g, '').slice(0, 14);
      
  • Amount:
    The transaction amount in Kenyan Shillings (KSh).

  • PartyA:
    The phone number of the user initiating the payment.

  • PartyB:
    The payee’s business number (e.g., till or paybill number).

  • PhoneNumber:
    The same as PartyA—the phone number to receive the STK Push request.

  • CallbackURL:
    A URL where Mpesa will send the transaction response.

  • TransactionDesc:
    A brief description of the transaction (e.g., “Payment for Order #123”).

4. Code Implementation

Objective: Implement the STK Push request in code.

  • Example in PHP:
    function initiateSTKPush($accessToken, $shortCode, $passkey, $phoneNumber, $amount, $callbackUrl) {
        $timestamp = date('YmdHis');
        $password = base64_encode($shortCode . $passkey . $timestamp);
    
        $url = "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest";
    
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
            "Authorization: Bearer $accessToken",
            "Content-Type: application/json"
        ]);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
        $data = [
            "BusinessShortCode" => $shortCode,
            "Password" => $password,
            "Timestamp" => $timestamp,
            "TransactionType" => "CustomerPayBillOnline",
            "Amount" => $amount,
            "PartyA" => $phoneNumber,
            "PartyB" => $shortCode,
            "PhoneNumber" => $phoneNumber,
            "CallBackURL" => $callbackUrl,
            "AccountReference" => "Order123",
            "TransactionDesc" => "Payment for Order123"
        ];
    
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    
        $response = curl_exec($curl);
        curl_close($curl);
    
        return $response;
    }
    

5. Handling API Response

Objective: Parse and handle the response from the STK Push API.

  • Successful Request:
    A successful request will return a JSON response similar to the following:

    {
        "MerchantRequestID": "12345",
        "CheckoutRequestID": "67890",
        "ResponseCode": "0",
        "ResponseDescription": "Success. Request accepted for processing",
        "CustomerMessage": "Success. Request accepted for processing"
    }
    
    • ResponseCode: "0" indicates success.
  • Error Scenarios:

    • Invalid Phone Number: Check the format and ensure it starts with 254.
    • Insufficient Balance: The user may not have enough funds for the transaction.
  • Log Responses:
    Store both successful and failed responses for troubleshooting and analytics.

6. Testing STK Push

Objective: Verify the STK Push functionality in a test environment.

  • Using Postman:

    1. Create a new POST request.
    2. Set the URL to the STK Push endpoint.
    3. Add headers:
      • Authorization: Bearer AccessToken
      • Content-Type: application/json
    4. Add the required parameters to the body in JSON format.
    5. Click Send and monitor the response.
  • On the Phone:

    • If successful, you will receive an Mpesa pop-up on the test number to approve the payment.