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

Summary of various implementation methods of mysql database backup

This article describes various ways to implement ...

An article to help you understand the basics of VUE

Table of contents What is VUE Core plugins in Vue...

Solve the problem that the IP address obtained using nginx is 127.0.0.1

Get ip tool import lombok.extern.slf4j.Slf4j; imp...

Introduction to Docker Quick Deployment of SpringBoot Project

1. Install Docker First open the Linux environmen...

JavaScript implements draggable progress bar

This article shares the specific code of JavaScri...

Example of how to identify the user using a linux Bash script

It is often necessary to run commands with sudo i...

html+css+js to realize the function of photo preview and upload picture

Preface: When we are making web pages, we often n...

Detailed explanation of the use of default in MySQL

NULL and NOT NULL modifiers, DEFAULT modifier, AU...

Comparison of mydumper and mysqldump in mysql

If you only want to back up a few tables or a sin...

A Preliminary Study on JSBridge in Javascript

Table of contents The origin of JSBridge The bidi...

Detailed explanation of Nginx version smooth upgrade solution

Table of contents background: Nginx smooth upgrad...

Detailed explanation and extension of ref and reactive in Vue3

Table of contents 1. Ref and reactive 1. reactive...