Office Address

Mwembe Tayari, Mombasa, Kenya

Phone Number

+254792430508
+254752005904

Email Address

admin@jaytechcloud.com
jaytechcloudlimited@gmail.com

Integrating M-Pesa API with Node.js

Integrating M-Pesa API with Node.js

M-Pesa is the leading mobile money payment system in Africa. If you’re building a Node.js application that requires mobile payments, integrating the M-Pesa Daraja API is crucial.

This guide will take you through step-by-step integration, covering:

✅ Generating an M-Pesa API Access Token
✅ STK Push (Lipa na M-Pesa Online Payment)
✅ C2B (Customer to Business Payments)
✅ B2C (Business to Customer Payments)
✅ Transaction Status Inquiry
✅ Account Balance Inquiry


1. Understanding M-Pesa Daraja API

The M-Pesa Daraja API is a set of RESTful APIs provided by Safaricom that allow businesses to process mobile payments.

Key Features

FeaturePurpose
STK Push (Lipa na M-Pesa Online Payment)Allows customers to pay via M-Pesa by receiving a payment request on their phone.
C2B (Customer to Business Payments)Enables customers to send money to a business Paybill or Till number.
B2C (Business to Customer Payments)Allows a business to send money to a customer’s M-Pesa account.
Transaction Status QueryChecks if a transaction was successful.
Account Balance InquiryRetrieves the balance of a Paybill or Till number.

2. Prerequisites

Before integrating M-Pesa API into Node.js, ensure you have:

Required Accounts and Tools

✅ M-Pesa Developer Account → Register here
✅ Business Shortcode (Paybill or Till Number)
✅ M-Pesa API Credentials (Consumer Key & Secret)
✅ Node.js Installed (Latest version recommended)
✅ Express.js (For handling API requests)

Install Required Packages

npm install express axios dotenv body-parser cors

3. Getting Your M-Pesa API Credentials

To access the M-Pesa API, you need:
✅ Consumer Key
✅ Consumer Secret

How to Get API Credentials

  1. Go to Safaricom Developer Portal
  2. Log in or create an account
  3. Create a new App → Select M-Pesa API
  4. Copy your Consumer Key and Secret

4. Generating M-Pesa API Access Token

Before making any API calls, you must first authenticate using an Access Token.

Step 1: Create mpesa.js file

const axios = require("axios");
const dotenv = require("dotenv");
dotenv.config();

const generateAccessToken = async () => {
  const consumerKey = process.env.MPESA_CONSUMER_KEY;
  const consumerSecret = process.env.MPESA_CONSUMER_SECRET;
  const auth = Buffer.from(`${consumerKey}:${consumerSecret}`).toString("base64");

  try {
    const response = await axios.get(
      "https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials",
      {
        headers: {
          Authorization: `Basic ${auth}`,
        },
      }
    );
    return response.data.access_token;
  } catch (error) {
    console.error("Error generating access token:", error);
  }
};

module.exports = generateAccessToken;

✅ The access token expires in 60 minutes.
✅ Use this token in the Authorization Header for all API calls.


5. Implementing STK Push (Lipa na M-Pesa Online Payment)

What is STK Push?

STK Push allows customers to pay businesses via M-Pesa by receiving a payment request on their phone.

Step 1: Sending STK Push Request

const express = require("express");
const axios = require("axios");
const generateAccessToken = require("./mpesa");
const dotenv = require("dotenv");

dotenv.config();
const app = express();
app.use(express.json());

app.post("/stkpush", async (req, res) => {
  const accessToken = await generateAccessToken();

  const businessShortcode = process.env.BUSINESS_SHORTCODE;
  const passkey = process.env.MPESA_PASSKEY;
  const phoneNumber = req.body.phone;
  const amount = req.body.amount;
  const callbackUrl = "https://yourdomain.com/callback";

  const timestamp = new Date()
    .toISOString()
    .replace(/[-:T.]/g, "")
    .slice(0, 14);

  const password = Buffer.from(`${businessShortcode}${passkey}${timestamp}`).toString("base64");

  const payload = {
    BusinessShortCode: businessShortcode,
    Password: password,
    Timestamp: timestamp,
    TransactionType: "CustomerPayBillOnline",
    Amount: amount,
    PartyA: phoneNumber,
    PartyB: businessShortcode,
    PhoneNumber: phoneNumber,
    CallBackURL: callbackUrl,
    AccountReference: "TestPayment",
    TransactionDesc: "Payment for goods",
  };

  try {
    const response = await axios.post(
      "https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest",
      payload,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );
    res.status(200).json(response.data);
  } catch (error) {
    console.error("Error sending STK Push:", error);
    res.status(500).json({ error: "Error sending STK Push" });
  }
});

app.listen(3000, () => {
  console.log("Server running on port 3000");
});

✅ ResponseCode "0" means request sent successfully.
✅ The customer receives an M-Pesa prompt to enter their PIN.


6. Handling STK Push Callback Responses

After the payment, M-Pesa sends a callback response to the CallBackURL.

Step 1: Set Up an Endpoint to Handle Callbacks

app.post("/callback", (req, res) => {
  console.log("Callback Response:", req.body);
  res.status(200).json({ message: "Callback received" });
});

✅ M-Pesa sends a JSON response with payment status.
✅ Store successful transactions in your database.


7. Implementing C2B (Customer to Business Payments)

C2B allows customers to send money to your Paybill or Till Number.

Register C2B URLs

app.post("/registerC2B", async (req, res) => {
  const accessToken = await generateAccessToken();

  const payload = {
    ShortCode: process.env.BUSINESS_SHORTCODE,
    ResponseType: "Completed",
    ConfirmationURL: "https://yourdomain.com/confirmation",
    ValidationURL: "https://yourdomain.com/validation",
  };

  try {
    const response = await axios.post(
      "https://sandbox.safaricom.co.ke/mpesa/c2b/v1/registerurl",
      payload,
      {
        headers: {
          Authorization: `Bearer ${accessToken}`,
        },
      }
    );
    res.status(200).json(response.data);
  } catch (error) {
    res.status(500).json({ error: "Error registering C2B URL" });
  }
});

✅ Customers can now send money to your Paybill/Till Number.
✅ You’ll receive real-time notifications.

🎉 Congratulations! You’ve successfully integrated M-Pesa API into Node.js.

💬 Questions? Comment Below! 🚀

Josphat Okutu
Author

Josphat Okutu

Leave a comment

Your email address will not be published. Required fields are marked *

Subscribe to our newsletter.

Never miss out a moment with JayTech Cloud. Subscribe to our newsletter today to get our updates an offers.

shape