Home Web Front-end Front-end Q&A Nodejs implements SMS verification

Nodejs implements SMS verification

May 23, 2023 pm 04:24 PM

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');
Copy after login

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}`));
Copy after login

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: '发送失败'
    });
  });
});
Copy after login

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: '验证失败'
    });
  }
});
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

How do you define routes using the <Route> component? How do you define routes using the <Route> component? Mar 21, 2025 am 11:47 AM

The article discusses defining routes in React Router using the &lt;Route&gt; component, covering props like path, component, render, children, exact, and nested routing.

What are Redux reducers? How do they update the state? What are Redux reducers? How do they update the state? Mar 21, 2025 pm 06:21 PM

Redux reducers are pure functions that update the application's state based on actions, ensuring predictability and immutability.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

What are Redux actions? How do you dispatch them? What are Redux actions? How do you dispatch them? Mar 21, 2025 pm 06:21 PM

The article discusses Redux actions, their structure, and dispatching methods, including asynchronous actions using Redux Thunk. It emphasizes best practices for managing action types to maintain scalable and maintainable applications.

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

See all articles