Python Flask WeChat applet login process and login api implementation code

Python Flask WeChat applet login process and login api implementation code

1. Let’s take a look at the effect first

insert image description here

Data returned by the interface request:

insert image description here

2. Official Login Flowchart

insert image description here

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 session_key , openid and unionid of the WeChat user that is actually needed through the code2Session API interface.

6. The backend server verifies the user information and decrypts encryptedData After logging in to the WeChat applet and obtaining the session_key, the encryptedData and iv data are returned. The encryptedData contains the user information after decryption. The decrypted json format is as follows:

{
 "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


from Crypto.Cipher import AES This will usually result in ModuleNotFoundError:No module named "Crypto" error. (1) Execute pip3 install pycryptodome
(2) If the prompt still says that the module is not available, check whether there is a Crypto folder in the virtual environment directory Lib—-site-package . You should see a crypto folder and rename it to Crypto .

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 /user/wxlogin api code:

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:
  • Python implements WeChat applet user login and template push
  • Python implements registration and login applet functions
  • Python implements multiple payment methods for WeChat applet
  • Five Python mini programs with code
  • Python code to implement the timing summary of the applet login process

<<:  Vue implements three-level navigation display and hiding

>>:  mysql: [ERROR] unknown option '--skip-grant-tables'

Recommend

A brief analysis of the four import methods and priorities in CSS

First: 4 ways to introduce CSS There are four way...

Vue custom bullet box effect (confirmation box, prompt box)

This article example shares the specific code of ...

Sharing tips on using vue element and nuxt

1. Element time selection submission format conve...

How to quickly build an LNMP environment with Docker (latest)

Preface Tip: Here you can add the approximate con...

Nexus private server construction principle and tutorial analysis

one. Why build a Nexus private server? All develo...

CSS3 to achieve dynamic background gradient effect

Learning CSS3 is more about getting familiar with...

Vue.js Textbox with Dropdown component

A Textbox with Dropdown allows users to select an...

DOM operation implementation in react

Table of contents Previous words Usage scenarios ...

Detailed explanation of the functions and usage of MySQL common storage engines

This article uses examples to illustrate the func...

How to use ssh tunnel to connect to mysql server

Preface In some cases, we only know the intranet ...

Solution to the problem of passing values ​​between html pages

The first time I used the essay, I felt quite awkw...