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 achieve WeChat Mini Programs's login to api by Python

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to achieve WeChat Mini Programs login api by Python". 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 "how to achieve Python WeChat Mini Programs login api" bar!

First, let's see the effect.

Data returned by API request:

II. Official login flow chart

Third, sort out the login process of Mini Program:

1. Call wx.login on Mini Program

2. Judge whether the user is authorized or not

3. Mini Program end accesses wx.getuserinfo

4. Js code on Mini Program:

Wx.login ({success: resp = > {/ / send res.code to the background for openid, sessionkey, unionid console.log (resp); var that = this; / / get user information wx.getsetting ({success: res = > {if (res.authsetting ['scope.userinfo']) {/ / has been authorized. You can call getuserinfo directly to get the avatar nickname without popping up 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 to be executed after the request is completed})})}})

5. The backend server accesses code2session and uses the api API code2session to obtain the login status session_key, openid and unionid of Wechat users that they really need.

6. The backend server verifies the user information and decrypts the encrypteddata

After logging in, WeChat Mini Programs obtains session_key and returns the data of encrypteddata,iv. The decrypted encrypteddata contains the user's information. 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 decrypted file-wxbizdatacrypt.py

From crypto.cipher import aes usually encounters a modulenotfounderror:no module named "crypto" error.

(1) execute pip3 install pycryptodome

(2) if the module is still not available, check the virtual environment directory lib--site-package to see if there is a crypto folder. Then you should see that there is a crypto folder and rename it to crypto.

Import base64import jsonfrom crypto.cipher import aesclass 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:])]

8. / user/wxloginapi code of flask:

Import json,requestsfrom wxbizdatacrypt import wxbizdatacryptfrom 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' # developer's appid appsecret for WeChat Mini Programs =' appsecret' # developer's appsecret code for WeChat Mini Programs = data ['platcode'] # temporary login credential for Wechat from front-end post code 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 api resdata = response_data.json () openid = resdata ['openid'] # get the user's openid session_key = resdata [' session_key'] # get the user's session key session_key pc = wxbizdatacrypt (appid, session_key) # decrypt the user information userinfo = pc.decrypt (encrypteddata) Iv) # get user information print (userinfo)''the following section determines whether a user exists in the database to add or return a custom login state (if the user does not exist, add If the user exists, return the user information)-omit-I will omit this part. Return json.dumps ({"code": 200, "msg": "login succeeded", "userinfo": userinfo}, indent=4, sort_keys=true, default=str, ensure_ascii=false) in the database. I believe that everyone has a deeper understanding of "how to achieve WeChat Mini Programs login api in Python", so you might as well do it in practice. 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: 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