Revolutionize Your Business Payments with Easy Mpesa Integration in Kenya

With over 40 million registered users, M-PESA has become a popular payment method in Kenya, leading many businesses to integrate the mobile money service into their operations for greater convenience and accessibility for customers. In the integration guide below provided by Robert a senior software engineer at https://deeptechlabs.co.ke/ we will use Node.js, a JavaScript runtime, and MongoDB, a NoSQL database management system.

Step 1: Register for an Mpesa API account

To use the Mpesa API, you’ll need to register for an account on the Safaricom developer portal and create an app. Once you’ve done this, you’ll get access to an API key and a secret key that you’ll use to make requests to the API.

Step 2: Install necessary packages

In your Node.js project, you will need to install the axios package, which we will use to make HTTP requests to the Mpesa API. You can install axios by running the following command in your terminal:

npm install axios
Step 3: Create a function to generate authentication token

To make requests to the Mpesa API, you’ll need to include an authentication token in the request headers. The authentication token is generated using your API key and secret key. Here’s an example of a function that you can use to generate the authentication token:

const axios = require('axios');
const base64 = require('base-64');

const generateAccessToken = async () => {
  const consumer_key = 'YOUR_API_KEY';
  const consumer_secret = 'YOUR_SECRET_KEY';

  const credentials = `${consumer_key}:${consumer_secret}`;
  const encodedCredentials = base64.encode(credentials);

  const url = 'https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials';

  try {
    const response = await axios.get(url, {
      headers: {
        'Authorization': `Basic ${encodedCredentials}`
      }
    });
    return response.data.access_token;
  } catch (error) {
    console.log(error.response.data);
    return null;
  }
};

In this example, we use the base-64 package to encode the API key and secret key. We then make a GET request to the https://sandbox.safaricom.co.ke/oauth/v1/generate endpoint, passing the encoded credentials in the Authorization header. The response from this endpoint contains the authentication token, which we extract and return.

Note that we’re using the Safaricom sandbox environment in this example. When you’re ready to go live, you’ll need to use the production environment instead.

Step 4: Make requests to the Mpesa API

Once you have the authentication token, you can make requests to the Mpesa API to perform various transactions. Here’s an example of how you can make a request to the C2B Simulate endpoint to initiate a payment:

const initiatePayment = async () => {
  const access_token = await generateAccessToken();

  const url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate';

  const data = {
    'ShortCode': 'YOUR_SHORTCODE',
    'CommandID': 'CustomerPayBillOnline',
    'Amount': '10',
    'Msisdn': '254708374149',
    'BillRefNumber': 'TestAPI'
  };

  const response = await axios.post(url, data, {
    headers: {
      'Authorization': `Bearer ${access_token}`,
      'Content-Type': 'application/json'
    }
  });

  console.log(response.data);
};

In this example, we first generate the authentication token using the function we created earlier. We then define the data that we want to send in the request body. This includes the shortcode that identifies your Mpesa account, the CommandID which is set to CustomerPayBillOnline, the amount to be paid, the phone number of the person making the payment, and a unique reference number.

We then make a POST request to the https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate endpoint, passing the authentication token in the Authorization header and the data in the request body. The response from the endpoint contains the status of the payment.

Step 5: Integrate Mpesa API with MongoDB

To integrate Mpesa API with MongoDB, you can create a collection in your database to store the details of each transaction that you make using the API. Here’s an example of how you can create a transactions collection and save the details of a transaction to the collection:

const MongoClient = require('mongodb').MongoClient;

const saveTransaction = async (transaction) => {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

  try {
    await client.connect();

    const database = client.db('mydb');
    const collection = database.collection('transactions');

    const result = await collection.insertOne(transaction);
    console.log(`Transaction saved with ID: ${result.insertedId}`);
  } catch (error) {
    console.log(error);
  } finally {
    await client.close();
  }
};

// Example usage
const transaction = {
  'ShortCode': 'YOUR_SHORTCODE',
  'CommandID': 'CustomerPayBillOnline',
  'Amount': '10',
  'Msisdn': '254708374149',
  'BillRefNumber': 'TestAPI'
};

saveTransaction(transaction);

In this example, we use the MongoClient to connect to the MongoDB instance running on localhost:27017. We then connect to the mydb database and the transactions collection. We use the insertOne method to insert the transaction into the collection, and log the ID of the inserted document to the console.

Note that you will need to modify the uri variable to match the URI of your MongoDB instance.

With these steps, you can easily integrate Mpesa API with your Node.js and MongoDB application. You can use the same approach to integrate other APIs with your application, as long as they have HTTP endpoints that you can call using an HTTP client library like axios.

Step 6: Error Handling

Error handling is an important aspect of any application that interacts with external APIs. In the case of Mpesa API, errors can occur due to various reasons such as incorrect authentication credentials, invalid input data, or system errors.

To handle errors in our Node.js application, we can use try-catch blocks to catch and handle errors that occur during API calls or database operations. We can also use the axios error handling mechanism to handle HTTP errors returned by the Mpesa API.

Here’s an example of how you can handle errors when making an API call to Mpesa API:

const axios = require('axios');

const makePayment = async (transaction) => {
  const consumerKey = 'YOUR_CONSUMER_KEY';
  const consumerSecret = 'YOUR_CONSUMER_SECRET';
  const auth = `Basic ${Buffer.from(`${consumerKey}:${consumerSecret}`).toString('base64')}`;

  const url = 'https://sandbox.safaricom.co.ke/mpesa/c2b/v1/simulate';

  try {
    const response = await axios.post(url, transaction, {
      headers: {
        'Authorization': auth,
        'Content-Type': 'application/json'
      }
    });

    console.log(response.data);
  } catch (error) {
    console.log(error.response.data);
  }
};

// Example usage
const transaction = {
  'ShortCode': 'YOUR_SHORTCODE',
  'CommandID': 'CustomerPayBillOnline',
  'Amount': '10',
  'Msisdn': '254708374149',
  'BillRefNumber': 'TestAPI'
};

makePayment(transaction);

In this example, we use the try-catch block to catch any errors that occur during the API call. If an error occurs, we log the error message to the console using the console.log function.

We also use the axios error handling mechanism to catch HTTP errors returned by the API. If an HTTP error occurs, we log the error message returned by the API to the console.

In this tutorial, we have learned how to integrate Mpesa API with a Node.js and MongoDB application. We have covered the basics of the Mpesa API, how to authenticate with the API, how to make API calls, how to handle errors, and how to store transaction data in a MongoDB database.

By following these steps, you can easily integrate Mpesa API with your Node.js and MongoDB application, and start accepting mobile payments from your customers.

Step 7: Storing Transaction Data in MongoDB

Now that we have successfully made a payment using the Mpesa API, the next step is to store the transaction data in a MongoDB database. We will use the mongoose package to interact with MongoDB.

First, let’s install the mongoose package using NPM:

npm install mongoose

Next, let’s create a Transaction model in models/transaction.js file:

const mongoose = require('mongoose');

const transactionSchema = new mongoose.Schema({
  transactionType: {
    type: String,
    required: true
  },
  transactionId: {
    type: String,
    required: true
  },
  transactionTime: {
    type: Date,
    required: true
  },
  amount: {
    type: Number,
    required: true
  },
  phoneNumber: {
    type: String,
    required: true
  },
  status: {
    type: String,
    required: true
  },
  resultCode: {
    type: Number,
    required: true
  },
  resultDesc: {
    type: String,
    required: true
  },
});

const Transaction = mongoose.model('Transaction', transactionSchema);

module.exports = Transaction;

This model defines the schema for storing transaction data in the database. We have defined the following fields:

  • transactionType: the type of transaction (e.g., C2B, B2C, B2B, etc.)
  • transactionId: the transaction ID returned by the Mpesa API
  • transactionTime: the time the transaction was made
  • amount: the amount of the transaction
  • phoneNumber: the phone number of the customer making the transaction
  • status: the status of the transaction (e.g., Completed, Failed, Cancelled, etc.)
  • resultCode: the result code returned by the Mpesa API
  • resultDesc: the result description returned by the Mpesa API

Next, let’s update our makePayment function in mpesa.js file to save the transaction data in the MongoDB database:

const Transaction = require('../models/transaction');

const makePayment = async (transaction) => {
  // ...

  try {
    const response = await axios.post(url, transaction, {
      headers: {
        'Authorization': auth,
        'Content-Type': 'application/json'
      }
    });

    const { TransactionType, TransID, TransTime, Amount, MSISDN, ResultDesc, ResultCode } = response.data;
    const transactionData = {
      transactionType: TransactionType,
      transactionId: TransID,
      transactionTime: new Date(TransTime),
      amount: Amount,
      phoneNumber: MSISDN,
      status: ResultDesc,
      resultCode: ResultCode,
      resultDesc: ResultDesc,
    };

    const savedTransaction = await Transaction.create(transactionData);
    console.log('Transaction saved to database:', savedTransaction);
  } catch (error) {
    console.log(error.response.data);
  }
};

In this updated function, we create a new Transaction object using the transaction data returned by the API. We then use the create method of the Transaction model to save the transaction data in the MongoDB database.

Finally, we log a message to the console indicating that the transaction has been saved to the database.

Conclusion

In this final step, we learned how to store transaction data in a MongoDB database using the mongoose package. We updated our makePayment function to save transaction data to the database using the create method of the Transaction model.

By following the steps outlined in this guide, you should now have a basic understanding of how to integrate the Mpesa API with a Node.js and MongoDB application.

Of course, there are many other features of the Mpesa API that we did not cover in this guide, such as checking transaction status, reversing transactions, and more. However, the concepts and techniques we covered here should provide a solid foundation for building more complex Mpesa-powered applications.

As you continue to work with Node.js and MongoDB, you will likely encounter new challenges and opportunities to learn and grow. Remember to stay curious, experiment, and don’t be afraid to ask for help when you need it.

To summarize, here are the key steps we covered in this guide:

  1. Set up a new Node.js project and install the required packages (axios, dotenv, and express).
  2. Create a .env file to store the Mpesa API credentials.
  3. Set up an express server and create a POST route for making payments.
  4. Create a mpesa.js module to handle API interactions.
  5. Use the axios package to make a payment request to the Mpesa API.
  6. Parse the response data and log the results to the console.
  7. Use the mongoose package to store transaction data in a MongoDB database.

With these steps in mind, you should be well-equipped to start building your own Mpesa-powered applications using Node.js and MongoDB.

Thanks, good luck and happy coding!

 

Leave a Reply

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