Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does WeChat Mini Programs realize the effect of login session

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of WeChat Mini Programs how to achieve the login session effect, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe everyone will gain something after reading this WeChat Mini Programs article on how to achieve the login session effect. Let's take a look.

Background

WeChat Mini Programs's use can quickly establish and promote user circles based on scenarios, in which user information and authorization process are used according to business needs, mainly including api functions encapsulated by Wechat in development tools: wx.login, wx.getUserInfo, wx.checkSession, wx.getStorageSync, wx.request and so on.

1. Keywords

The user's open data returned when the open data call wx.getUserInfo (this API is adjusted, and the authorization pop-up window will no longer appear using this API to guide the user to take the initiative to authorize the operation) can be obtained at any time, but the encrypted data encryptedData needs to be decrypted using the user's session_key as the secret key to get the original complete data. To prevent the returned data from being tampered with and forged, developers can send signature and rawData to the developer server for verification. The server uses the user's corresponding session_key to calculate the signature signature2 using the same algorithm, and the integrity of the data can be verified by comparing signature with signature2. The returned results mainly include:

The parameter type describes the userInfo OBJECT user information object, which does not contain sensitive information such as openid. RawData String does not include the original data string of sensitive information, which is used to calculate the signature. Signature String uses sha1 (rawData + sessionkey) to get the string, which is used to verify the user information, refer to the documentation signature. For the encrypted data of encryptedData String complete user information, including sensitive data, see the initial vector of the encrypted data decryption algorithm iv String encryption algorithm for details. For more information, please see the example of the result returned after a successful call to the encrypted data decryption algorithm / /. {encryptedData: "6exNeBvACXreply EpzLNF2vYRhM0Z1tNZnBOYP0Q7jQ4Ofvroom69qYGGVAB34aj4f364mkjAAD5pgDDJ41hGkkrguIaHJGioI3EhGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rKedfBUerG4jEgXS0GeERMtJ15tEGz7qzcA49c1D1obZ1TunZZq1v1lXo3oUbnmAx7LUQcCQAAA7LUQcCQA1KLUQcCQAAA7LUQcCQA6AAAX6PUBFY3EhGSEQYAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rKedfBUerG4jEgX4rKedfBUerG4jEgX4rGGkrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rKEhGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9GkrGkrAfE1mPovV9s6Prg4rGSEQyrAfE1mPovV9s6Prg4rGSEQyrAfE1 Signature: "c32wba325164258b9a332b6fdsdew2e520081348", userInfo: {avatarUrl: "https://wx.qlogo.cn/mmsen/vi_s/0daYVYsscPNxEvALzBTsJarXwUmlxjZJZMHPM6NNLegH4wLRcRlsA1x4bsJg/132", city:", country: "Iceland", gender:1, language: "zh_CN", nickName: "xxx", province: ""}}

Sensitive data acquisition (encrypted data encryptedData signature signature)

For encryptedData, developers need to symmetrically decrypt the encrypted data (encryptedData) returned by the API if they need to obtain sensitive data. That is, the encryptedData that needs to be decrypted by session_key on the developer server has the following structure:

{"openId": "OPENID", "nickName": "NICKNAME", "gender": GENDER, "city": "CITY", "province": "PROVINCE", "country": "COUNTRY", "avatarUrl": "AVATARURL", "unionId": "UNIONID", "watermark": / / data watermark {"appid": "APPID" / / sensitive data belongs to appid Developers can verify whether this parameter is consistent with their own appid "timestamp": TIMESTAMP / / the timestamp of sensitive data acquisition, which can be used to verify the timeliness of data}}.

Custom login environment: data on the developer's server: using the open data or decrypted sensitive data obtained by API calls and session_key operations: using the data to establish a unique identity of the user on Mini Program, and sending the self-defined login status information record session (or other information records) to the client, with session_key as the secret key Must be saved on the developer server (previous interface https://api.weixin.qq.com/sns... You can set it to a valid address in the Mini Program development settings-server configuration, but now it's not working. Can only use a third-party server for API calls) use: users do not log in for the first time-> query the custom session-- in the local cache > get the session and query the developer server-- > this session is not available on the server-- > users can make normal business requests (this is only a common and normal login situation)

two。 Log in

Basic: use wx.login () to obtain the parameter code needed by the developer server when requesting session_key and other data from the Wechat API server. The developer server uses code+appid+app secret (Mini Program key, which can be obtained by the management backend) in exchange for the user's unique identity openid and session key session_key. But each call to wx.login () updates the session_key on the Wechat interface server.

Log in for the first time

Obtain login credentials code-- > send to developer server construction interface (appid + app secret + code) to request Wechat interface server data-> return user data key session_key and unique ID openid to developer server-> generate custom third party session based on session_key and openid, store session_key to developer server, and cannot send session_key to client Prevent sensitive data from leaking-- > send third-party custom login information session to the client-- > save custom third-party login status information session to the local cache. If the login is successful, you can set a login ID flag, so that flag=true indicates that the login is successful for the first time and carries out relevant processing operations. The API for login verification credentials (which is called in the developer server and cannot be used in Mini Program) is:

Https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code appid Mini Program uniquely identifies secret Mini Program. The app secret js_code of secret Mini Program is the credential obtained by wx.login when logging in. Code grant_type is authorization_code.

The specific pseudo code is as follows:

/ * I encapsulate this step into a function and then call the backend services that need to log in before I have permission to access them. * you can use this function to operate, basic logic You can also expand * @ url: the developer server login service API can set the default value * @ key: the key value of the third-party custom login session stored in the local cache * @ callback: you need to use the callback function (or collection of functions) of the login service * / function Login (key,url) Callback) {/ / first use wx.login to obtain login credentials code and send them to developer server wx.login ({success: function (res) {if (res.code) {/ / send code to developer server to get session_key and openid wx.request ({url:url) Data: {code: res.code} / / sent to developer server success successfully: function (res) {/ / developer server successfully obtained session_key and openid and returned / / third-party custom session or decrypted data such as json format res to client if (res.has3rdSession) {/ / login succeeded Save a third-party session to the local cache console.log ("login successful") wx.setStorageSync (key Res.3rdSession) / / set login ID as true this.setData {flag:true} / / for subsequent callback processing callback (res).... } else {/ / did not return third-party custom session, login failed console.log ("login failed"). } else {/ / did not get login credentials code, login failed console.log ('login failed!' + res.errMsg). })}

Non-first login

Wx.getStorageSync () queries whether our custom session login status information is in the local cache, and if so, it proves that it is not the first time to log in. At this time, first query whether the user's session_key on the Wechat API server has expired. If it expires, regardless of the session defined by ourselves, log in again, and set the login ID flag to false. If it does not expire, you can send sessio to the developer server to query the user information. If the developer server tells us that the self-defined session has expired, log in again, and set the login ID flag to false. If it does not expire, query whether there is this session to obtain the user's information. The pseudo code is as follows:

/ *-I encapsulate this step into a function and then call the backend services that need to log in before I have permission to access them. -you can use this function to operate, basic logic You can also extend-@ url: developer server service interface-@ key: the key name of the self-defined session stored in the local cache-@ callback: need to use the callback function (or set of functions) of the login service-@ others: other parameters such as data needed * / function doRequestWithSession (key,url,callback) Others) {try {var value = wx.getStorageSync (key) if (value) {/ / there is a custom login session Non-first login / / query whether the user key session_key expires wx.checkSession ({success: function () {/ / session_key does not expire And has been valid for the current life cycle / / send custom session query user information wx.request ({url: url, data: value) to the developer server / / the custom session value of the local cache can be added with other required data others and other success: function (res) {if (res.hasSession) {/ / query succeeded There is our custom session / / on the developer server to perform the corresponding operation based on the returned result. First determine whether the session expires / / if our custom session has expired if (res.expired) {console.log ("session expired") Re-login ") / / set the login identity as false this.setData {flag:false} wx.login () / / re-login or Return the error code. } else {/ / has not expired The returned result can be the relevant information of the user / / log in to console.log ("Welcome back") callback (res) successfully. }} else {/ / developer server does not have our custom session, log in to console.log again ("No such session Re-login ") / / set the login identity as false this.setData {flag:false} wx.login () / / re-login or return Return the error code. })}, fail: function () {/ / session_key has been invalidated You need to re-execute the login process / / set the login ID as false this.setData {flag:false} wx.login () / / log in again or return an error code. }})} else {/ / there is no custom session login status information in the local cache, then log in for the first time or subsequent processing / / set the login ID as false this.setData {flag:false} wx.login () / / or return an error code. }} catch (e) {/ / exception handling. }}

When conditional judgment requires services with login permissions, you can use conditional judgment pseudo code:

If (this.data.flag) {/ / has logged in, non-first login doRequestWithSession (key,url,callback,others).} else {/ / has not been logged in. You can further check whether the local cache has 3rdSession do other things.} 3. Get secure raw data

As mentioned in the first part, sensitive data and open data can be obtained with wx.getUserInfo, but it is impossible to decrypt sensitive data without logging in to obtain decryption key session_key. Therefore, in open data, without login, we can only get the user's nickname, avatar, city, gender, nationality, etc., and there is no unique id to identify the user. So how to get our secure raw data, only: get open data-> get login permission, developer server gets key session_key verification signature decryption data-> return decryption data, including openid. Pseudo code:

A.wxml file:

/ / wx.getUserInfo interface has been adjusted. Authorization pop-up window will no longer appear when using this interface. If you want to use components to guide users to actively authorize operations, you should pay attention to: / / if the user has not been authorized, calling this interface will directly report an error; when the user has been authorized, you can use this interface to obtain user information / / example login

A.js file:

Page ({data: {}) . / / Click the login button and trigger showUserInfo:function (e) {/ / get the data to be decrypted var encryptedData = e.detail.encryptedData / * * @ key third-party custom login session exists locally cached key value * @ url decryption sensitive data developer server service interface * @ callback obtains the callback function after decrypting the data * @ encryptedData undecrypted data currently obtained * / doRequestWithSession (key Url,callback,encryptedData),}) 4. Backstage

There are many backend services, which can be managed on the API platform:

Login API: domain/api/login

Verification signature decryption API: domain/api/decrypt

Other

Example of decryption code (official 4 language versions: Python, php, C++, node):

This is the end of the article on "how to achieve the login session effect of WeChat Mini Programs". Thank you for your reading. I believe that everyone has a certain understanding of the knowledge of "how to achieve the effect of login session by WeChat Mini Programs". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report