溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python登錄api實現(xiàn)代碼怎么寫

發(fā)布時間:2022-05-09 10:30:40 來源:億速云 閱讀:280 作者:iii 欄目:大數(shù)據(jù)

這篇文章主要介紹“Python登錄api實現(xiàn)代碼怎么寫”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Python登錄api實現(xiàn)代碼怎么寫”文章能幫助大家解決問題。

一、先來看看效果

Python登錄api實現(xiàn)代碼怎么寫

接口請求返回的數(shù)據(jù):

Python登錄api實現(xiàn)代碼怎么寫

二、官方登錄流程圖

Python登錄api實現(xiàn)代碼怎么寫

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

1、小程序端調(diào)用wx.login

2、判斷用戶是否授權

3、小程序端訪問 wx.getuserinfo

4、小程序端js代碼:

wx.login({
 success: resp => {
 // 發(fā)送 res.code 到后臺換取 openid, sessionkey, unionid
 console.log(resp);
 var that = this;
 // 獲取用戶信息
 wx.getsetting({
 success: res => {
 if (res.authsetting['scope.userinfo']) {
 // 已經(jīng)授權,可以直接調(diào)用 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 () { }//請求完成后執(zhí)行的函數(shù)
			 })
 }
 })
 } 
 }
 })
 }
 })

5、后端服務器訪問code2session,通過code2session這個api接口來獲取真正需要的微信用戶的登錄態(tài)session_key和 openid 和 unionid

6、后端服務器校驗用戶信息,對encrypteddata 解密
微信小程序登錄后獲得session_key后,返回了encrypteddata,iv的數(shù)據(jù),其中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)執(zhí)行pip3 install pycryptodome
(2)如果還是提示沒有該模塊,那就虛擬環(huán)境目錄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數(shù)據(jù)轉(zhuǎn)為字典
 appid = 'appid' # 開發(fā)者關于微信小程序的appid
 appsecret = 'appsecret' # 開發(fā)者關于微信小程序的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發(fā)起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)
 '''
 下面部分是通過判斷數(shù)據(jù)庫中用戶是否存在來確定添加或返回自定義登錄態(tài)(若用戶不存在則添加;若用戶存在,返回用戶信息)
 
 --------略略略略略略略略略-------------
 
 這部分我就省略啦,數(shù)據(jù)庫中對用戶進行操作
 '''
 
 return json.dumps
({
"code": 200, "msg": "登錄成功","userinfo":userinfo}, indent=4, sort_keys=true, default=str, ensure_ascii=false)

關于“Python登錄api實現(xiàn)代碼怎么寫”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識,可以關注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI