Home>Article>WeChat Applet> User login and login status maintenance in WeChat mini program

User login and login status maintenance in WeChat mini program

hzc
hzc forward
2020-06-28 10:10:23 3619browse

Update description:

Due to the official revision of the relevant API of the WeChat applet, there have been some changes in the login function process, so another article has been updated recently (with video description and Complete sample code), you can read it together with this article for reference:

Login and session retention process after the revision of WeChat applet interface

Provide user login and maintain user login status , is something that a software application with a user system generally needs to do. For a social platform like WeChat, if we make a small program application, we may rarely make a pure tool software that is completely separated from and abandons the connection of user information.

Allowing users to log in, identifying users and obtaining user information, and providing services with users as the core are what most small programs will do. Today we will learn how to log in users in the mini program and how to maintain the session state after login.

In the WeChat mini program, we will generally involve the following three types of login methods:

  • Own account registration and login
  • Use other third-party platforms Account login
  • Log in with a WeChat account (that is, directly use the currently logged-in WeChat account to log in as a user of the mini program)

The first and second methods are currently Web The two most common methods in applications can also be used in WeChat mini programs, butneed to pay attentionis that there is noCookiemechanism in the mini program, so when using this Before using the 2 methods, please confirm whether your or third-party APIs need to rely onCookie; also, HTML pages are not supported in mini programs. Those third-party APIs that need to use page redirection to log in do so. Renovated, or no longer usable.

Today we will mainly discuss the third method, that is, how to log in using a WeChat account, because this method is most closely integrated with the WeChat platform and has a better user experience.

Login process

Quoting the login flow chart from the official document of the mini program, the entire login process is basically as shown in the following figure:

User login and login status maintenance in WeChat mini program

This figure , "mini program" refers to the code part we write using the mini program framework, "third-party server" is generally our own background service program, and "WeChat server" is WeChat's official API server.

Let’s break down this flow chart step by step.

Step 1: Obtain thelogin credentials (code) of the currently logged-in WeChat user on the client

The first step to log in in the mini program is to obtain the login credentials first . We can use the wx.login() method and get a login credentials.

We can initiate a login credential request in the App code of the mini program, or in any other Page code, mainly based on the actual needs of your mini program.

App({ onLaunch: function() { wx.login({ success: function(res) { var code = res.code; if (code) { console.log('获取用户登录凭证:' + code); } else { console.log('获取用户登录态失败:' + res.errMsg); } } }); } })

Step 2: Send the login credentials to your server, and use the credentials on your server to exchange the WeChat server for the WeChat user'sunique identification (openid)andSession key (session_key)

First, we use the wx.request() method to request a background API implemented by ourselves and carry the login credentials (code), for example, in our Based on the previous code, add:

App({ onLaunch: function() { wx.login({ success: function(res) { var code = res.code; if (code) { console.log('获取用户登录凭证:' + code); // --------- 发送凭证 ------------------ wx.request({ url: 'https://www.my-domain.com/wx/onlogin', data: { code: code } }) // ------------------------------------ } else { console.log('获取用户登录态失败:' + res.errMsg); } } }); } })

Your background service (/wx/onlogin) then needs to use the passed login credentials to call the WeChat interface in exchange for openid and session_key. The interface address format is as follows:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

Here is the code of the background service I built using Node.js Express, for reference only:

router.get('/wx/onlogin', function (req, res, next) { let code = req.query.code request.get({ uri: 'https://api.weixin.qq.com/sns/jscode2session', json: true, qs: { grant_type: 'authorization_code', appid: '你小程序的APPID', secret: '你小程序的SECRET', js_code: code } }, (err, response, data) => { if (response.statusCode === 200) { console.log("[openid]", data.openid) console.log("[session_key]", data.session_key) //TODO: 生成一个唯一字符串sessionid作为键,将openid和session_key作为值,存入redis,超时时间设置为2小时 //伪代码: redisStore.set(sessionid, openid + session_key, 7200) res.json({ sessionid: sessionid }) } else { console.log("[error]", err) res.json(err) } }) })

If this background code is successfully executed, you can get the openid and session_key. This information is the login status of the current WeChat account on the WeChat server.

However, for security reasons, please do not directly use this information as the user ID and session ID of your mini program to be sent back to the mini program client. We should make our own layer on the server side. session, generate a session id from this WeChat account login state and maintain it in our own session mechanism, and then distribute this session id to the mini program client for use as a session identifier.

Regarding how to implement this session mechanism on the server side, we now generally use key-value storage tools, such as redis. We generate a unique string as a key for each session, and then store session_key and openid as values in redis. For safety, a timeout should be set when saving.

Step 3: Savesessionid on the client

When developing web applications, in the client (browser), we usually store the session id in a cookie , but the mini program does not have a cookie mechanism, so cookies cannot be used. However, the mini program has local storage, so we can use storage to save the sessionid for subsequent background API calls.

在之后,调用那些需要登录后才有权限的访问的后台服务时,你可以将保存在storage中的sessionid取出并携带在请求中(可以放在header中携带,也可以放在querystring中,或是放在body中,根据你自己的需要来使用),传递到后台服务,后台代码中获取到该sessionid后,从redis中查找是否有该sessionid存在,存在的话,即确认该session是有效的,继续后续的代码执行,否则进行错误处理。

这是一个需要session验证的后台服务示例,我的sessionid是放在header中传递的,所以在这个示例中,是从请求的header中获取sessionid:

router.get('/wx/products/list', function (req, res, next) { let sessionid = req.header("sessionid") let sessionVal = redisStore.get(sessionid) if (sessionVal) { // 执行其他业务代码 } else { // 执行错误处理 } })

好了,通过微信账号进行小程序登录和状态维护的简单流程就是这样,了解这些知识点之后,再基于此进行后续的开发就会变得更容易了。

另外,腾讯前端团队也开源了他们封装的相关库Wafer,可以借鉴和使用。

  • 服务端SDK: wafer-node-session
  • 小程序端SDK: wafer-client-sdk

感谢阅读我的文章,如有疑问或写错的地方请不吝留言赐教。

一斤代码的《微信小程序》相关教程文章
一斤代码的《从编程小白到全栈开发》系列教程文章

推荐教程:《Vue.js教程推荐:最新的5个vue.js视频教程精选

The above is the detailed content of User login and login status maintenance in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete