flask 微信扫码登录

flask 微信扫码登录flask微信扫码登录app和路由配置代码importreimporttimeimportrequestsfromflaskimportFlask,render_template,session,jsonifyapp=Flask(__name__)app.secret_key=’1231sdfasdf’frombs4importBeautifu…

大家好,欢迎来到IT知识分享网。

flask 微信扫码登录

app和路由配置代码

import re
import time
import requests
from flask import Flask, render_template, session, jsonify

app = Flask(__name__)
app.secret_key = '1231sdfasdf'

from bs4 import BeautifulSoup


def xml_parse(text):
    result = { 
   }
    soup = BeautifulSoup(text, 'html.parser')
    tag_list = soup.find(name='error').find_all()
    for tag in tag_list:
        result[tag.name] = tag.text
    return result


@app.route('/login')
def login():
    ctime = int(time.time() * 1000)
    qcode_url = "https://login.wx2.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_={0}".format(
        ctime)

    rep = requests.get(
        url=qcode_url
    )
    # print(rep.text) # window.QRLogin.code = 200; window.QRLogin.uuid = "gb8UuMBZyA==";
    qcode = re.findall('uuid = "(.*)";', rep.text)[0]
    session['qcode'] = qcode
    return render_template('login.html', qcode=qcode)


@app.route('/check/login')
def check_login():
    qcode = session['qcode']
    ctime = int(time.time() * 1000)
    # https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=oeq3xdRFig==&tip=0&r=-412057997&_=1546600257051
    # https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=oa95cvIS5w==&tip=0&r=-413943228&_=1546602155746
    check_login_url = 'https://login.wx2.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip=0&r=-413943228&_={1}'.format(
        qcode, ctime)
    rep = requests.get(
        url=check_login_url
    )
    result = { 
   'code': 408}

    if 'window.code=408' in rep.text:
        # 用户未扫码
        result['code'] = 408
    elif 'window.code=201' in rep.text:
        # 用户扫码,获取头像
        result['code'] = 201
        result['avatar'] = re.findall("window.userAvatar = '(.*)';", rep.text)[0]
    elif 'window.code=200' in rep.text:
        # 用户确认登录
        redirect_uri = re.findall('window.redirect_uri="(.*)";', rep.text)[0]
        print(redirect_uri)

        # https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=A_pgPh0SjvyHWTDEF3kce2Wg@qrticket_0&uuid=wbewGl1rwQ==&lang=zh_CN&scan=1546599481&fun=new&version=v2
        # https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=A_pgPh0SjvyHWTDEF3kce2Wg@qrticket_0&uuid=wbewGl1rwQ==&lang=zh_CN&scan=15

   
        redirect_uri = redirect_uri + "&fun=new&version=v2"
        ru = requests.get(url=redirect_uri)

        # <error><ret>0</ret><message></message><skey>@crypt_2272b9c9_c4a1df2d806c0b32bc7f8b678b907bd6</skey><wxsid>hKPtRPRAn0yZWwZW</wxsid><wxuin>1440810436</wxuin><pass_ticket>%2BuiXaDx68luSpK5djbIrAqKoVLi4vSlxTg7dQe4105vIaFK93ORlG1kPgO5uQsSi</pass_ticket><isgrayscale>1</isgrayscale></error>
        ticket_dict = xml_parse(ru.text)
        # print(ticket_dict)
        session['ticket_dict'] = ticket_dict
        result['code'] = 200

    return jsonify(result)


@app.route('/index')
def index():
    pass_ticket = session['ticket_dict']['pass_ticket']
    init_url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=-412030554&lang=zh_CN&pass_ticket={0}".format(
        pass_ticket)

    rep = requests.post(
        url=init_url,
        json={ 
   
            'BaseRequest': { 
   
                'DeviceID': "e572672200373583",
                'Sid': session['ticket_dict']['wxsid'],
                'Skey': session['ticket_dict']['skey'],
                # 'Uin': session['ticket_dict']['wxuin'],
                'Uin': "1440810436",

            }
        }
    )
    rep.encoding = 'utf-8'

    init_user_dict = rep.json()
    print(init_user_dict)

    return render_template('index.html', init_user_dict=init_user_dict)


if __name__ == '__main__':
    app.run()

index.html页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>欢迎使用Web微信:{ 
   { 
   init_user_dict.User.NickName}}</h1>

<h3>最近联系人</h3>
<ul>
    { 
   % for row in init_user_dict.ContactList %}
    <li>{ 
   { 
   row.NickName}}</li>
    { 
   % endfor %}
    <li><a href="#">查看所有联系人</a></li>
</ul>

<h3>最近公众号</h3>
{ 
   % for item in init_user_dict.MPSubscribeMsgList %}
<div>
    <h3>{ 
   { 
   item.NickName}}</h3>
    <ul>
        { 
   % for msg in item.MPArticleList %}
        <li><a href="{ 
   { msg.Url }}">{ 
   { 
   msg.Title}}</a></li>
        { 
   % endfor %}
    </ul>
</div>
{ 
   % endfor %}


</body>
</html>

login.html页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
    <div style="width: 200px;margin: 100px auto;background-color:cadetblue" >
        <h2 style="text-align: center;color:white;padding-top: 15px">微信登录</h2>
        <img id="userAvatar" style="width: 200px;height: 200px;" src="https://login.weixin.qq.com/qrcode/{ 
   {qcode}}" alt="">
    </div>

    <script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
    <script>
        $(function () { 
   
            checkLogin();
        });
        function checkLogin() { 
   
            $.ajax({ 
   
                url:'{ 
   { url_for('check_login') }}',
                method:'GET',
                dataType:'json',
                success:function (arg) { 
   
                    console.log(arg);
                    checkLogin();
                    if(arg.code === 408){ 
   
                        checkLogin();
                    }else if(arg.code === 201){ 
   
                        $('#userAvatar').attr('src',arg.avatar);
                        checkLogin();
                    }else if(arg.code === 200){ 
   
                        location.href = "{ 
   { url_for('index') }}"
                    }
                }
            })
        }
    </script>
</body>
</html>

显示效果

登录界面

C:\Users\john\AppData\Roaming\Typora\typora-user-images\1546668183423.png

获取微信登录信息

1546667297336
在这里插入图片描述

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/22060.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信