This is a step by step tutorial on how to implement Africa's Talking (AT) client to business (C2B) payment API to your Node.js(express) application. Check out the whole project from GitHub.

Prerequisite

  1. Visual Studio Code or any IDE of your choice.
  2. Basic knowledge of Node.js.
  3. Africa's talking sandbox test environment.
  4. Postman.

How to get started.

Login to your AT account and  generate API key. To use the AT Payment API you need an API key that is unique and generated from your personal account. If you don't have an account create one here.

Once you are logged in, click on the sandbox button. It will redirect you to AT dashboard. Click on settings, then API key. You will see the Enter password text box, input your account password and click on generate. Make sure you save your API key, since you wont be able to see it on subsequent visits.

Create a new file and name it .env . This is where we will store our environment variables. In this case the apikey, username and port. Make sure you use the current generated apikey, use sandbox as the apps username. Use "sandbox" for development in the test environment.

Initialize node using npm init or yarn init.  After initializing node you should be able to see node modules and package.json file in your project root directory.

We will need to add some dependencies for some modules to work. Copy either of the two commands to the console in your root directory. npm install express africastalking body-parser dotenv or yarn add express africastalking body-parser dotenv. To handle HTTP POST request in express.js version 4 and above we install body-parser middleware. body-parser extracts the entire body portion of an incoming request stream and exposes it on req.body.  dotenv loads environment variables from the .env file.

apiKey="your api key"
username="your username"
port="your port"

We will be using ES6+ syntax and therefore we will have to add babel. To learn more about babel click here. npm i @babel/core babel-cli @babel/preset-env babel-watch --save-dev or yarn add @babel/core babel-cli @babel/preset-env babel-watch --dev.

Now we will create the C2B payment function. Create a file in your root directory and name it mobile-payment.js. Copy the below code to your file.

import express from "express";
import dotenv from "dotenv";
const router = express.Router();

dotenv.config();

const credentials = {
    apiKey: process.env.apiKey,
    username: process.env.username
  };
  
  // Get payments service
  const AfricasTalking = require('africastalking')(credentials);
  
  // Initialize the SDK
  const payments = AfricasTalking.PAYMENTS;
  
  // Initiate the payment
  router.post("/",(req,res)=>{
        const options = {
          //Set the product name
          productName: req.body.productName,
          phoneNumber: req.body.phoneNumber,
          currencyCode: req.body.currencyCode,
          amount: req.body.amount,
        };
        payments.mobileCheckout(options)
        .then (result =>{
            console.log(result);  
            res.json(result)
        }).catch (err => {
          console.log(err);
          res.json(err.toString());
        });         
  })
  
  export default router;

dotenv.config() method reads the environment variables. const credentials authenticates our application. const AfricasTalking  imports the Africa's talking module and const payment  accesses the AT payment  API .The router.post payment route sends a request(req) to the AT payment API. As soon as the request is sent and the data given in the body is accurate, it returns the full response object with res.json(response) as well as logs the response to the console with console.log(response).  In case the request fails, an error message is returned using res.json(error.toString()). The toString() method converts the error to a string. Finally we export our route using  export default router.

Create another file and name it app.js in the same directory(root directory). Copy the following code to this file;

import express from "express";
import 'babel-polyfill';
import router from "./mobile-payment";
import dotenv from "dotenv";
import bodyParser, { json } from "body-parser";

dotenv.config();

const app = express();
const port = process.env.port || 3000;

app.listen(port, ()=> console.log(`Listening from ${port}`));

app.use(bodyParser.json());

app.use("/v3", router);

Note when importing your mobile payment file the number of dots depend on where you saved your file. We then set our live server to run on the port set on the .env file or port 3000. Our application listens from the AT API passing the whole body through bodyParser.json()

Add the following scripts to your package.json

"build": "babel app.js --out-dir build",
"start": "babel-watch app.js"

Your package.json file should look like this;

{
  "name": "payment",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "babel app.js --out-dir build",
    "start": "babel-watch app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "africastalking": "^0.5.2",
    "body-parser": "^1.19.0",
    "dotenv": "^8.2.0",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.1",
    "@babel/preset-env": "^7.12.1",
    "babel-cli": "^6.26.0",
    "babel-watch": "^7.0.0",
    "make-runnable": "^1.3.8"
  }
}

Now lets run our application. Run npm start in your root terminal. You should be able to see in your console Listening from port ${your Port}.

Open postman, fill in the body as you can see below and run your application. You should receive payment  notification in your sandbox environment. Note, no notification will be sent to your mobile phone.

Body in JSON
Response
Payment confirmation in your sand box environment

There you go. We have used the AT C2B payment API successfully.

Happy coding!!

You've successfully subscribed to Decoded For Devs
Welcome back! You've successfully signed in.
Great! You've successfully signed up.
Your link has expired
Success! Your account is fully activated, you now have access to all content.