DEV Community

AlinaJ
AlinaJ

Posted on

SMS Verification APIs with Node.js

What Is SMS Verification?

SMS verification is a method of authentication system that enables users to receive a shortcode on their mobile phones, which is used to verify their identity when logging into an application.
SMS is among the most widespread types of multi-factor authentication (MFA), requiring no apps or digital keys, making it independent of a specific ecosystem and helping to streamline various user workflows in applications.

It provides enhanced security because a hacker would need to have the user's username, password, and physical access to their phone, which likely has its own authentication, to log into an application. Although, now a days, OTP SMS is still being hacked and hence it is very necessary to keep in mind the OTP SMS fraud prevention methods.

Image description

Benefits of SMS Verification

Despite alternatives like FIDO2 and mobile authenticator applications gaining popularity, SMS verification remains widely used due to its benefits:

a. Secure: Increases security significantly as it makes it hard for malicious actors to access user accounts.

b. Ease of use: Almost everyone has access to a mobile phone today, making SMS verification a popular choice with no additional costs on software or hardware devices.

c. Convenience: Reduces the burden of remembering passwords by sending a unique code to the user's mobile for verification.

Setup for SMS Verification with Message Central

Message Central is a CPaaS solution with a suite of products including OTP SMS APIs, SMS APIs and WhatsApp marketing platform.

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

b. 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:

a. Message Central Details

b. Adding Message Central Details in Code

c. Send a Test Otp for verification

Message Central Details

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.

Adding MessageCentral 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/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});
});

Send a Test Otp Sms for Verification

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//

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 description

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///
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 description

Top comments (2)

Collapse
 
abebur profile image
Abebur • Edited

Remember when sending a message meant waiting days for a letter to arrive? Yeah, neither does SMSLive. It's as if the platform invented time travel for messages. One second, you're hitting send, and the next, your customer on the other side of the globe already has your message in their inbox. Whether you're managing a flash sale or sending crucial updates, the real-time tracking feature lets you watch it all unfold like a sci-fi flick. And thanks to its bulk SMS capability, you can reach entire continents at once, no DeLorean required. With SMSLive, you can even personalize your sender ID – because who says time travelers can’t have a touch of class? So, why stick to old-fashioned methods when you can leap into the future? Get on board here smslive.pro. It’s like having a time machine for your business communication – except, you know, totally real and way more practical.

Collapse
 
neospy profile image
NeoSpy

For integrating SMS verification with Node.js, I’ve had great success using the Twilio API. It’s straightforward and well-documented, making it easy to set up SMS verification for user authentication. Plus, their support is excellent if you run into any issues. Definitely worth considering for your project!