Published on

Getting Started With Mpesa Daraja API

Authors

Getting Started With Mpesa Daraja API

In this post, we are going to develop a simple API to connect with MPESA API using nodejs and express.

Prerequisite:

  • Safaricom developer account > check out the Safaricom Developer portal
  • Ngrok > Download here

    In order to test our application we need to expose it to the internet and the easiest way to do that is by using ngrok service

  • Postman > Download here

To get started, we will create a folder called mpesa and initialize it with some default npm settings.

  $> mkdir mpesa && cd mpesa
  $> npm init -y
  $> npm install express dotenv
  $> touch app.js

Your package.json should look like below

package.json

{
  "name": "mpesa",
  "version": "1.0.0",
  "description": "",
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2"
  }
}

app.js

import express from "express";

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

const port = process.env.PORT || 5000;


app.post("/api/mpesa", (req, res) => {
  let message = {
    ResponseCode: "00000000",
    ResponseDesc: "success",
  };

  // respond to safaricom servers with a success message
  res.json(message);

});

app.listen(port, () => {
console.log(`App listening on port ${port}`)
});

Now head over to safaricom developer portal and create a sample test application. copy the following from the applicationyou created.

.env

SAFARICOM_CONSUMER_SECRET=paste_secret_here
SAFARICOM_CONSUMER_KEY=paste_key_here
PASS_KEY=paste_passkey_here
BUSINESS_SHORT_CODE=paste_shortcode_here