An elegant way to handle WeChat applet authorization login

An elegant way to handle WeChat applet authorization login

Preface

When the WeChat mini program project involves obtaining user information and implementing user login, you can easily obtain the WeChat user identity through the login capability officially provided by WeChat and quickly establish a user system within the mini program. The official document only provides how to call the authorized login. If you just copy the document as is to write the code, it will inevitably cause poor code maintainability. Therefore, this article focuses on how to handle the authorized login of the WeChat applet more elegantly.

Basic process of authorized login

The above picture is the basic flowchart of authorized login provided by the official website of WeChat Mini Program. Here I will only explain the process from the perspective of front-end development.

  • Get the temporary login credential code through wx.login().
  • The code is passed to the server by calling the interface provided by the server, and then the server returns the openid and session_key to the front-end. This means that the authorized login has been successfully completed. As for the purpose of openid and sesstion_key, we will explain it later.

After understanding the general login process, you can start writing code. Because the API interface calls provided by WeChat are not conducive to code maintenance, I used promise to encapsulate the process (if you don’t understand, you can refer to the ES6 document for a detailed introduction). The advantage of this is that you can chain the interface calls in the future, and you can also combine async/await (ES6 syntax) to synchronize the asynchronous interface.

Encapsulation of get/post interfaces

Create a service folder in the root directory to store the code related to the interface. Create a myRequest.js file in the service folder and encapsulate the get/post request of the applet. The code is as follows:

//Get request encapsulation (jump page judgment)
//Global variables can be obtained through the global function getApp. Global data can be set in app.js in the root directory. let app=getApp();
const myGet = (url, data)=>{
 return new Promise((resolve, reject)=>{
 wx.request({
  url: `${app.globalData.HTTP}${url}`,
  data:data,
  method:"GET",
  //This authorization is the value containing openid and session_key information header: { 'authorization': app.globalData.authorization}, //Get the user information in the global variable and put it into the request header success:(res)=>{
  if (res.data.code == 409) {
   //409 means the user is not logged in, so it is forced to jump to the written login page wx.navigateTo({
   url: '../login/login'
   })
  } else{
   resolve(res.data);
  }
  },
  fail:(res)=>{
  reject();
  }
 })
 })
}
//post request encapsulation (jump page judgment)
const myPost = (url, data) => {
 return new Promise((resolve, reject) => {
 wx.request({
  url: `${app.globalData.HTTP}${url}`,
  data: data,
  method: "POST",
  header: { 'authorization': app.globalData.authorization},
  success: (res) => {
  if (res.data.code == 409){
   wx.navigateTo({
   url: '../login/login'
   })
  }else{
   resolve(res.data);
  }
  
  },
  fail: (res) => {
  reject();
  }
 })
 })
}
module.exports = {
 myGet,
 myPost,
}

The global variable configuration app.js code is as follows (note that the global variable data will be initialized after refreshing the page or re-entering the mini program, and the current data status cannot be permanently saved):

//app.js
App({
 onLaunch: function() {
 //Here you can write some code that needs to be executed for project initialization according to the actual needs of the project},
 globalData: {
 HTTP: "https://shop.yamecent.com/",
 //After we obtain the openid and session_key, we will store them in the authorization of the applet memory, so that the data will not be lost unless the applet authorization is deleted: wx.getStorageSync('authorization') || "", //Get the authorization stored in the applet memory
 }
})

Authorization login interface encapsulation

This part of the encapsulation will use async/await to process the asynchronous interface synchronously. If you don’t understand, you can refer to the ES6 document description. Create login.js in the service folder. The code is as follows:

const myRequest = require('./myRequest.js');
const app = getApp();
const HTTP = app.globalData.HTTP;
//WeChat login interface to obtain code encapsulation const myLogin=()=>{
 return new Promise((resolve, reject)=>{
 wx.login({
  success:(res)=>{
  resolve(res.code);
  },
  fail:(res)=>{
  reject(res.errMsg);
  console.log("WeChat login and code acquisition failed");
  }
 })
 })
}
//Get openid and session_key interface encapsulation const getUserMsg=(myUrl,myData)=>{
 return new Promise((resolve,reject)=>{
 wx.request({
  url: myUrl,
  method: "POST",
  data: myData,
  success:(res)=>{
  if(res.data.code==500){
   //Get failed wx.showToast({
   title: res.data.msg,
   icon: 'none',
   duration: 2000,
   mask:true,
   })
   resolve(500); //Return 500 if failed   
  }else{
   resolve(res.data.data);
  }  
  },
  fail:(res)=>{
  reject(res.data.msg);
  console.log("Failed to obtain openid and session_key interfaces");  
  }
 })
 })
}

//Encapsulate storage (Note: the storage process here is asynchronous)
const mySetStorage=(key,val)=>{
 return new Promise((resolve, reject) => {
 wx.setStorage({
  key: key,
  data: val,
  success: () => {
  resolve(true);
  },
  fail: () => {
  reject(false);
  }
 })
 }) 
}

