This article brings you an introduction to the method of adding session mechanism to WeChat applet. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
The idea of this article comes from reading the source code of WeChat wafer a few days ago. Thanks to all wafer code writers.
Let’s look at the code implementation first
var SESSION_KEY = 'xxxxxx';var Session = { get: function() { return wx.getStorageSync(SESSION_KEY) || null; }, set: function(session) { wx.setStorageSync(SESSION_KEY, session); }, clear: function() { wx.removeStorageSync(SESSION_KEY); }, }; module.exports = Session;
It’s very simple, isn’t it? This is how it is implemented. Explain, for example, when we log in, we need to make a storage on the mini program side. Mainly What is stored is the access_token returned by the backend (this value is used for interface requests that require user authentication), then the above Session can be used.
if (result.statusCode === 200 && data.access_token) { Session.set(data.access_token); }
When we determine whether the local user is logged in, we can also perform the following operations
var session = Session.get(); if (session) { wx.checkSession({ success: function () { //// }, fail: function () { Session.clear(); // doLogin(); }, }); } else { //doLogin(); 进行登录 }
Of course, this mechanism is not necessary, but with it, the code becomes more concise and obtains The user's session, writing session and clearing session, one thing is very easy for your backend junior to understand when they see your code.
The above is the detailed content of Introduction to the method of adding session mechanism to WeChat applet. For more information, please follow other related articles on the PHP Chinese website!