The login process of the WeChat applet - detailed code explanation

Mini program login flow chart (see the official website link for details):
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
Mini programs can be easily accessed through the official WeChat login capability Acquire the user identity provided by WeChat in a timely manner, and quickly establish the user system in the mini program.

The task that front-end developers need to do is to work from the small program to the developer server.
The developer server to WeChat interface service is the work of the background staff to decrypt and get the openid and session_key.

1. Analysis of the login process
First login:

1. First, you need to call the applet api interface wx.login() to obtain the temporary login credential code, which has an expiration time.
2. Send this code back to the developer server (that is, request the login interface of the developer server, and exchange the user login status information through the credential, including the user's unique identifier (openid) and the session key (session_key) for this login, etc. ).
3. After getting the session key (session_key) sent back from the developer server, the front end should save wx.setStorageSync('sessionKey', 'value')

When logging in again, it is necessary to judge whether the stored session_key has expired:
1. Obtain the session_key in the cache, wx.getStorageSync('sessionKey')
2. If there is a session_key in the cache, then call the applet api interface wx.checkSession() To determine whether the login status has expired, the callback success indicates that the current session_key has not expired, and the callback failure indicates that the session_key has expired. After the login state expires, the front end needs to call wx.login() to obtain the code of the new user, and then initiate a login request to the developer server.
3. Generally, in project development, the developer server will also impose expiration restrictions on the user's login status, so at this time, after judging whether the login status in the WeChat server has not expired, it is necessary to determine whether the login status of the developer server has expired. (Just request the interface given by the developer server to judge the request).
4. Whether the WeChat server has expired or the developer server login status has expired, you must start the three steps as the first login. So pay attention to the package code.

Learn more about wx.checkSession():
https://developers.weixin.qq.com/miniprogram/dev/api/wx.checkSession.html

2. Code encapsulation analysis
Through the above text analysis, we encapsulate the login process:

 

/**
* 用户相关服务 登陆,检查登录态
*/
const api = require('api.js');  // 这里是本人对统一接口地址封装
import {
HTTP
} from 'http.js'  // 这个是本人对wx.request()这个api进行了封装

// 一般都把登录代码封装为一个类,然后export 类出去。当多个组件使用到的时候就继承这个类就可以使用登录接口了。
class USER extends HTTP {  

/**
* Promise封装登录接口
* 判断本地缓存是否有sessionKey
* 有的情况下判断它是否过期
* **如果微信服务器没过期,继续从开发者服务器校验是否过期
* ****如果没过期,跳过登录,过期则调用登录接口
* **如果微信服务器登录态过期,则调用登录接口
* 没有则说明无登录态,调用登录接口
*/
login() {
return new Promise((resolve, reject) => {
	let sessionKey = wx.getStorageSync('sessionKey')
	if (sessionKey) {
		console.log('sessionKey不为空')
		this._checkWXSession() //检查用户的登录态在微信服务端是否过期
		.then(() => {
			console.log('微信后台未过期>>>开始检测开发者服务器登录态')
			return this._checkSerSession() // 检查用户登录态在开发者服务器端是否过期
		}).then(res => {
			console.log('sessionKey校验通过')
			resolve()
		})
		.catch((res) => {
			console.log('sessionKey校验未通过,过期了')
			this._wxLogin().then(res => {
				console.log(res)
				return this._serLogin(res.code)
			}).then(() => {
				resolve()
			})
		})
	} else {
		console.log('sessionKey为空,先微信服务器登录,再进行开发者服务器登录')
		this._wxLogin().then(res => {
			console.log(res)
			return this._serLogin(res.code)
		}).then(() => {
			resolve()
		})
	}
})
}

Code encapsulation for checking whether the WeChat server login status has expired:

/**
* Promise封装wx.checkSession(),检查微信服务器登录态是否过期
*/
_checkWXSession() {
	return new Promise((resolve, reject) => {
		wx.checkSession({
			success: () => {
				resolve(true)
			},
			fail: () => {
				reject(false)
			}
		})
	})
}

Check the code encapsulation of the login status of the developer server:

/**
* Promise封装开发者服务器sessionKey,检查开发者服务器登录态
*/
_checkSerSession() {
	return new Promise((resolve, reject) => {
		this.request({
			url: api.checkSession,
			header: {
			sessionKey: wx.getStorageSync('sessionKey')
			},
			method: 'POST'
			})
		.then(res => {
			resolve(res);
		})
		.catch(res => {
			reject(res)
			console.log('后台登录态过期')
		})
	})
}

Encapsulation of wx.login() WeChat login interface api :

/**
* Promise封装wx.login
*/
_wxLogin() {
	return new Promise((resolve, reject) => {
		wx.login({
			success: (res) => {
				if (res.code) {
					resolve(res);
				} 
				else {
					reject(res);
				}
			},
			fail: (err) => {
				reject(err);
			}
		})
	})
}

Encapsulation of developer server request interface login :

/**
* Promise封装开发者服务器登陆(获取登录后的sessionKey)
*/
_serLogin(code) {
	return new Promise((resolve, reject) => {
		this.request({
			url: api.login,
			data: {
			code: code
			},
			method: 'post'
			})
		.then(res => {
			wx.setStorageSync('sessionKey', res.data)
			console.log('登录成功的回调')
			resolve()
			})
		.catch(err => {
			this._show_error('开发者服务器登录失败')  //这个是消息提示框,在请求中封装了,这里简单理解错误弹出消息提示。
		})
	})
}

Guess you like

Origin blog.csdn.net/aaa123aaasqw/article/details/129954300