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

Vue conditional rendering v-if and v-show

Table of contents 1. v-if 2. Use v-if on <temp...

CSS realizes the layout method of fixed left and adaptive right

1. Floating layout 1. Let the fixed width div flo...

Native JS realizes compound motion of various motions

This article shares with you a compound motion im...

View the dependent libraries of so or executable programs under linux

View the dependent libraries of so or executable ...

Detailed explanation of the error problem of case when statement

Preface In the MySQL database, sometimes we use j...

Detailed explanation of Linux copy and paste in VMware virtual machine

1. Linux under VMware Workstation: 1. Update sour...

How to recover files accidentally deleted by rm in Linux environment

Table of contents Preface Is there any hope after...

MySQL character set garbled characters and solutions

Preface A character set is a set of symbols and e...

Getting Started Guide to MySQL Sharding

Preface Relational databases are more likely to b...

Detailed explanation of vite2.0 configuration learning (typescript version)

introduce You Yuxi’s original words. vite is simi...

19 MySQL optimization methods in database management

After MySQL database optimization, not only can t...

Optimize the storage efficiency of BLOB and TEXT columns in InnoDB tables

First, let's introduce a few key points about...