How to set up registration and authentication in Drupal using SMS API
Registration confirmation and authentication via SMS API is an effective tool on many sites. This feature helps reduce the number of spam accounts, improve user experience, and provide valuable data for targeted campaigns. Let's figure out how to implement such confirmation through MTS Exolve on sites with Drupal.
Benefits of SMS confirmation
Let's take a closer look at the benefits of such confirmation.
Increased security
Two-factor authentication (2FA) makes the user's experience on the site safer. The SMS code serves as an additional layer of security, reducing the risk of unauthorized access, even if an attacker has gained access to the password. Sending a verification code to a phone number helps verify that the user owns the number, reducing the likelihood of creating fake accounts. But there are many subtleties about them colleagues have already spoken.
Improving user experience
This is a simple and fast way to verify your identity. Most users are familiar with the process of receiving and entering SMS codes, which makes the registration and authentication process intuitive. Users receive notifications in real time.
Reducing the number of false registrations
This is a good way to filter out spam accounts: requiring SMS verification helps reduce the number of automated registrations and spam accounts, which improves the quality of the user database.
Restoring access
SMS can be used to send password recovery codes, making it easier for users to regain access to their accounts.
Marketing Opportunities
This is a convenient way to collect marketing data. A phone number verified via SMS is a valuable resource. This allows marketers to send targeted offers and notifications, increasing user engagement.
In addition, SMS allows you to quickly and reliably inform users about important events, promotions and news.
Security Compliance
In some industries, such as finance or healthcare, identity verification via SMS may be a requirement to meet security and data protection standards.
Audit and tracking
Integration with SMS API allows you to keep logs of sent codes and confirmations, making it easier to audit security and track suspicious activity.
Obviously, all these benefits are worth implementing them yourself. Moreover, without using registration and authentication via SMS, it is unlikely that you will be able to create a commercially successful website.
How to make registration confirmation and authentication via SMS on CMS Drupal
Integration of SMS confirmation has two limitations: the SMS gateway used and the site engine. In this article we will look at the option for Drupal and the API platform MTS Exolve.
Installing modules
Let's start by installing the SMS Framework module:
Go to the module page SMS Framework on Drupal.org and download it. If desired, you can use Composer:
```bash
composer require drupal/smsframework
```
We install a module for the SMS API of the provider, in our case MTS Exolve. Here you will have to tinker. Before you begin, install and configure Drupal 9 or 10.
Step 1. Preparing to work with the MTS Exolve API
Register on the MTS Exolve website and get your API credentials.
Step 2. Creating a custom module for integration with the MTS Exolve API.
Let's create the module structure:
Go to the `modules/custom` directory of your Drupal site.
Create a new folder for your module, for example `mts_sms`.
Inside the `mts_sms` folder, create a file `mts_sms.info.yml` with the following content:
```yaml
name: 'MTS SMS Integration'
type: module
description: 'Module for SMS registration confirmation using MTS Exolve API.'
core_version_requirement: ^9 || ^10
package: Custom
dependencies:
- drupal/user
Create a module file `mts_sms.module`.
Inside the `mts_sms` folder, create a file `mts_sms.module` and add the following code:
<?php
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;
/**
* Implements hook_form_alter() to modify user registration form.
*/
function mts_sms_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Add a phone number field to the registration form.
$form['phone_number'] = [
'#type' => 'tel',
'#title' => t('Phone Number'),
'#required' => TRUE,
];
// Add a submit handler to the registration form.
$form['#submit'][] = 'mts_sms_user_register_form_submit';
}
/**
* Submit handler for user registration form.
*/
function mts_sms_user_register_form_submit($form, FormStateInterface $form_state) {
// Get the phone number from the form.
$phone_number = $form_state->getValue('phone_number');
// Generate a random confirmation code.
$confirmation_code = rand(100000, 999999);
// Save the confirmation code to the user's session.
\Drupal::service('user.private_tempstore')->get('mts_sms')->set('confirmation_code', $confirmation_code);
// Send the confirmation code via SMS.
$api_key = 'YOUR_API_KEY';
$api_secret="YOUR_API_SECRET";
$sender="YourSenderName";
$message = "Your confirmation code is $confirmation_code";
mts_sms_send_sms($api_key, $api_secret, $phone_number, $sender, $message);
}
/**
* Function to send SMS via MTS Exolve API.
*/
function mts_sms_send_sms($api_key, $api_secret, $phone_number, $sender, $message) {
$url="https://api.mts.exolve.ru/sms/send";
$data = [
'api_key' => $api_key,
'api_secret' => $api_secret,
'to' => $phone_number,
'sender' => $sender,
'message' => $message,
];
$options = [
'http' => [
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
],
];
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) {
\Drupal::logger('mts_sms')->error('Failed to send SMS.');
} else {
\Drupal::logger('mts_sms')->notice('SMS sent successfully.');
}
}
Create a file `mts_sms_confirm.module` to process input and check the confirmation code:
<?php
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Implements a form to confirm the registration code.
*/
class ConfirmCodeForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'confirm_code_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['confirmation_code'] = [
'#type' => 'textfield',
'#title' => $this->t('Confirmation Code'),
'#required' => TRUE,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Confirm'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$entered_code = $form_state->getValue('confirmation_code');
$stored_code = \Drupal::service('user.private_tempstore')->get('mts_sms')->get('confirmation_code');
if ($entered_code == $stored_code) {
\Drupal::messenger()->addMessage($this->t('Registration confirmed successfully.'));
// Complete the user registration process here.
} else {
\Drupal::messenger()->addError($this->t('Invalid confirmation code.'));
}
}
}
We register the route to confirm the code, for which we create the file `mts_sms.routing.yml` and add the following code:
```yaml
confirm_code.form:
path: '/confirm-code'
defaults:
_form: '\Drupal\mts_sms\Form\ConfirmCodeForm'
_title: 'Confirm Registration Code'
requirements:
_permission: 'access content'
Step 3. Activation and configuration of the module
We activate and configure the module. To activate, go to the Drupal administrative panel and activate the `MTS SMS Integration` module. Next, go to the registration page and register a new user. All that remains is to check how it works: send an SMS with a confirmation code to the entered number, go to the `/confirm-code` page, enter the received code and see the result.
Please note that the instructions for integrating with the SMS API in Drupal are extremely general. It is very likely that additional customization and refinement will be required depending on the specifics of your project and your requirements.
Install the module for two-factor authentication: go to the module page [TFA (Two-factor Authentication) ] and just download it.
All necessary modules are installed.
Setting up SMS Framework
In the Drupal administrative panel, we activate the installed modules `SMS Framework`, `SMS MTS Exolve` and `TFA`. After this we configure SMS Gateway. Go to `Configuration` -> `SMS Framework` -> `Gateways`; click `Add Gateway` and select MTS Exolve, after which we enter the data that we were given when registering on the API platform.
Setting up two-factor authentication (2FA)
To configure the TFA module, go to `Configuration` -> `People` -> `Two-factor Authentication`. In the `Plugin settings` section, select `SMS` as the authentication method and configure sending SMS using the previously configured SMS Gateway.
Setting up registration confirmation
To set up registration confirmation, you will again have to tinker a little. Everything will look something like this:
We are making a custom module to confirm registration. Create a folder for your module in `modules/custom` and create a file called `registration_confirm.info.yml`:
```yaml
name: 'Registration Confirmation'
type: module
description: 'Module for SMS registration confirmation.'
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
- drupal/smsframework
We create a module file `registration_confirm.module`, in which we will process user registration and SMS sending:
<?php
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\User;
use Drupal\sms\Message\SmsMessage;
/**
* Implements hook_form_alter() to modify user registration form.
*/
function registration_confirm_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {
// Add a phone number field to the registration form.
$form['phone_number'] = [
'#type' => 'tel',
'#title' => t('Phone Number'),
'#required' => TRUE,
];
// Add a submit handler to the registration form.
$form['#submit'][] = 'registration_confirm_user_register_form_submit';
}
/**
* Submit handler for user registration form.
*/
function registration_confirm_user_register_form_submit($form, FormStateInterface $form_state) {
// Get the phone number from the form.
$phone_number = $form_state->getValue('phone_number');
// Generate a random confirmation code.
$confirmation_code = rand(100000, 999999);
// Save the confirmation code to the user's session.
\Drupal::service('user.private_tempstore')->get('registration_confirm')->set('confirmation_code', $confirmation_code);
// Send the confirmation code via SMS.
$message = new SmsMessage();
$message->setRecipient($phone_number);
$message->setBody(t('Your confirmation code is @code', ['@code' => $confirmation_code]));
\Drupal::service('smsprovider')->sendMessage($message);
}
To process code confirmation, we create a form for entering the code and a handler for checking the entered code.
Completion and testing
Go to the administrative panel and activate the `Registration Confirmation` module. All that remains is to register a new user and make sure that the SMS is sent correctly and the user can confirm registration using the code.
Benefits of Confirming Registration and User Authentication via API
There are now more than enough SMS gateways, but the option with an API platform provides many advantages.
Simplified management and scalability
Such platforms offer user-friendly and comprehensive control panels, making it easy to administer and monitor SMS messages. With an API, it is easier to scale the service as the number of users increases.
Advanced functionality
There are often provisions for various use cases, such as two-factor authentication (2FA), phone number verification, notifications, etc. In addition, message templates and personalization can be easily customized.
Reporting and analytics
The platforms provide detailed reports on message delivery, which helps track performance and identify problems. The archive contains the message history and an event log.
Technical support and documentation
For example, MTS Exolve has clear, intelligible documentation with technical support.
The choice between integration with an API platform and a regular SMS gateway depends on the specific needs and resources of your project. An API platform is suitable for more complex and scalable projects where advanced features and security are important, while a regular SMS gateway may be suitable for smaller, less complex applications on a budget.
I hope this article will help you with setting up the integration. Please keep in mind that the code provided must be adjusted to meet the requirements of your site, CMS and provider.
Author: Roman Andreev