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

Implementation steps for installing Redis container in Docker

Table of contents Install Redis on Docker 1. Find...

jQuery realizes the shuttle box effect

This article example shares the specific code of ...

How to create a table by month in MySQL stored procedure

Without going into details, let's go straight...

Pure JS method to export table to excel

html <div > <button type="button&qu...

How to set npm to load packages from multiple package sources at the same time

Table of contents 1. Build local storage 2. Creat...

A Preliminary Study on JSBridge in Javascript

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

Ubuntu regularly executes Python script example code

Original link: https://vien.tech/article/157 Pref...

Steps for IDEA to integrate Docker to achieve remote deployment

1. Enable remote access to the docker server Log ...

How to simply configure multiple servers in nginx

1: I won’t go into the details of how to install ...

How many common loops do you know about array traversal in JS?

Preface As a basic data structure, arrays and obj...

How to connect Django 2.2 to MySQL database

1. The error information reported when running th...

Use href to simply click on a link to jump to a specified place on the page

After clicking the a tag in the page, you want to ...

Example code for converting html table data to Json format

The javascript function for converting <table&g...

Is it easy to encapsulate a pop-up component using Vue3?

Table of contents Summary put first: 🌲🌲 Preface: ...