1. Let’s take a look at the effect first Data returned by the interface request: 2. Official Login Flowchart 3. Mini Program Login Process: 1. The applet calls wx.login 2. Determine whether the user is authorized 3. Access wx.getUserInfo from the applet 4. Mini program js code: wx.login({ success: resp => { // Send res.code to the backend in exchange for openId, sessionKey, unionId console.log(resp); var that = this; // Get user information wx.getSetting({ success: res => { if (res.authSetting['scope.userInfo']) { // Already authorized, you can directly call getUserInfo to get the avatar nickname without a pop-up window wx.getUserInfo({ success: userResult => { var platUserInfoMap = {} platUserInfoMap["encryptedData"] = userResult.encryptedData; platUserInfoMap["iv"] = userResult.iv; wx.request({ url: 'http://127.0.0.1:5000/user/wxlogin', data: { platCode: resp.code, platUserInfoMap: platUserInfoMap, }, header: { "Content-Type": "application/json" }, method: 'POST', dataType:'json', success: function (res) { console.log(res) wx.setStorageSync("userinfo", res.userinfo) //Set local cache }, fail: function (err) { }, // Request failed complete: function () { } // Function executed after request is completed }) } }) } } }) } }) 5. The backend server accesses code2session and obtains the login 6. The backend server verifies the user information and decrypts { "openId": "OPENID", "nickName": "NICKNAME", "gender": GENDER, "city": "CITY", "province": "PROVINCE", "country": "COUNTRY", "avatarUrl": "AVATARURL", "unionId": "UNIONID", "watermark": { "appid":"APPID", "timestamp":TIMESTAMP } } 7. Create a new decryption file - WXBizDataCrypt.py
import base64 import json from Crypto.Cipher import AES class 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(s[len(s)-1:])] 8. Flask's import json,requests from WXBizDataCrypt import WXBizDataCrypt from flask import Flask @app.route('/user/wxlogin', methods=['GET','POST']) def user_wxlogin(): data = json.loads(request.get_data().decode('utf-8')) # Convert the front-end Json data to a dictionary appID = 'appID' # The developer's appID for the WeChat applet appSecret = 'appSecret' # Developer's appSecret for WeChat Mini Program code = data['platCode'] # WeChat temporary login credential code sent by the front end POST encryptedData = data['platUserInfoMap']['encryptedData'] iv = data['platUserInfoMap']['iv'] req_params = { 'appid': appID, 'secret': appSecret, 'js_code': code, 'grant_type': 'authorization_code' } wx_login_api = 'https://api.weixin.qq.com/sns/jscode2session' response_data = requests.get(wx_login_api, params=req_params) # Initiate a GET request to the API resData = response_data.json() openid = resData ['openid'] # Get the user's OpenID for the current applet session_key = resData ['session_key'] # Get the user's session key session_key for the current applet pc = WXBizDataCrypt(appID, session_key) #Decrypt user information userinfo = pc.decrypt(encryptedData, iv) #Get user information print(userinfo) ''' The following part determines whether to add or return a custom login state by judging whether the user exists in the database (if the user does not exist, add it; if the user exists, return the user information) --------slightly slightly slightly slightly slightly slightly slightly slightly------------- I will skip this part and operate on users in the database''' return json.dumps ({ "code": 200, "msg": "Login successful", "userinfo": userinfo}, indent=4, sort_keys=True, default=str, ensure_ascii=False) Summarize This is the end of this article about Python Flask WeChat applet login details and login API implementation. For more related Python Flask WeChat applet login details and login API implementation content, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Vue implements three-level navigation display and hiding
>>: mysql: [ERROR] unknown option '--skip-grant-tables'
0. Background Hardware: Xiaomi Notebook Air 13/In...
When making a web page, you sometimes use a dividi...
Download the secure terminal MobaXterm_Personal F...
Background: During the development process, we of...
I usually use nginx as a reverse proxy for tomcat...
Table of contents Preface Front-end structure Bac...
Mysql supports 3 types of lock structures Table-l...
When faced with a SQL statement that is not optim...
ffmpeg is a very powerful audio and video process...
I designed and customized a navigation bar with a...
Preface The three-column layout, as the name sugg...
Table of contents 1. Install Docker 2. Install Gi...
When you browse many websites, you will find that ...
Why is it stuck? There is a premise that must be ...
Jupyter notebook is configured under the docker c...