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

CSS3 custom scroll bar style::webkit-scrollbar sample code detailed explanation

The default scroll bar style in Windows is ugly, ...

NestJs uses Mongoose to operate MongoDB

I recently started learning the NestJs framework....

Several ways to easily traverse object properties in JS

Table of contents 1. Self-enumerable properties 2...

JavaScript MouseEvent Case Study

MouseEvent When the mouse performs a certain oper...

Implementation code for infinite scrolling with n container elements

Scenario How to correctly render lists up to 1000...

SQL interview question: Find the sum of time differences (ignore duplicates)

When I was interviewing for a BI position at a ce...

Alpine Docker image font problem solving operations

1. Run fonts, open the font folder, and find the ...

Detailed explanation of Excel parsing and exporting based on Vue

Table of contents Preface Basic Introduction Code...

Detailed steps to install docker in 5 minutes

Installing Docker on CentOS requires the operatin...

Detailed explanation of MySQL InnoDB secondary index sorting example

Sorting Problem I recently read "45 Lectures...

How to simulate network packet loss and delay in Linux

netem and tc: netem is a network simulation modul...

Vue routing relative path jump method

Table of contents Vue routing relative path jump ...