python代碼實現(xiàn)小程序登錄流程時序總結(jié)
官方文檔
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/login.html
小程序登錄
小程序可以通過微信官方提供的登錄能力方便地獲取微信提供的用戶身份標識,快速建立小程序內(nèi)的用戶體系。
登錄流程時序

說明:
- 調(diào)用wx.login()獲取臨時登錄憑證code,并回傳到開發(fā)者服務(wù)器。
- 調(diào)用auth.code2Session接口,換取用戶唯一標識 OpenID和會話密鑰 session_key。
之后開發(fā)者服務(wù)器可以根據(jù)用戶標識來生成自定義登錄態(tài),用于后續(xù)業(yè)務(wù)邏輯中前后端交互時識別用戶身份。
注意:
- 會話密鑰
session_key是對用戶數(shù)據(jù)進行加密簽名的密鑰。為了應用自身的數(shù)據(jù)安全,開發(fā)者服務(wù)器不應該把會話密鑰下發(fā)到小程序,也不應該對外提供這個密鑰。 - 臨時登錄憑證 code 只能使用一次
小程序的登錄總結(jié)
1 小程序端執(zhí)行wx.login()獲取code
2 將1中的code發(fā)送到后端,后端調(diào)用auth.code2Session這個接口,得到openid和session_key
3 自定義登入狀態(tài),我們生成一個key與openid和session_key相綁定。把key返回到小程序中
4 小程序端保存,然后下次請求需要登入的接口的時候,把key帶上。
案例
# app.js的onLaunch中 因為登錄是用戶感覺不到的
App({
onLaunch: function () {
let that = this
// 登錄
wx.login({
success: res => {
// 發(fā)送 res.code 到后臺換取 openId, sessionKey, unionId
console.log(res.code) //拿到code
wx.request({
url:that.globalData.baseurl+"/login/",
data:{'code':res.code},
method:'POST',
success(e){
console.log(e.data)
// wx.setStorageSync("token", e.data.data.token)
}
})
}
}),
globalData: {
userInfo: null,
baseurl:"http://127.0.0.1:8000"
}
# dango后臺中
# urls.py 路由中
path('login/', user.Login.as_view()),
# user.py中
from rest_framework.views import APIView
from rest_framework.response import Response
from api.wx import wx_login
import hashlib, time
from django.core.cache import cache
from api.models import Wxuser
class Login(APIView):
def post(self, request):
param = request.data
print(request.data)
if not param.get('code'):
return Response({"status": 1, "msg": '缺少參數(shù)'})
else:
code = param.get("code")
user_data = wx_login.get_login_info(code)
if user_data:
val = user_data['session_key'] + "&" + user_data['openid']
md5 = hashlib.md5()
md5.update(str(time.clock()).encode("utf-8"))
key = md5.hexdigest()
cache.set(key, val) # 放進內(nèi)存redis庫中,把key傳給前端當token.下次前臺帶著key就能拿到val
has_user = Wxuser.objects.filter(openid=user_data['openid']).first() # 判斷openid是否存在
if not has_user:
Wxuser.objects.create(openid=user_data['openid'])
return Response({
"status": 0,
"msg": "ok",
"data": {"token": key}
})
else:
return Response({"status": 2, "data": "無效的code"})
# models.py中:
from django.db import models
class Wxuser(models.Model):
id = models.AutoField(primary_key=True)
openid=models.CharField(max_length=255)
name = models.CharField(max_length=50)
avatar = models.CharField(max_length=200)
language = models.CharField(max_length=50)
province = models.CharField(max_length=50)
city = models.CharField(max_length=50)
country = models.CharField(max_length=50)
#gender = models.CharField(max_length=50)
creat_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
def __str__(self):
return self.openid
# settings.py中:自己注冊的微信小程序信息
AppId=""
AppSecret=""
code2Session="https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code"
# wx_login.py中:
from api.wx import settings
import requests
def get_login_info(code):
# 拼接路徑
code_url = settings.code2Session.format(settings.AppId,settings.AppSecret,code)
response = requests.get(code_url) # 返回的是json數(shù)據(jù)
json_response = response.json() # 把json數(shù)據(jù)轉(zhuǎn)換為字典
if json_response.get('session_key'):
return json_response
else:
return False
# cache緩存配置redis數(shù)據(jù)庫以上就是python代碼實現(xiàn)小程序登錄流程時序總結(jié)的詳細內(nèi)容,更多關(guān)于python小程序登錄時序總結(jié)的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Blueprint實現(xiàn)路由分組及Flask中session的使用詳解
這篇文章主要為大家介紹了Blueprint實現(xiàn)路由分組及Flask中session的使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11
python網(wǎng)絡(luò)編程學習筆記(九):數(shù)據(jù)庫客戶端 DB-API
這篇文章主要介紹了python 數(shù)據(jù)庫客戶端 DB-API的相關(guān)資料,需要的朋友可以參考下2014-06-06
arcgis使用Python腳本進行批量截圖功能實現(xiàn)
最近公司數(shù)據(jù)部那邊有個需求,需要結(jié)合矢量數(shù)據(jù)和影像數(shù)據(jù),進行批量截圖,并且截圖中只能有一個圖斑,還要添加上相應的水印,這篇文章主要介紹了arcgis使用Python腳本進行批量截圖,需要的朋友可以參考下2023-01-01
Python3中zip()函數(shù)知識點小結(jié)
本文主要介紹了Python3中zip()函數(shù)知識點小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

