How to handle token expiration in WeChat Mini Programs

How to handle token expiration in WeChat Mini Programs

Conclusion first

Business process: If the token is found to be expired from the network log, the page will be redirected to the login page, requiring the user to log in again.

Code logic: Use custom HttpUtil to encapsulate wx.request API, globally capture expired tokens, automatically process them, and then send them to upper-level businesses.

question

Token expiration phenomenon:

In network requests, the client token will expire after a period of time, causing subsequent network requests to fail and throwing an exception log as follows:

data: {code: "99997", date: 1634174831325, message: "TOKEN EXPIRED", status: "ERROR"}

The API provided by the mini program: wx.request is very simple. Developers can only check token expiration in the callback function after the request response is successful. The conventional approach is:

1. Define the method to check token expiration:

function checkAuth(resp) {
  if(resp.data.code == '99997') { //The token expiration code returned by our server is 99997. The code can be customized with the backend.
    wx.navigateTo({
      url: '/pages/login/login', // Jump to the login page here and ask the user to log in again})
    console.log("Need to log in again...");
  }
}

2. In the response of each request interface, call checkAuth(res) to capture token expiration.

Problem code

function createMatchImage(data, fun) {
  //console.log(getApp())
  console.log("token = " + getApp().getToken())
  wx.request({
    method: 'POST',
    url: conf.baseUrl + 'match/matchImages', 
    data: data,
    header: {
      'content-type': 'application/json',
      'sessionKey': getApp().getToken()
    },
    success: function (res) {
      console.log(res)
      conf.checkAuth(res) // Check if the token is expired. If it is expired, jump to the login page.
      fun(res);
    }
  });
}
 
function getMatchImages(id, fun) {
  wx.request({
   ...
    success: function (res) {
      conf.checkAuth(res)
   ...
    }
  });
}
 
function deleteImage(id, fun) {
...
  wx.request({
    ...
    success: function (res) {
      conf.checkAuth(res)
      fun(res);
      //return res;
    }
  });
}

In the above code, each interface will have repeated code, such as configuring baseUrl, token, and checkAuth(). So here we can further remove duplicate code.

Solution

Unify the entry point for network requests and define the HttpUtil class. Encapsulates wx.request method.

const get = (url, success, fail) => {
    var _token = getApp().getToken()
    wx.request({
      method:'GET',
      url: baseUrl + url,
      header:{
        'Authorization': _token,
        'content-type': 'application/json',
      },
      success:function(res) {
        checkAuth(res) //Block token expiration here and jump to the login interface console.log(res)
        success(res)
      },
      fail:function(res){
        console.log("Request failed")
        fail(res)
      }
    })
}
···
 
module.exports = {
    get: get,
    post: post
}

HttpUtil usage scenarios:

const httpUtil = require("../common/http/HttpUtil")
 
//The logic layer initiates a network request, only the URL and the success callback function need to be passed. This is much cleaner than before.
function getActivities(success) {
    httpUtil.get('meetup/api/v1/activity/getActivityList?pageNo=1&pageSize=100', function(res) {
        success(res)
    })
}
 
module.exports = {
    getActivities : getActivities
}

As shown above, when using httpUtil, the process of handling token expiration is transparent and the details are encapsulated internally. At the same time, the business side also saves the boilerplate code such as setting tokens, token expiration processing, baseUrl, etc.

Use Promise to encapsulate callback functions

We can use Promise to avoid passing in a callback function when calling the request interface.

const get = (params) => {
    var _token = getApp().getToken()
    return new Promise((resolve, reject) => {
      wx.request({
        method:'GET',
        url: concatUrl(params),
        header:{
          'Authorization': _token,
          'content-type': 'application/json',
        },
        success: (res) => {
          checkAuth(res) //Block token expiration here and jump to the login interface resolve(res)
        },
        fail:(err) => {
          console.log("Request failed")
          reject(err)
        }
      })
    })
}

Directions:

// service layer, define network interface function getActivities() {
    return HttpUtil.get({
        url: 'meetup/api/v1/activity/getActivityList?pageNo=1&pageSize=100'
    })
}
    /**
     * Load the activity list (load the group first to get the activity avatar)
     */
    fetchGroupAndActivities: function(){
      if(this.data.isLogin) {
        var that = this
        getGroups() //Load the avatars of the group list first.
        .then((res)=>{
          if(res.data.code == "10000") { 
            ...
            return getActivities() //Secondly, load the activity list}
        })
        .then((res)=>{ //Chain call, process activity list data.
          if (res.data.code == "10000") {
          ...
          }
        })
        .catch((err) => { //Catch exceptions uniformly. If any callback in the then above sends an exception, the call chain will be directly interrupted and processed here.
          console.log("get act and group failed...")
        })
    }},

Summarize

In the encapsulation process of wx.requestAPI, the Promise object is used inside HttpUtil to encapsulate baseUrl, token processing, etc., hiding the implementation details, providing a unified interface to the outside world and supporting chain calls. This is a common facade design pattern. The disadvantage is that it violates the open-closed principle. If some new interception request interface processing is added, the original interface implementation must be modified. Later, an intermediate layer can be added as an interceptor to expand new functions.

This is the end of this article about how WeChat Mini Programs handle token expiration issues. For more information about Mini Program token expiration, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • About WeChat Mini Program crawler token automatic update issue
  • Mini Program Development to Implement Unified Management of Access_Token
  • Tutorial on how to log in to WeChat Mini Program and exchange tokens
  • WeChat applet url and token settings detailed explanation
  • Mini Program to implement Token generation and verification

<<:  HTML mouse css control

>>:  Implementation of tomcat deployment project and integration with IDEA

Recommend

MySQL 5.7.17 Compressed Version Installation Notes

This article shares the installation steps of MyS...

nuxt.js multiple environment variable configuration

Table of contents 1. Introduction 2. Scenario 3. ...

MySQL green version setting code and 1067 error details

MySQL green version setting code, and 1067 error ...

How to delete all contents in a directory using Ansible

Students who use Ansible know that Ansible only s...

Analysis of the HTML writing style and reasons of experienced people

1. Navigation: Unordered List vs. Other Label Ele...

Summary of practical experience of HTML knowledge points

1. The table tag is table, tr is row, td is cell, ...

Using nginx + fastcgi to implement image recognition server

background A specific device is used to perform i...

Detailed explanation of the functions and usage of MySQL common storage engines

This article uses examples to illustrate the func...

Talk about implicit conversion in MySQL

In the course of work, you will encounter many ca...

Introduction to Nginx log management

Nginx log description Through access logs, you ca...

Detailed explanation of mysql permissions and indexes

mysql permissions and indexes The highest user of...

Five delay methods for MySQL time blind injection

Five delay methods for MySQL time blind injection...

Ubuntu boot auto-start service settings

How to create a service and auto-start it in Ubun...