OTP Verification System using MessageCentral in NodeJS

One-time password verification adds an extra layer of security to your digital accounts. It works by sending a unique password to your phone via text message. You enter this password to prove it’s really you.

MessageCentral is an OTP (One-Time Password) service provider that makes it easy for businesses to add OTP verification to their apps or systems. They offer an API that allows seamless integration, meaning any type of application can quickly incorporate OTP verification for enhanced security.

Prerequisites:

Create a MessageCentral Account

  • Sign up for a MessageCentral account to get started. You will receive a customer ID, which you will use in your application.

Install Required Packages:

  • Ensure you have Node.js installed on your machine. Create a new directory for your project and initialize a new Node.js project. Install the required packages using npm.
npm install express request

What is OTP verification system?

OTP (One-Time Password) verification is like having a secret code that changes every time you need to prove who you are online. It’s a way to make sure it’s really you accessing your accounts or doing transactions. Basically, you get a special code sent to your phone via text message or an app. You enter this code to show that you’re the rightful user. It’s simple and adds an extra layer of security to your digital life.

Steps to Integrate OTP Verification System

Step 1: Message Central Setup

  • After creating an account on MessageCentral, you need the following details:
  • Customer Id: You can get the customer ID from MessageCentral Home Console.
  • Login Credentials: You’d require an email and would need to create a password.

Step 2: Project Setup

  • There should only one Javascript file. That JavaScript code handles full integration to MessageCentral SMS OTP API’s.

Step 3: Credentials in Code

To add MessageCentral details to the code, find out the variable definition with names like “customerId”, “email”, and “password”:

const customerId = '[Your Customer ID]';
const email = '[Your Email]';
const password = '[Your Password]';

To add your credentials in javascript code, you need to create a javascript file i.e mc_verication_service.js: And add provided code into this file.

Node
//mc_verication_service.js

const request = require("request");
const express = require("express");

const app = express();
const port = 3000;

const baseURL = "https://cpaas.messagecentral.com";
const customerId = "[Your Customer ID]";
const email = "[Your Email]";
const password = "[Your Password]";

let verificationId;

const generateAuthToken = async () => {
    const base64String = Buffer.from(password).toString("base64");

    const url = `${baseURL}/auth/v1/authentication/token?
    country=IN&customerId=${customerId}&email=${email}
    &key=${base64String}&scope=NEW`;

    const options = {
        url: url,
        headers: {
            accept: "*/*",
        },
    };

    return new Promise((resolve, reject) => {
        request(options, (error, response, body) => {
            if (error) {
                console.error("Error generating auth token:", error);
                reject(error);
                return;
            }

            console.log("Auth Token:", body);
            authToken = JSON.parse(body).token;

            resolve(authToken);
        });
    });
};

const sendOtp = async (countryCode, mobileNumber) => {
    const url = `${baseURL}/verification/v2/verification/send?
    countryCode=${countryCode}&customerId=${customerId}&
    flowType=SMS&mobileNumber=${mobileNumber}`;

    const options = {
        url: url,
        method: "POST",
        json: true,
        headers: {
            accept: "*/*",
            authToken: authToken,
        },
    };

    return new Promise((resolve, reject) => {
        request(options, (error, response, body) => {
            if (error) {
                console.error("Error generating auth token:", error);
                reject(error);
                return;
            }
            console.log("Request :", options);
            console.log("Body :", body);
            verificationId = body.data.verificationId;
            resolve(body);
        });
    });
};

const velidateOtp = async (otpCode, countryCode, mobileNumber) => {
    const url = `${baseURL}/verification/v2/verification/validateOtp?
    countryCode=${countryCode}&mobileNumber=${mobileNumber}&
    verificationId=${verificationId}&customerId=${customerId}&code=${otpCode}`;

    const options = {
        url: url,
        method: "GET",
        json: true,
        headers: {
            accept: "*/*",
            authToken: authToken,
        },
    };

    return new Promise((resolve, reject) => {
        request(options, (error, response, body) => {
            if (error) {
                console.error("Error generating auth token:", error);
                reject(error);
                return;
            }
            console.log("Request :", options);
            console.log("Body :", body);

            resolve(body);
        });
    });
};

app.post("/sendotp/:countryCode/:mobileNumber", async (req, res) => {
    const { countryCode, mobileNumber } = req.params;

    const authToken = await generateAuthToken();

    try {
        body = await sendOtp(countryCode, mobileNumber);

        if (body.data.responseCode == 200 && body.data.errorMessage == null) {
            res.status(200).send("Otp sent! Successfully");
        } else {
            res.status(400).send("Bad Request ${body.data.errorMessage}");
        }
    } catch (error) {
        console.error("Error sending OTP:", error);
        const s = error;
        res.status(500).send(s);
    }
});

app.get(
    "/validateOtp/:countryCode/:mobileNumber/:otpCode",
    async (req, res) => {
        const { countryCode, mobileNumber, otpCode } = req.params;

        const authToken = await generateAuthToken();

        try {
            body = await velidateOtp(otpCode, countryCode, mobileNumber);

            if (
                body.data.verificationStatus == "VERIFICATION_COMPLETED" &&
                body.data.errorMessage == null
            ) {
                res.status(200).send("Otp verification Done! ");
            } else {
                res.status(400).send("Bad Request : ${body.data.errorMessage}");
            }
        } catch (error) {
            console.error("Error verifying OTP:", error);
            const s = error;
            res.status(500).send(s);
        }
    }
);

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});

Step 4: Send a Test OTP

If you need to test the service without code, you can go to the free SMS verification page on the MessageCentral website.

To ensure that the integration is successful, send a test OTP SMS as follows:

  • Run the JavaScript file using the command node mc_verification_service.js.
  • Open Postman and set Request Method as POST and URL as http://localhost:3000/sendotp/<countryCode>/<phone_number>. Example: http://localhost:3000/sendotp/91/123****123.

sending otp

Once you have received the OTP in your SMS inbox, you can test your own validation OTP API to validate the OTP:

  • Open Postman and set the Request Method as GET and URL as http://localhost:3000/validateOtp/<countryCode>/<phone_number>/<otp>. Example for an Indian Phone Number: http://localhost:3000/validateOtp/91/123****123/****.

validate otp