//Encapsulate storage const myGetStorage=(key)=>{
 return new Promise((resolve,reject)=>{
 wx.getStorage({
  key: 'key',
  success: (res)=>{
  resolve(res.data);
  },
  fail:()=>{
  reject("Failed to obtain storage");
  }
 })
 })
}


//Authorization method encapsulation //sendData is the user information obtained through the authorization button. Here it is passed as a parameter to the background to save the user's information //cb is the function to be executed after the authorization login is successful. The specific function depends on the project requirements and may not be required const myAuthorize = (sendData,cb="") => {
 async function accredit() {
 wx.showLoading({
  title: 'Certification in progress',
  mask:true
 })
 let code = await myLogin(); //WeChat login to get code interface sendData.code=code;
 let author = await getUserMsg(`${HTTP}auth`, sendData); //Get the background openid sesstion_key interface wx.hideLoading();
 if(author==500){
  return;
 }
 await mySetStorage("authorization", author.Authorization); //Save to memory, enter the applet to get and store in app.globalData app.globalData.authorization = author.Authorization;
 typeof cb == "function" && cb(author); //Login status parameters needed for callback //Other business logic can be added here, such as the number of shopping carts of tabbar users, etc. wx.showToast({
  title: 'Successful Authorization',
  icon: 'success',
  duration: 2000,
  mask: true
 });    

 
 }
 accredit();
}

module.exports = {
 myAuthorize,
 mySetStorage,
 myGetStorage
}

After the authorization login is packaged, let's see how to use it in the project. Since the WeChat applet authorization can only be triggered by a button, use the button component and specify the open-type as the getUserInfo type to obtain the user's basic information. The login.wxml code is as follows:

<button class='btn' open-type="getUserInfo" bindgetuserinfo='gotoLogin'>Log in now</button>

The login.js code is as follows:

// pages/login/login.js
const myRequest = require('../../common/script/myRequest.js');
const login = require('../../common/script/login.js');
const app = getApp();
const HTTP = app.globalData.HTTP;
Page({

 /**
 * Initial data of the page */
 data: {
 
 },
 gotoLogin: function (e) {
 let sendOjb={};//Used to store user informationif (e.detail.errMsg == "getUserInfo:ok"){
  sendOjb = { avatar: e.detail.userInfo.avatarUrl,
     nickname: e.detail.userInfo.nickName, 
     sex: e.detail.userInfo.gender,
     province: e.detail.userInfo.province, 
     city: e.detail.userInfo.city}; 
  login.myAuthorize(sendOjb,()=>{
  wx.navigateBack(); //Return to the previous page after success, or write some other logic according to project requirements}) 
 }else{
  
 }
 },
 /**
 * Life cycle function--listen for page loading*/
 onLoad: function (options) {

 },
})

Conclusion

The above code can be copied and pasted into your own WeChat applet project and it will run normally. If there are any errors or areas that need improvement, please contact me and I will correct them in time.

This concludes this article on the elegant way to handle WeChat Mini Program authorized login. For more relevant WeChat Mini Program authorized login content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • WeChat Mini Program user authorization to obtain mobile phone number (getPhoneNumber)
  • springboot+jwt+springSecurity WeChat applet authorization login problem
  • Implementation of WeChat applet wx.getUserInfo authorization to obtain user information (avatar, nickname)
  • Implementation of login authorization for uni-app WeChat applet
  • WeChat Mini Program User Background Location and Recording Authorization and Request Example

<<:  mysql5.5 installation graphic tutorial under win7

>>:  How to deploy Node.js with Docker

Recommend

HTML table markup tutorial (5): light border color attribute BORDERCOLORLIGHT

In a table, you can define the color of the upper...

Pure CSS to achieve the list pull-down effect in the page

You may often see the following effect: That’s ri...

Detailed tutorial on building Gitlab server on CentOS8.1

There is no need to say much about the difference...

react-diagram serialization Json interpretation case analysis

The goal of this document is to explain the Json ...

Docker FAQ

Docker only maps ports to IPv6 but not to IPv4 St...

Solution - BASH: /HOME/JAVA/JDK1.8.0_221/BIN/JAVA: Insufficient permissions

1) Enter the folder path where the jdk file is st...

Web componentd component internal event callback and pain point analysis

Table of contents Written in front What exactly i...

How to explain TypeScript generics in a simple way

Table of contents Overview What are Generics Buil...

Nginx external network access intranet site configuration operation

background: The site is separated from the front ...

Example code of how CSS matches multiple classes

CSS matches multiple classes The following HTML t...

Problem analysis of using idea to build springboot initializer server

Problem Description Recently, when I was building...

MySQL encoding utf8 and utf8mb4 utf8mb4_unicode_ci and utf8mb4_general_ci

Reference: MySQL character set summary utf8mb4 ha...

Interpretation of the module for load balancing using nginx

Table of contents Two modules for using nginx for...