a、status=408什么也沒有操作
b、status=201微信掃了碼但是沒有點擊確認
c、status=200代表掃碼成功並確認登陸
前端是當頁面加載完成才弄下一次請求,利用ajax請求,當status=408時,一直在加載請求,當status=201時,獲取用戶頭像一直加載請求,直到status=200才跳轉到另一個頁面,涉及到登陸記得加cookie
1、請求登陸的地址,請求登陸的 時候會有上面說的三種狀態,分別判斷
2、如果是確認掃碼登陸了,會返回一個redirect_uri地址,這個地址用來請求獲取用戶的信息ticket,返回的地址與頁面請求返回的少了"&fun=new&version=v2&lang=zh_CN",得加上這個才能獲取ticket
返回的ticket如下:
<error>
<ret>0</ret>
<message></message> <skey>@crypt_dd043c47_d6303d6aed797c295a21960d9c2d729c</ske y> <wxsid>hYiHcYEqVMC4Kim9</wxsid> <wxuin>795592819</wxuin> <pass_ticket>aNUg%2B%2FHFbBavV3w9ndTBh8hjSErIhrkBBGVl0PV F%2B9lQhFi5KtGYjlWCv2%2FoBrQf</pass_ticket>
<isgrayscale>1</isgrayscale>
</error>
3、url地址,webchat/urls.py
path('polling/', views.long_pooling, name="long_pooling"),
4、前端頁面,templates/webch.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wechat</title>
</head>
<body>
<div style="width: 300px;margin: 0 auto;">
<img id="qcode" style="width: 300px;height: 300px;" src="https://login.weixin.qq.com/qrcode/{{code}}"/>
</div>
<script src="/static/js/jquery.min.js"></script>
<!--<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>-->
<script>
//頁面加載完在請求polling()
$(function () {
polling();
})
function polling() {
$.ajax({
url:'/polling/',
type:"GET",
dataType:"json",
success:function (arg) {
if(arg.status == 408){
polling()
}else if(arg.status == 201){
//獲取圖片接着發
$("#qcode").attr('src',arg.data);
polling()
}else{
location.href="/index/"
}
}
})
}
</script>
</body>
</html>
5、后台登陸的三種狀態判斷,web/views.py
# Create your views here.
from django.shortcuts import render
from django.shortcuts import HttpResponse
import requests
import re
import time
import json
from bs4 import BeautifulSoup
VERIFY_TIME =None
verifi_uuid =None
LOGIN_COOKIE_DICT = {}
TICKET_COOKIE_DICT= {}
TICKET_DATA_DICT = {}
TIPS=1
def long_pooling(request):
"""二維碼長輪詢獲取登陸"""
"""
1、status=408什么也沒有操作
2、status=201微信掃了碼但是沒有操作
3、status=200代表掃碼成功並確認登陸
"""
#返回的json狀態和數據
ret = {"status":408,"data":None}
#二維碼長輪詢url
try:
#TIPS=0是沒有過於頻繁的輪詢.剛開始是為1
global TIPS
#請求的地址,uuid=verifi_uuid,后面那個值是隨機生產時間戳
base_pooling_url = "https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip={1}&r=-1322669031&={2}"
pooling_url= base_pooling_url.format(verifi_uuid,TIPS,VERIFY_TIME)
reponse_login = requests.get(url=pooling_url)
#print("pooling_reponse.text",pooling_reponse.text)
#掃碼一直沒有點擊登陸,狀態碼是201,獲取返回頭像數據
if "window.code=201" in reponse_login.text:
#獲取頭像圖片地址
TIPS = 0
#獲取圖片地址
avatar = re.findall("userAvatar = '(.*)';",reponse_login.text)[0]
#print("avatar",avatar)
#更新狀態和內容
ret["status"] = 201
ret["data"] = avatar
#print("reponse_login",reponse_login.text)
elif "window.code=200" in reponse_login.text:
#登陸時候獲取的cookies
LOGIN_COOKIE_DICT.update(reponse_login.cookies.get_dict())
#登陸成功返回一個重定向地址,這個地址請求可以獲取用戶信息ticket
redirect_uri = re.findall('redirect_uri="(.*)";',reponse_login.text)[0]
redirect_uri+="&fun=new&version=v2&lang=zh_CN"
#print("redirect_uri",redirect_uri)
#獲取ticket和添加ticket的cookie
reponse_ticket = requests.get(url=redirect_uri,cookies=LOGIN_COOKIE_DICT)
TICKET_COOKIE_DICT.update(reponse_ticket.cookies.get_dict())
#print("reponse_ticket:",reponse_ticket.text)
#找出ticket里的值
soup=BeautifulSoup(reponse_ticket.text,"html.parser")
for tag in soup.find():
#print(tag.name,tag.string)
#把數據存入到dict中,為了下次請求的時候使用
TICKET_DATA_DICT[tag.name]=tag.string
#print("TICKET_DATA_DICT",TICKET_DATA_DICT)
ret["status"] = 200
except Exception as e:
print(e)
return HttpResponse(json.dumps(ret))
微信登陸的頁面初始化,獲取用戶的基本信息
找到獲取用戶信息請求地址
返回的用戶信息
path('index/', views.index, name="index"),
后台的請求獲取用戶信息,web/views.py
def index(request):
"""微信登陸的頁面初始化,獲取用戶的基本信息"""
user_init_url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=-1332226764"
payload_data = {
"DeviceID":"e379444626462097",
"Sid":TICKET_DATA_DICT["wxsid"],
"Skey":TICKET_DATA_DICT["skey"],
"Uin":TICKET_DATA_DICT["wxuin"]
}
cookie_all = {}
#因為不知道用哪個cookie所以上面兩個都給加上了
cookie_all.update(LOGIN_COOKIE_DICT)
cookie_all.update(TICKET_COOKIE_DICT)
#返回的內容是用戶的信息
reponse_init=requests.post(url=user_init_url,json=payload_data,cookies=cookie_all)
print("reponse_init",reponse_init)
return render(request,"index.html",{"data":reponse_init.text,})
注:因為之前是圖片加載完成就發送請求,造成前端status不等於200就不斷輪詢pedding,然后使django的wsgi引發錯誤(太多的請求,wsgi不知獲取那個信息):
self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split'
解決:是等頁面加載完再輪詢,當剛開始請求時候剛開始url的tip=1,當status=201的時候tip=0。,這樣他就不會不斷的輪詢,