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 to solve the failure of WeChat Mini Programs login session key session

2025-03-13 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "WeChat Mini Programs login session key session failure how to solve", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "WeChat Mini Programs login session key session failure how to solve" it!

1. Login session key session_key validity

Https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/signature.html

If developers encounter failed signature verification or decryption due to incorrect session_key, please pay attention to the following considerations related to session_key.

When wx.login is called, the user's session_key may be updated and the old session_key may be invalidated (the refresh mechanism has the shortest period. If the same user calls wx.login multiple times in a short time, not every call will cause session_key refresh). Developers should only call wx.login when they clearly need to log back in and update the session_key stored on the server through the auth.code2Session interface in time.

Wechat will not inform developers of the validity period of session_key. We will renew session_key according to the behavior of users using Mini Program. The more often users use Mini Program, the longer the validity of session_key.

When the session_key fails, the developer can obtain a valid session_key by re-executing the login process. You can use the API wx.checkSession to verify whether the session_key is valid, thus preventing Mini Program from performing the login process repeatedly.

When developers implement a custom login state, they can consider the session_key validity period as the validity period of their login state, and they can also implement a custom timeliness policy.

Second, solve the problem of logging into session_key

Determine whether it expires by wx.checkSession.

Step 1: onLaunch calls the write-once login method during the life cycle

Step 2: determine whether it expires through wx.checkSession elsewhere. If it expires, call the login method again and update session_key.

Case: solve the problem of expiration of session_key, send personal information and decrypt it in # app.js: / / app.jsApp ({/ * when the initial message of Mini Program is completed Will trigger onlaunch (global trigger only once) * / onLaunch: function () {/ / login this.my_login ()}, my_login:function () {let that = this wx.login ({success: res = > {/ / send res.code to the background in exchange for openId, sessionKey, unionId console.log (res.code) wx.request ({url: that.globalData.baseurl + "login/") Data: {"code": res.code}, method: "POST", success (e) {wx.setStorageSync ('token', e.data.data.token)}})})}, globalData: {userInfo: null Baseurl: "http://127.0.0.1:8000/"}}) # page js: / / get the app global object const app = getApp () user1:function (e) {wx.getSetting ({success (res) {if (res.authSetting ['scope.userInfo']) {wx.getUserInfo ({success: (res) = > {console.log (" res ")) Res) / / this res is the user's information / / send the data to the backend wx.request ({/ / send iv,encryptedData url: app.globalData.baseurl + "getinfo/", data: {iv:res.iv, encryptedData: res.encryptedData Token:wx.getStorageSync ("token")}, method: "POST", success: (e) = > {console.log ('data returned at the background', e)}})} }) / / determine whether the wx.checkSession expires ({success () {/ / session_key is not expired) And it has been valid for the current life cycle. Fail () {/ / session_key has expired, and you need to re-execute the login process app.my_login () / / log in again. Update session_key wx.getUserInfo ({success: (res) = > {console.log ("res la la", res) / / this res is the user's information / / send the data to the backend wx.request ({/ / send iv) EncryptedData url: 'url',})},})})} backend decryption information Save to database # login: # urls.pypath ('getinfo/', user.Info.as_view ()), # user.pyfrom django.core.cache import cachefrom api.models import Wxuserfrom api.wx import WXBizDataCryptfrom api.my_ser import wx_user_serfrom rest_framework.response import Responseclass Info (APIView): def post (self) Request): param = request.data if param ['iv'] and param.get ("token") and param.get ("encryptedData"): iv = param [' iv'] encryptedData = param.get ("encryptedData") session_key_openid = cache.get (param.get ("token") if session_key_openid: sessionKey Openid = session_key_openid.split ("&") # decryption user_info = WXBizDataCrypt.WXBizDataCrypt.get_info (sessionKey, encryptedData, iv) print ('user_info', user_info) save_data = {"name": user_info [' nickName'], "avatar": user_info ['avatarUrl'] "language": user_info ['language'], "province": user_info [' province'], "city": user_info ['city'], "country": user_info [' country'] } # store user information in database Wxuser.objects.filter (openid=openid). Update (* * save_data) # Test: return Tong Hu information to the foreground user = Wxuser.objects.filter (openid=openid). First () user = wx_user_ser (instance=user) Many=False. Data return Response ({"status": 0, "msg": "ok", "data": user}) else: return Response ({"code": 2 "msg": "invalid token"}) else: return Response ({"code": 1, "msg": "missing parameter"}) # detect dictionary sorting # WXBizDataCrypt file Decryption of download Then the secondary package of import base64import jsonfrom Crypto.Cipher import AESfrom api.wx import settingsclass WXBizDataCrypt: def _ init__ (self, appId, sessionKey): self.appId = appId self.sessionKey = sessionKey def decrypt (self, encryptedData, iv): # base64 decode sessionKey = base64.b64decode (self.sessionKey) encryptedData = base64.b64decode (encryptedData) iv = base64.b64decode (iv) cipher = AES.new (sessionKey, AES.MODE_CBC) Iv) decrypted = json.loads (self._unpad (cipher.decrypt (encryptedData) if decrypted ['watermark'] [' appid']! = self.appId: raise Exception ('Invalid Buffer') return decrypted def _ unpad (self, s): return s [:-ord (slen (s)-1:])] @ classmethod def get_info (cls,sessionKey,encryptedData Iv): # appId = settings.AppId # sessionKey = sessionKey # encryptedData = encryptedData # iv = iv # instantiate this class WXBizDataCrypt # pc = cls (appId, sessionKey) # return pc.decrypt (encryptedData, iv) # simplified to: return cls (settings.AppId, sessionKey) .decrypt (encryptedData, iv) mysql data inventory emoji setting

1.mysql database type

two。 Configuration: the default is utf8,3 bytes. The emoji is 4 bytes.

Need to set: 'OPTIONS': {' charset': 'utf8mb4'}

Import pymysqlpymysql.install_as_MySQLdb () DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME': 'python13',' USER': 'root',' PASSWORD': '123,' HOST': 'localhost',' PORT': 3306, 'OPTIONS': {' charset': 'utf8mb4'},}}, backend How to parse user information in wx.getUserInfor.

1 We use encryptedData and iv for decryption, and we must use session_key, so it must be login status.

2 but session_key has a validity period. And the validity period of session_key is not a fixed value, it is determined by user behavior, the validity period of session_key.

But we can judge whether it is out of date by wx.checkSession.

4 to ensure that the session_key does not expire. We send iv,encryptedData,token (login credentials) to the back end.

5 the backend uses the official sdk to decrypt it.

6 after the decryption is successful, the data is saved. The character set of the database must be utf8mb4 before the meme can be saved.

For example, the official sdk does not have a Crypto package and can be solved by the following methods:

Pip install pycryptodome here, I believe that everyone on the "WeChat Mini Programs login session key session failure how to solve" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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: 279

*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