当前位置:网站首页>[node] node+ SMS API to realize verification code login

[node] node+ SMS API to realize verification code login

2022-06-22 09:20:00 Jdoit CW

Content

node The server login interface uses real SMS to verify login

1. node Server setup + Database connection

The operation here is simple and easy to understand , May refer to :node Server quick build

2. SMS api Use

For SMS api , Here to Take Alibaba cloud's SMS service as an example ( Any platform with SMS service can be used )

2.1 Log in to the platform to configure parameters

1. Enter the SMS console , Configure the SMS format to be sent , If there is no signature , You need to apply for signature
 Insert picture description here

2. Click to see API Demo Enter configuration generated api; Choose Node.js

 Insert picture description here

2.2 According to the generated api Used in projects

Code comments are detailed

const Core = require('@alicloud/pop-core'); //cwen  Call Alibaba SMS module ( It needs to be installed first )
//cwen  For Alibaba SMS service API To configure 
let client = new Core({
    
  accessKeyId: '<accessKeyId>', //  You need to apply first ( The procedure is described below )
  accessKeySecret: '<accessSecret>', //  You need to apply first ( The procedure is described below )
  endpoint: 'https://dysmsapi.aliyuncs.com', // No need to change 
  apiVersion: '2017-05-25' // No need to change 
});
//cwen  Request mode 
let requestOption = {
    
    method: 'POST'
};

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

//cwen  Use alicloud api 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": " Xiao Chen application ya", // Signature 
            "TemplateCode": "SMS_197625305", // Templates , Used to send text messages 
            "TemplateParam": JSON.stringify({
     'code': randCode }) // Specify the verification code to send ( Here to rander  Function as an example )
        }
          //#  Before sending the verification code, judge whether the mobile phone number has been registered 
    if (await isRegister(phone)) {
      //  Here is the database operation ( Negligible )
        client.request('SendSms', params, requestOption).then((result) => {
    
            if (result.Code == 'OK') {
    
                res.send({
    
                    status: 200,
                    msg: ' Send successfully '
                });
                loginInfo.push({
    
                    phone: phone,
                    code: randCode
                });
                console.log(randCode)
            } else {
    
                res.send({
    
                    status: 400,
                    msg: ' fail in send '
                })
            }
        })
    } else {
    
        res.send({
    
            status: 400,
            msg: ' The 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 verification code 
        if (validateCode(phone, code)) {
     //  Judge whether the verification code matches the mobile phone number 
            let user = await isFirstLogin(phone); //  Here is the database operation , Get user information ( Negligible )
            res.send({
    
                status: 200,
                msg: ' Login successful ',
                data: user[0]
            })
            loginInfo = []; //  Login successful , Empty the array immediately , So that the verification code cannot be sent again 
        } else {
    
            res.send({
    
                status: 400,
                msg: ' Verification code error '
            })
        }
    } else {
    
        res.send({
    
            status: 400,
            msg: ' Verification code not obtained '
        })
    }
}

//  Be careful : Finally, remember to expose the interface 

Be careful accessKeyId、accessKeySecret You need to apply before using

 Insert picture description here

3. Use the interface to log in

Here to Postman Take the interface debugging tool as an example , The mobile number is the mobile number registered in the database

  1. Request to send verification code

 Insert picture description here

  1. The mobile phone receives the verification code

 Insert picture description here

  1. Verification code login

 Insert picture description here

cheer up , Every one of you on the road

原网站

版权声明
本文为[Jdoit CW]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220844301375.html