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

Install Docker for Windows on Windows 10 Home Edition

0. Background Hardware: Xiaomi Notebook Air 13/In...

Differences in the hr separator between browsers

When making a web page, you sometimes use a dividi...

Example of how to configure nginx in centos server

Download the secure terminal MobaXterm_Personal F...

How to use time as a judgment condition in MySQL

Background: During the development process, we of...

How to use Nginx proxy to surf the Internet

I usually use nginx as a reverse proxy for tomcat...

How to manage large file uploads and breakpoint resume based on js

Table of contents Preface Front-end structure Bac...

Detailed explanation of the lock structure in MySQL

Mysql supports 3 types of lock structures Table-l...

Tips for optimizing MySQL SQL statements

When faced with a SQL statement that is not optim...

Centos7 installation of FFmpeg audio/video tool simple document

ffmpeg is a very powerful audio and video process...

jQuery implements navigation bar effect with expansion animation

I designed and customized a navigation bar with a...

Detailed tutorial on using Docker to build Gitlab based on CentOS8 system

Table of contents 1. Install Docker 2. Install Gi...

How to display a small icon in front of the browser URL

When you browse many websites, you will find that ...

A brief discussion on CSS3 animation jamming solutions

Why is it stuck? There is a premise that must be ...

How to configure Jupyter notebook in Docker container

Jupyter notebook is configured under the docker c...