温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python登录api实现代码怎么写

发布时间:2022-05-09 10:30:40 来源:亿速云 阅读:270 作者:iii 栏目:大数据

这篇文章主要介绍“Python登录api实现代码怎么写”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python登录api实现代码怎么写”文章能帮助大家解决问题。

一、先来看看效果

Python登录api实现代码怎么写

接口请求返回的数据:

Python登录api实现代码怎么写

二、官方登录流程图

Python登录api实现代码怎么写

三、小程序登录流程梳理:

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 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的/user/wxloginapi代码:

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')) # 将前端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实现代码怎么写”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI