How to quickly add a phone number verification form to your website

Integrating mobile number verification into your web application is one of the most effective methods of authenticating users on your platform. This step will help significantly reduce the presence of spam mailings, automated bots and fraudulent activities on the site. Adding a mobile number verification form when logging into a website protects user accounts from various threats, such as password guessing, phishing attacks, and other malicious activities. Thus, even if the account password is revealed, attackers will not be able to access it without going through the verification procedure through a mobile number.

My name is Anastasia Ivanova, and I am engaged in technical documentation in the company i-Digital. In this article, I will talk about how you can integrate a mobile number verification form on your website using our widget.

The phone verification widget from i-digital direct relieves you of the need to independently send a verification code to users’ mobile numbers, check the sent and entered code, monitor the duration of the session and take care of the security of sending the code. To use it, you will need to make a simple integration in HTML code, as well as set up a closed interaction between the server part of your application and the i-digital direct server.

What you will need

First of all, register with Personal account i-digital direct. After registration, set up the phone verification widget and create an API key to manage it. To do this, follow the detailed instructions from the article “Setting up a widget in your personal account

In this article, we will implement an application server on NodeJS framework based Express. We will also install additional modules: body-parser for processing data from incoming HTTP requests, library axios for making outgoing HTTP requests and template engine nunjucks for JavaScript.

Initializing the Application and Installing Dependencies

Before you get started, make sure Node.js is installed on your computer. Node.js can be downloaded from official website. Node.js comes bundled with the npm package manager, which is designed for installing additional modules.

Run the npm init command in a terminal to create a new NodeJS project. Optionally fill in the parameters of your application that the system will request (name, brief description, author information, etc.).

Completing the procedure will result in the formation of a package.json configuration in your project, which contains all the specified information about your application (entered during the initialization process) and a list of installed packages.

Add to your project the libraries indicated in the “What you will need” by running in the terminal:

npm install -s express axios body-parser nunjucks

Once the library installation process is complete, the package.json file will display a list of installed dependencies:

Express.js server development

Create a basic Hello World application using Express. Instructions for creating one can be found at Express official website.

Include previously installed modules in your project:

// Подключение модулей
const bodyParser = require("body-parser");
const axios = require('axios');
const nunjucks = require('nunjucks');

Configure your application to handle incoming HTTP requests using body-parser as follows:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded( {extended: false} ))

Run the application using the node {file_name}.js command in the terminal. After starting, you will see a notification about the application running on the port you specified in the terminal. Go to address http://localhost:{port}/to see the welcome message from the application:

Client setup

We will store client pages in a separate views folder. Create a corresponding folder in the project directory. Create the following HTML files in the new folder:

  • index – home page where the user indicates his mobile number;

  • widget – page with a number confirmation widget from i-digital direct;

  • success – the final page with a message about the successful completion of the number verification.

The structure of the application will be as follows:

Next, we will look step by step at the implementation of the client and server parts of the application.

Application Implementation

Client: home page – index.html

Add form and input elements to your home page for entering a mobile number and a button that initiates a POST request with the entered number to the server URL /sendPhoneNumber. After receiving the number, the server uses it when rendering the page with the number confirmation widget.

Paste the HTML code below into your index.html file:

<!-- Форма для ввода номера телефона и отправки POST-запроса на точку доступа сервера /sendPhoneNumber -->
<form method="post" action="sendPhoneNumber">
  <label>Номер мобильного телефона в формате 79*********</label><br /><br />
  <input name="phoneNumber" type="tel" />
  <button>Подтвердить номер телефона</button>
</form>

Server: processing the request to the home page

Specify the use of the nunjucks template engine to render HTML pages from the views directory we created in the previous step. Write the following line of code to the server's index.js file:

nunjucks.configure('views', { express: app });

Adapt the app.get handler for the home page:

// Настройка ответа на запросы к домашней странице (рендер index.html файла)
app.get('/', (req, res) => {
  res.render('index.html');
});

This way the server will display the contents of index.html when the home page is visited.

Start the server and go to the address http://localhost:{port}/to check that the mobile phone number entry form appears on the home page.

Server: processing data from the form with number

When the user enters the number and clicks the “Confirm” button, the form will send a POST request to /sendPhoneNumber. The server will accept this request and display a widget page widget.html with the phone number value entered on the home page. Add the following lines to index.js:

