In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "how to write Python login api implementation code". Xiaobian shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "how to write Python login api implementation code" can help you solve the problem.
First, let's see the effect
Data returned by interface request:
二、官方登录流程图
三、小程序登录流程梳理:
1、小程序端调用wx.login
2、判断用户是否授权
3、小程序端访问 wx.getuserinfo
4、小程序端js代码:
wx.login({ success: resp => { // 发送 res.code 到后台换取 openid, sessionkey, unionid console.log(resp); var that = this; // 获取用户信息 wx.getsetting({ success: res => { if (res.authsetting['scope.userinfo']) { // 已经授权,可以直接调用 getuserinfo 获取头像昵称,不会弹框 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) //设置本地缓存 }, fail: function (err) { },//请求失败 complete: function () { }//请求完成后执行的函数 }) } }) } } }) } })
5、后端服务器访问code2session,通过code2session这个api接口来获取真正需要的微信用户的登录态session_key和 openid 和 unionid
6、后端服务器校验用户信息,对encrypteddata 解密
微信小程序登录后获得session_key后,返回了encrypteddata,iv的数据,其中encrypteddata解密后包含了用户的信息,解密后的json格式如下:
{ "openid": "openid", "nickname": "nickname", "gender": gender, "city": "city", "province": "province", "country": "country", "avatarurl": "avatarurl", "unionid": "unionid", "watermark": { "appid":"appid", "timestamp":timestamp }}
7、新建解密文件--wxbizdatacrypt.py
from crypto.cipher import aes这边一般会遇到modulenotfounderror:no module named "crypto"错误
(1)执行pip3 install pycryptodome
(2)如果还是提示没有该模块,那就虚拟环境目录lib--site-package中查看是否有crypto文件夹,这时你应该看到有crypto文件夹,将其重命名为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(s[len(s)-1:])]
8、flask的/user/wxloginapi代码:
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')) # 将前端json数据转为字典 appid = 'appid' # 开发者关于微信小程序的appid appsecret = 'appsecret' # 开发者关于微信小程序的appsecret code = data['platcode'] # 前端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) # 向api发起get请求 resdata = response_data.json() openid = resdata ['openid'] # 得到用户关于当前小程序的openid session_key = resdata ['session_key'] # 得到用户关于当前小程序的会话密钥session_key pc = wxbizdatacrypt(appid, session_key) #对用户信息进行解密 userinfo = pc.decrypt(encrypteddata, iv) #获得用户信息 print(userinfo) ''' 下面部分是通过判断数据库中用户是否存在来确定添加或返回自定义登录态(若用户不存在则添加;若用户存在,返回用户信息) --------略略略略略略略略略------------- 这部分我就省略啦,数据库中对用户进行操作 ''' return json.dumps({"code": 200, "msg": "登录成功","userinfo":userinfo}, indent=4, sort_keys=true, default=str, ensure_ascii=false)关于"Python登录api实现代码怎么写"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注行业资讯频道,小编每天都会为大家更新不同的知识点。
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.