Home  >  Article  >  Web Front-end  >  Nodejs implements SMS verification

Nodejs implements SMS verification

PHPz
PHPzOriginal
2023-05-23 16:24:081131browse

With the popularity of mobile Internet, SMS verification has become an important part of many websites and mobile applications. It can verify the authenticity of the user's mobile phone number, increase the security and trust of the account, and also prevent malicious registration and fraudulent transactions. Based on Node.js technology, we can easily implement SMS verification function.

Node.js is a JavaScript running environment based on the V8 engine, which can use JavaScript to develop back-end programs. The advantage of Node.js is that it supports fast network and data processing, and its efficient event-driven mechanism can simplify asynchronous programming. Therefore, Node.js is very suitable for developing high-concurrency, high-performance back-end applications. Below, we will demonstrate how to use Node.js to implement SMS verification.

Step 1: Obtain the SDK of the SMS API service provider

To implement the SMS verification function, you first need to send the SMS verification code to the user through the interface provided by the third-party SMS API service provider. Here we take Alibaba Cloud SMS API service as an example. Alibaba Cloud SMS API provides a wealth of interfaces and SDKs to meet SMS needs in different scenarios.

Here, we need to register an account on the Alibaba Cloud official website and purchase the SMS API service. After the purchase is successful, we can obtain the corresponding SDK, Key and other developer information.

Step 2: Install and configure Node.js

Before you start using Node.js to implement the SMS verification function, you need to install and configure the Node.js environment.

Node.js can download the relevant installation program from the official website. After the installation is complete, we need to use the npm command in the command line to install common Node.js third-party modules such as express and body-parser. These modules can provide us with common functions such as HTTP server, routing and data processing, so that we can develop more conveniently. After the installation is complete, we need to write Node.js script code to implement the SMS verification function.

Step 3: Implement the SMS verification function

Next, we will implement the SMS verification function through the following steps.

1. Import third-party modules and SDK

First, we need to import the Node.js third-party module we need to use and the SDK provided by Alibaba Cloud SMS API service, as follows:

const express = require('express');
const bodyParser = require('body-parser');
const SMSClient = require('@alicloud/sms-sdk');

2. Create an Express server instance

Next, we need to use the express framework to create an HTTP server instance to handle client requests and listen to the port we specify.

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

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

app.listen(port, () => console.log(`Listening on port ${port}`));

This code first creates an express application instance and specifies the port as 3000. Then, use the body-parser module to parse the JSON-formatted data in the HTTP request.

3. Define the API interface for sending SMS verification codes

In order to be able to send SMS verification codes to users, we need to define an API interface through which to receive user requests and return SMS verification code information. The API interface is defined as follows:

app.post('/api/sendSMS', (req, res) => {
  // 获取电话号码和验证码
  const phoneNumber = req.body.phoneNumber;
  const verifyCode = generateVerifyCode();

  // 发送验证码短信
  const accessKeyId = 'your_accessKeyId';
  const secretAccessKey = 'your_secretAccessKey';
  const smsClient = new SMSClient({ accessKeyId, secretAccessKey }); 
  smsClient.sendSMS({
    PhoneNumbers: phoneNumber, // 电话号码
    SignName: 'your_sign_name', // 短信签名名称
    TemplateCode: 'your_template_code', // 短信模板CODE
    TemplateParam: JSON.stringify({ code: verifyCode }) // 验证码信息
  }).then(result => {
    console.log(result);
    res.send({
      code: 0,
      message: '发送成功'
    });
  }).catch(err => {
    console.error(err);
    res.send({
      code: -1,
      message: '发送失败'
    });
  });
});

For the above code, the description is as follows:

  • First, obtain the user's phone number phoneNumber and the randomly generated verification code verifyCode from the HTTP request parameters .
  • Then, use the SMS API service sdk provided by Alibaba Cloud to send an SMS verification code to the user's phone number.

The accessKeyId and secretAccessKey are the developer information we applied for in Alibaba Cloud, while TemplateCode and TemplateParam are the code and corresponding parameters of the SMS template we defined in the Alibaba Cloud SMS console respectively.

  • Finally, when sending a text message successfully or fails, we will return a corresponding message to the client. The Promise callback mechanism is used here to return the corresponding results when the verification code SMS is sent successfully or fails.

4. Verify the verification code entered by the user

After the user receives the SMS verification code, he or she needs to enter the verification code into our application for verification. Therefore, we need to define an API interface again to receive the verification request from the client and perform verification code verification on the server side.

app.post('/api/verifySMS', (req, res) => {
  const phoneNumber = req.body.phoneNumber; 
  const verifyCode = req.body.verifyCode; 

  // 验证码比对
  if (verifyCode === '1234') {
    res.send({
      code: 0,
      message: '验证成功'
    });
  } else {
    res.send({
      code: -1,
      message: '验证失败'
    });
  }
});

In this API interface, we first obtain the user's phone number phoneNumber and the verification code verifyCode entered by the user from the HTTP request parameters. Then, compare the verification code entered by the user with the verification code previously saved on the server side. If they are consistent, "Verification Successful" will be returned, otherwise "Verification Failure" will be returned.

To sum up, it is not difficult to implement the SMS verification function of Node.js. We only need to use the event-driven mechanism provided by Node.js and call the API interface and SDK provided by the SMS API service provider. Implement SMS verification function conveniently and quickly to improve account security and trust.

The above is the detailed content of Nodejs implements SMS verification. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn