SMS Verification APIs with Node.js

Version – 1.0

Setup for SMS Verification

  1. Create a MessageCentral Account: Sign up for a Message Central account to get started. You will receive a customer ID, which you will use in your application.

  2. 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

Integration Steps

This process involves the following three significant steps:

  1. Message Central Setup
  2. Input Details in Code
  3. Send a Test OTP

a. Message Central Setup

After creating an account on Message Central, you need the following details:

  • Customer Id - You can get the customer ID from Message Central Home Console
  • Login Credentials: You’d require an email and would need to create a password.

b. Input Details in Code

To add MessageCentral details on the code find out the variable definition with name “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.

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/v3/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/v3/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}`);
});

c. Send a Test OTP

If you need to test the service without code, you can go to the free SMS verification page on the Message Central’s website.

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

1. Run the javascript file using command

node mc_verification_service.js

2. Open the Postman and set Request Method as POST and 

URL as http://localhost:3000/sendotp/<countryCode>/<phone_number>  
Here’s the port 3000, it is default and defined in code, can be changed.

Example, For Indian Phone Number URL : http://localhost:3000/sendotp/91/123****123

  • Image: Sending Otp
Image 1 : Sending Otp

3. Now You have an otp on your sms inbox. Try your own validation Otp API to validate OTP.

Open the Postman and set Request Method as GET and

URL as  http://localhost:3000/validateOtp/<countryCode>/<phone_number>/<otp>

Here’s the port 3000, it is default and defined in code, can be changed.

Example, For Indian Phone NumberURL :   http://localhost:3000/validateOtp/91/123****123/****

  • Image: Verifying Otp
Image 1 : Verifying Otp
Share this article
verification code

Boost your sales and customer engagement with Message Central now!

Message Central Logo Blue
Close Icon
Message Central Team
Hi there
How can we help you today?
WhatsApp Icon
Start Whatsapp Chat
WhatsApp Chat
WhatsApp Icon