app.post('/sendPhoneNumber', (req, res) => {
  const phoneNumber = req.body.phoneNumber; // номер телефона формы
  res.render('widget.html', {
    phoneNumber: phoneNumber,
  }); // передаем номер на страницу с виджетом
});

Client: number confirmation widget page – widget.html

This page will host the i-Digital Direct widget. To do this, first of all, connect the css and js files from the i-Digital CDN to the of the page:

<link rel="stylesheet" href="https://cdn.direct.i-dgtl.ru/VerifyWidget.css" />
<script src="https://cdn.direct.i-dgtl.ru/VerifyWidget.umd.min.js"></script>

Add a DOM element into which the widget will be embedded by its id:

<div id="widget"></div>

Next, you need to initialize the widget using the following code template:

window.VerifyWidget.mount('#ELEMENT_ID', {
   destination: 'CLIENT_PHONE_NUMBER',
   widgetId: 'YOUR_WIDGET_ID',
   captchaSiteKey: 'YOUR_CAPTCHA_SITEKEY'
}, sendAuthKeyFunc, onSuccessFunc)

You can see a description of the parameters in our article “Phone verification on your website” Replace the following parameter values ​​in the template:

  • ELEMENT_ID – id of the element that was created above (widget).

  • CLIENT_PHONE_NUMBER is a variable into which the number that the user entered on the previous page is substituted.

  • YOUR_WIDGET_ID – the id of the widget that you will receive after it creation according to these instructions.

  • YOUR_CAPTCHA_SITEKEY – the secret key of the captcha service, which you will receive after creating it. Detailed instructions can be found in the article “Using captcha

The widget initialization code looks like this:

window.VerifyWidget.mount('#widget', {
    destination: '{{ phoneNumber }}', // в переменную phoneNumber подставится номер пользователя
    widgetId: 'widget_id',
    captchaSiteKey: 'captcha_site_key',
  }, sendAuthKeyFunc, onSuccessFunc );

Now we need to implement the callback functions sendAuthKeyFunc and onSuccessFunc.

When the user selects the desired method of receiving the verification code, the widget executes the sendAuthKeyFunc function, which passes the unique identifier for sending the code (key). You need to pass this ID to the backend of your application.

To do this, add a fetch request to the address /sendAuthKeyFunc, which will pass the key when calling sendAuthKeyFunc:

const sendAuthKeyFunc = (key) => {
   const payload = {
     key,
   };
   return fetch('/sendAuthKeyFunc', {
     method: 'POST',
     headers: {
       'Content-Type': 'application/json',
     },
     body: JSON.stringify(payload),
   });
 };

When the user enters the correct verification code, the widget calls the onSuccessFunc function. When executing this function, you can also pass the key identifier to the application backend to check the validity of the number verification.

The key identifier is not passed to the onSuccessFunc function, as is the case with the sendAuthKeyFunc function. To pass the key value when executing onSuccessFunc, you can create a variable in advance and set the key value in it when executing the sendAuthKeyFunc function. For example:

messageKey = ''; // переменная для будущего сохранение значения key

const sendAuthKeyFunc = (key) => {
  messageKey = key;
  // здесь функция отправки POST-запроса на серверную часть
};

To pass the key to the server side of the application when executing the onSuccessFunc function, you need to add a fetch request to the /checkVerification address in the function.

After executing the request, the client must receive the verification result from the server. If the verification status is confirmed (CONFIRMED), the application can show the user the pages available after confirmation. Since the client needs to wait for a response from the server after a fetch request before showing hidden pages, write an asynchronous function:

 const onSuccessFunc = async () => {
  const payload = {
    key: messageKey,
  };
   
  // Отправляем POST-запрос на сервер и ждем, пока ответ не запишется в переменную response
  const response = await fetch('/checkVerification', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

  // Преобразовывает ответ от сервера в JSON формат
  const verificationInfo = await response.json();

  // Проверяем, что статус проверки кода подтвержден, убираем      виджет и показываем сраницу успешного подтверждения
  if (verificationInfo.status == 'CONFIRMED') {
    window.VerifyWidget.unmount('widget');
    window.location = '/success';
  }
 };

The widget and function initialization code can be written in separate files and imported into the widget.html file. But for ease of implementation, we will write the JavaScript code under the HTML code in the

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *