Two-dimensional code long polling obtain landing and get basic user information

a, status = 408 operate nothing

b, status = 201 micro-letter code but no sweeping click OK

c, status = 200 and confirmed the successful scan code representative of landing

When the front end of the page load is complete before a get request, using ajax request, when status = 408, the request has been loaded, when status = 201, acquiring the user has loaded avatar request until status = 200 is just to jump to another page, remember it comes to landing plus cookie

1, when the address of the login request, the request will be landing above said three states, respectively, is determined

2, if it is confirmed that scan code landed, will return a redirect_uri address that is used to request acquiring the user information Ticket, returns the address of the page less returned request "& fun = new & version = v2 & lang = zh_CN", you have to add this can get ticket

Return ticket as follows:

<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 address, webchat / urls.py

    path('polling/', views.long_pooling, name="long_pooling"),

4, the front pages, 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. Manage the three states of judgment, 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))

Micro-channel landing page initialization, access to basic user information

Find an address for user information request

Return user information


path('index/', views.index, name="index"),

User information acquisition request background, 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,})

Note: Because the picture is loaded before you send the request, resulting in front-end status is not equal to 200 to continue polling pedding, then django of wsgi throws an error (too many requests, I do not know wsgi get the information):

self.status.split(' ',1)[0], self.bytes_sent AttributeError: 'NoneType' object has no attribute 'split'

Resolution: The page is finished loading and the like and then polling request when the beginning of the beginning url tip = 1, when status = 201 when tip = 0. , So he will not continue to poll,

Guess you like

Origin www.cnblogs.com/venvive/p/11565253.html