Providing user login and maintaining the user's login status are generally things that a software application with a user system 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 (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 platform accounts to log in
Use WeChat account to log in (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 the two most common methods currently used in Web applications. They can also be used in WeChat mini programs, but need to pay attention to the following: There is no Cookie<a href="//m.sbmmt.com/wiki/422.html" target="_blank"></a> mechanism in the mini program, so before using these two methods, please confirm whether yours or a third party's
API needs to rely on Cookie ; In addition, HTML pages are not supported in mini programs. Those third-party APIs that need to use page redirection for login need to be modified or cannot be used.
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's
unique identification (openid)Session 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:
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)
}
})
})
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: Save
sessionid 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 { // 执行错误处理 } })
好了,通过微信账号进行小程序登录和状态维护的简单流程就是这样,了解这些知识点之后,再基于此进行后续的开发就会变得更容易了。
另外,腾讯前端团队也开源了他们封装的相关库,可以借鉴和使用。
服务器端库 weapp-session
小程序端库 weapp-session-client
感谢阅读我的文章,如有疑问或写错的地方请不吝留言赐教。
【相关推荐】
1. 微信小程序完整源码下载
The above is the detailed content of Mini Program Development--User Login and Maintenance Example Tutorial. For more information, please follow other related articles on the PHP Chinese website!