M-Pesa Integration in a Node.js Backend: The Complete Guide
Introduction to M-Pesa Integration
M-Pesa is a popular mobile payment service used by millions of people in Africa. As a developer, integrating M-Pesa into your Node.js backend can be a game-changer for your application, enabling users to make seamless payments and transactions. In this article, we'll take a deep dive into the world of M-Pesa integration, covering everything you need to know to get started.
Setting Up a Daraja Account
Before you can start integrating M-Pesa into your Node.js backend, you'll need to set up a Daraja account. Daraja is the official API gateway for M-Pesa, and it provides a secure and reliable way to interact with the M-Pesa platform. To set up a Daraja account, follow these steps:
- Go to the Daraja website and click on the "Register" button.
- Fill out the registration form with your details, including your name, email address, and phone number.
- Verify your email address and phone number by clicking on the links sent to you by Daraja.
- Log in to your Daraja account and navigate to the "API Settings" page.
- Generate a new API key and secret by clicking on the "Generate API Key" button.
Installing Required Dependencies
To integrate M-Pesa into your Node.js backend, you'll need to install the following dependencies:
express: a popular Node.js framework for building web applicationsaxios: a library for making HTTP requestscrypto: a library for encrypting and decrypting data
You can install these dependencies using npm or yarn:
npm install express axios crypto
Configuring M-Pesa API Settings
Once you have your Daraja account set up and your dependencies installed, you can start configuring your M-Pesa API settings. You'll need to set the following environment variables:
MPESA_CONSUMER_KEY: your Daraja API keyMPESA_CONSUMER_SECRET: your Daraja API secretMPESA_ENVIRONMENT: the environment you're using (e.g. "sandbox" or "production")
You can set these environment variables in your .env file or in your code using the dotenv library.
Making M-Pesa API Requests
To make M-Pesa API requests, you'll need to use the axios library to send HTTP requests to the M-Pesa API endpoint. You'll need to authenticate your requests using the MPESA_CONSUMER_KEY and MPESA_CONSUMER_SECRET environment variables.
Here's an example of how to make a request to the M-Pesa API:
const axios = require('axios'); const crypto = require('crypto'); const mpesaConsumerKey = process.env.MPESA_CONSUMER_KEY; const mpesaConsumerSecret = process.env.MPESA_CONSUMER_SECRET; const mpesaEnvironment = process.env.MPESA_ENVIRONMENT; const timestamp = new Date().toISOString(); const password = new Buffer(`${mpesaConsumerKey}${timestamp}${mpesaConsumerSecret}`).toString('base64'); const headers = { 'Content-Type': 'application/json', 'Authorization': `Bearer ${password}`, }; const data = { 'BusinessShortCode': 'YOUR_BUSINESS_SHORT_CODE', 'LipaNaMpesaPasskey': 'YOUR_LIPA_NA_MPESA_PASSKEY', 'TransactionType': 'CustomerBuyGoodsOnline', 'Amount': '100', 'PartyA': 'YOUR_PARTY_A', 'PartyB': 'YOUR_PARTY_B', 'PhoneNumber': 'YOUR_PHONE_NUMBER', 'CallBackURL': 'YOUR_CALLBACK_URL', 'AccountReference': 'YOUR_ACCOUNT_REFERENCE', 'TransactionDesc': 'YOUR_TRANSACTION_DESCRIPTION', }; axios.post(`https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest`, data, { headers }) .then((response) => { console.log(response.data); }) .catch((error) => { console.error(error); });
Handling M-Pesa API Responses
Once you've made a request to the M-Pesa API, you'll need to handle the response. The response will contain a ResponseCode and a ResponseDescription, which you can use to determine whether the transaction was successful or not.
Here's an example of how to handle an M-Pesa API response:
axios.post(`https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest`, data, { headers }) .then((response) => { const responseCode = response.data.ResponseCode; const responseDescription = response.data.ResponseDescription; if (responseCode === '0') { console.log(`Transaction successful: ${responseDescription}`); } else { console.error(`Transaction failed: ${responseDescription}`); } }) .catch((error) => { console.error(error); });
Conclusion
Integrating M-Pesa into your Node.js backend can be a complex process, but with the right guidance, you can get started quickly and easily. By following the steps outlined in this article, you can set up a Daraja account, install required dependencies, configure M-Pesa API settings, make M-Pesa API requests, and handle M-Pesa API responses. With M-Pesa integration, you can unlock seamless mobile payments for your users and take your application to the next level.