Example code for implementing verification code login in SMS API in Node

Example code for implementing verification code login in SMS API in Node

1. Node server setup + database connection

The operation here is relatively simple and easy to understand. You can refer to: Quick setup of node server

2. Use of SMS API

For SMS API, here we take Alibaba Cloud's SMS service as an example (any platform with SMS service can use it)

2.1 Log in to the platform to configure parameters

1. Enter the SMS console and configure the SMS format to be sent. If there is no signature, you need to apply for a signature before operation.

insert image description here

2. Click View API Demo to enter the configured API; select Node.js

insert image description here

2.2 Use the generated API in the project

Code comments are detailed

const Core = require('@alicloud/pop-core'); //cwen calls Ali SMS module (need to be installed first)
//cwen configures the Alibaba SMS service API let client = new Core({
 accessKeyId: '<accessKeyId>', // Need to apply first (steps below)
 accessKeySecret: '<accessSecret>', // Need to apply first (steps below)
 endpoint: 'https://dysmsapi.aliyuncs.com', //No need to change apiVersion: '2017-05-25' //No need to change });
//cwen request method let requestOption = {
  method: 'POST'
};

//# Generate a random four-digit number to simulate the verification code function rander(max, min) {
  return Math.floor(Math.random() * (max - min)) + min
}
//# Store mobile phone number + verification code (for easy verification)
var loginInfo = [];
//# Verify whether the phone number has sent a verification code let validate = (phone) => {
  return loginInfo.some(item => item.phone === phone)
}
//# Verify that the verification code is consistent let validateCode = (phone, code) => {
  return loginInfo.some(item => (item.phone === phone && item.code == code))
}

//cwen uses Alibaba Cloud API to send SMS verification (verification code login)
let sendLoginCroeCode = async(req, res) => {
  let { phone } = req.body;
  let randCode = rander(1000, 9999);
  var params = {
      "RegionId": "cn-hangzhou",
      "PhoneNumbers": phone, // client phone number "SignName": "小陈应用ya", // signature "TemplateCode": "SMS_197625305", // template, used to send text messages "TemplateParam": JSON.stringify({ 'code': randCode }) // specify the verification code to be sent (here the rander function is used as an example)
    }
     //# Before sending the verification code, determine whether the mobile phone number has been registered if (await isRegister(phone)) { // This is a database operation (can be ignored)
    client.request('SendSms', params, requestOption).then((result) => {
      if (result.Code == 'OK') {
        res.send({
          status: 200,
          msg: 'Sent successfully'
        });
        loginInfo.push({
          phone: phone,
          code: randCode
        });
        console.log(randCode)
      } else {
        res.send({
          status: 400,
          msg: 'Send failed'
        })
      }
    })
  } else {
    res.send({
      status: 400,
      msg: 'This phone number is not registered'
    })
  }
}

//# Verification code login interface let phoneCodeLogin = async(req, res) => {
  let { phone, code } = req.body;
  if (validate(phone)) { //Judge whether the mobile phone number has sent a verification codeif (validateCode(phone, code)) { //Judge whether the verification code matches the mobile phone numberlet user = await isFirstLogin(phone); //This is a database operation to obtain user information (can be ignored)
      res.send({
        status: 200,
        msg: 'Login successful',
        data: user[0]
      })
      loginInfo = []; // Login is successful, clear the array immediately to avoid failure to send verification code again} else {
      res.send({
        status: 400,
        msg: 'Verification code error'
      })
    }
  } else {
    res.send({
      status: 400,
      msg: 'Verification code not obtained'
    })
  }
}

// Note: Remember to expose the interface at the end

Note : accessKeyId、accessKeySecret need to be applied for before use

insert image description here

3. Log in using the interface

Here we take the Postman interface debugging tool as an example, and the mobile phone number is the mobile phone number registered in the database

Request verification code

insert image description here

Receive verification code on mobile phone

insert image description here

Verification code login

insert image description here

This is the end of this article about the sample code for implementing verification code login with SMS API in Node. For more relevant Node SMS verification code login content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Ali greater than SMS verification code node koa2 implementation code (latest)
  • How to access Ali Dayu SMS verification code with nodejs
  • Nodejs sends Post request function (Send SMS verification code example)
  • Nodejs implements SMS verification code function

<<:  Solution to MySQL unable to read table error (MySQL 1018 error)

>>:  A detailed introduction to Linux file permissions

Recommend

HTML data submission post_PowerNode Java Academy

The HTTP request methods specified by the HTTP/1....

The difference between html form submission action and url jump to actiond

The action of the form is different from the URL j...

Solution to Incorrect string value in MySQL

Many friends will report the following error when...

JavaScript realizes the drag effect of modal box

Here is a case of modal box dragging. The functio...

Summary of Linux file directory management commands

touch Command It has two functions: one is to upd...

Use of Linux ifconfig command

1. Command Introduction The ifconfig (configure a...

In-depth understanding of Vue's method of generating QR codes using vue-qr

Table of contents npm download step (1) Import (2...

How to view the IP address of Linux in VMware virtual machine

1. First, double-click the vmware icon on the com...

CentOS 6 uses Docker to deploy redis master-slave database operation example

This article describes how to use docker to deplo...

A universal nginx interface to implement reverse proxy configuration

1. What is a proxy server? Proxy server, when the...

Whitespace processing in HTML/CSS and how to preserve whitespace in the page

Whitespace rules in HTML In HTML, multiple spaces...

Web front-end performance optimization

Web front-end optimization best practices: conten...