python---web微信开发
Posted 山上有风景
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python---web微信开发相关的知识,希望对你有一定的参考价值。
一:轮询,长轮询,WebSocket了解
轮询:
在前端,设置时间内,一直向后端发送请求。
例如:使用setInterval方法设置定时器,一秒向后端发送一次请求,去主动获取数据,进行更新
由于前端一直请求,后端压力太大。而且当没有数据更新,前端一直去请求,太浪费了,没必要。
代码简单
长轮询:
在轮询的基础上,加以改造。Http请求到来,若是不主动close或者return,则连接会一直存在。但是不要让这个时间太长,会占用太多资源
例如:当前端发送请求,后端拿到后,不去关闭,而是等待一段时间,在这段时间内若是有数据到达,立刻返回,否则直到等待时间结束。
然后返回给前端,前端马上又发起一次请求......
消息是实时获取。
WebSocket:
http是单向请求,客户端去服务端获取数据。服务端不能主动推送消息。
而websocket类似于socket,可以实现双向发送,
实现当数据更新,可以主动推送
二:web微信流程介绍
三:微信登录开发
from django.shortcuts import render,HttpResponse from bs4 import BeautifulSoup import requests import time,re,json CTIME = None #用于保存全局时间戳 QCODE = None #当我们访问二维码时,会产生一个UUID,我们将其存放为全局 TIP = 1 #url中的一个参数tip,当其为1:代表我们还没有扫描二维码,当其为0:扫描了二维码
登录视图login,用于显示二维码
def login(request): global CTIME global QCODE CTIME = int(time.time()) data = { \'appid\':\'wx782c26e4c19acffb\', \'fun\':\'new\', \'lang\':\'zh_CN\', \'_\':CTIME } response = requests.get( url="https://login.wx.qq.com/jslogin", params=data ) pat_res = re.findall(\'uuid = "(.*)";\',response.text) #正则匹配UUID QCODE = pat_res[0] return render(request,"login.html",{\'qcode\':QCODE})
check_login用于检测登录状态:408未扫描,201扫描二维码但是未登录,200点击登录
def check_login(request): global TIP ret = {\'code\':408,\'data\':None} data = { \'loginicon\':"true", \'uuid\':QCODE, \'tip\':TIP, \'r\':\'-577317906\', \'_\':int(time.time()) } r1 = requests.get( url=\'https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login\', params=data ) if \'window.code=408\' in r1.text: print("无人扫描") return HttpResponse(json.dumps(ret)) elif \'window.code=201\' in r1.text: ret[\'code\'] = 201 pat_ret = re.findall("window.userAvatar = \'(.*)\';",r1.text)[0] ret[\'data\'] = pat_ret TIP = 0 return HttpResponse(json.dumps(ret)) elif \'window.code=200;\' in r1.text: ret[\'code\'] = 200 redirect_url = re.findall(\'window.redirect_uri="(.*)";\',r1.text)[0] reponse = requests.get( url=redirect_url+"&fun=new&version=v2" #url不够完整,需要我们完善 ) # print(reponse.text) #<error><ret>0</ret><message></message><skey>@crypt_7358fe11_af06754907ad9c216768337d80cf0ce7</skey><wxsid>icUySQoySDi2OZFK</wxsid><wxuin>2821071261</wxuin><pass_ticket>IWScm1SE%2BGQ%2BNEaghUBCxbF3xPJSzqXUGTO6BYh3TBEGlw8Wa7qETkA9EEAUudYU</pass_ticket><isgrayscale>1</isgrayscale></error> soup = BeautifulSoup(reponse.text,"lxml") info_dict = {} for tag in soup.find("error").children: info_dict[tag.name]=tag.get_text() get_user_info_url = \'https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=-613135321&pass_ticket=\'+info_dict[\'pass_ticket\'] get_user_info_form = { \'BaseRequest\': { \'DeviceID\':"e055319847811019", \'Sid\':info_dict[\'wxsid\'], \'Skey\':info_dict[\'skey\'], \'Uin\':info_dict[\'wxuin\'] } } reponse2 = requests.post( #获取的是用户信息,最近联系人,公众号,自己信息 url=get_user_info_url, json=get_user_info_form, #注意这里使用的是json,post不允许传送字典 ) reponse2.encoding = "utf-8" print(reponse2.text) return HttpResponse("OK")
\'\'\' 新请求 GET 获取跳转地址redirect_uri https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login? loginicon=true &uuid=QfsKELYXow== &tip=0 &r=-613406501 &_=1529621492415 --------------------------------------------------------- window.code=200; window.redirect_uri=" https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage? ticket=ASWg1dxC1oWVbJtZH8V-HhlB@qrticket_0 &uuid=QfsKELYXow== &lang=zh_CN &scan=1529621533"; 新请求 GET 获取凭证pass_ticket 服务端开始设置了cookie,说明在后面的请求中需要携带cookie https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage? ticket=ASWg1dxC1oWVbJtZH8V-HhlB@qrticket_0 &uuid=QfsKELYXow== &lang=zh_CN &scan=1529621533 &fun=new &version=v2 ----------------------------------------------------------------- <error> <ret>0</ret> <message></message> <skey>@crypt_7358fe11_ea821d506c39f7d75a3e83b4233caab4</skey> <wxsid>qUJZlkBIWQ0130QI</wxsid> <wxuin>2821071261</wxuin> <pass_ticket>xNiKeCBgFkMBfEK8oOK3Gp9qj%2F1HfLpcfPrDwGv3A4nltKskVqoxkECrVYEN9eJJ</pass_ticket> <isgrayscale>1</isgrayscale> </error> 新请求:获取用户所有信息,最近联系人和公众号 POST 需要携带数据,数据来自于上面凭证中 https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit? r=-613135321 &pass_ticket=xNiKeCBgFkMBfEK8oOK3Gp9qj%252F1HfLpcfPrDwGv3A4nltKskVqoxkECrVYEN9eJJ 数据 { BaseRequest: { DeviceID:"e055319847811019" Sid:"pY7nfHplUAsBOINz" Skey:"@crypt_7358fe11_e0ae163bd19650bea336df66837e9f7a" Uin:"2821071261" } } -------------------------------------------------------------------- { "BaseResponse": { "Ret": 0, "ErrMsg": "" } , "Count": 9, "ContactList": [{ "Uin": 0, "UserName": "filehelper", "NickName": "æ–‡ä»¶ä¼ è¾“åŠ©æ‰‹", "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=660872310&username=filehelper&skey=@crypt_7358fe11_ea821d506c39f7d75a3e83b4233caab4", "ContactFlag": 2, "MemberCount": 0, "MemberList": [], "RemarkName": "", "HideInputBarFlag": 0, "Sex": 0, "Signature": "", "VerifyFlag": 0, "OwnerUin": 0, "PYInitial": "WJCSZS", "PYQuanPin": "wenjianchuanshuzhushou", "RemarkPYInitial": "", "RemarkPYQuanPin": "", "StarFriend": 0, "AppAccountFlag": 0, "Statues": 0, "AttrStatus": 0, "Province": "", "City": "", "Alias": "", "SnsFlag": 0, "UniFriend": 0, "DisplayName": "", "ChatRoomId": 0, "KeyWord": "fil", "EncryChatRoomId": "", "IsOwner": 0 },还有其他的] } 新请求 https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxinit? r=-613135321 &pass_ticket=xNiKeCBgFkMBfEK8oOK3Gp9qj%252F1HfLpcfPrDwGv3A4nltKskVqoxkECrVYEN9eJJ 新请求 GET 获取所有联系人和公众号 https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact? lang=zh_CN &pass_ticket=gWbCT8vTjFeFKXDvfJZ6DtMtHo5d8zzhtLgLoybILn7eeTNSMI4BErA7e9otuPXQ &r=1529642330650 &seq=0 &skey=@crypt_7358fe11_9dc260b8cffb962a3e475ca50e7813c9 ----------------------------------------------------------------------------- { "BaseResponse": { "Ret": 0, "ErrMsg": "" } , "MemberCount": 162, "MemberList": [{ "Uin": 0, "UserName": "@39ef4d4197e9a7388e41fc9de150b3e28bf125082f1e442822814dec4803c6a0", "NickName": "å®é™è‡´è¿œ", "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=0&username=@39ef4d4197e9a7388e41fc9de150b3e28bf125082f1e442822814dec4803c6a0&skey=@crypt_7358fe11_9dc260b8cffb962a3e475ca50e7813c9", "ContactFlag": 1, "MemberCount": 0, "MemberList": [], "RemarkName": "", "HideInputBarFlag": 0, "Sex": 1, "Signature": "凶巴巴呛è´è´", "VerifyFlag": 0, "OwnerUin": 0, "PYInitial": "NJZY", "PYQuanPin": "ningjingzhiyuan", "RemarkPYInitial": "", "RemarkPYQuanPin": "", "StarFriend": 0, "AppAccountFlag": 0, "Statues": 0, "AttrStatus": 4197, "Province": "æ²³å—", "City": "郑州", "Alias": "", "SnsFlag": 17, "UniFriend": 0, "DisplayName": "", "ChatRoomId": 0, "KeyWord": "", "EncryChatRoomId": "", "IsOwner": 0 }, 还有其他 ] \'\'\'
前端代码:显示二维码和头像
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <img id="qrcode" style="width: 340px;height: 340px;" src="https://login.weixin.qq.com/qrcode/{{ qcode }}" alt=""> </body> </html> <script src="/static/jquery.js"></script> <script> $(function(){ checkLogin(); }) function checkLogin() { $.ajax({ url:\'/check-login.html\', type:\'GET\', dataType:"json", success:function(data){ console.log(data.code); if (data.code==408){ checkLogin(); } else if(data.code==201){ $("#qrcode").attr(\'src\',data.data) checkLogin(); } } }) } </script>
测试返回的最近联系人和公众号信息
user_dict = {} for item in user_dict.items(): print(item) for item in user_dict[\'ContactList\']: #最近联系人 print(item[\'PYQuanPin\'],item[\'NickName\']) for item in user_dict[\'MPSubscribeMsgList\']: #公众号和推送消息 print(item[\'UserName\'],item[\'NickName\']) for item2 in item[\'MPArticleList\']: print(item2[\'Title\'],item2[\'Cover\'],item2[\'Digest\'],item2[\'Url\'])
(\'ClientVersion\', 637929271) (\'GrayScale\', 1) (\'Count\', 10) (\'SystemTime\', 1529661118) (\'MPSubscribeMsgList:公众号列表,含有文章推送等信息\', [{\'UserName\': \'@393d71e59f81ac2feca148e8e269c0df\', \'MPArticleList\': [{\'Title\': \'\', \'Digest\': \'\', \'Url\': \'\', \'Cover\': \'图片\'}, ], \'MPArticleCount\': 2, \'Time\': 1529651105, \'NickName\': \'人工智能头条\'},]) (\'ChatSet\', \'filehelper,@@7c7137978e7349eac97453fa2adc290df295eaba3e7981e07ff85111f94a403c,weixin,@0fdf14d27dc0b2d34d013329ec498aae6284dbc340bdfbd8741227a72b1b3fa4,@393d71e59f81ac2feca148e8e269c0df,@@4d7d0c68e8445a6d69a5e3a2415c57c8f46858724cfdef8618b5790094e5de37,@@6b45638d8a8394a5bea103bd55ef49ce69dad73b8eda94dd5f63a126ec0e6ee4,@@d6c45082c0686e0cef729f3cb20db704b381b2aef67fe0a8a82151869220c8ef,@@03e7d8c59c30bb81dc0f2dc683b8e7a6f4a707f2aac6655c6e5036c349a96fe3,@02bf3be3c826bc38d4461d3ee52704e8,\') (\'MPSubscribeMsgCount:最近推送的公众号数目\', 2) (\'BaseResponse\', {\'ErrMsg\': \'\', \'Ret\': 0}) (\'SKey\', \'@crypt_7358fe11_08012eadffc70f5c3189f802236830be\') (\'ClickReportInterval\', 600000) (\'InviteStartCount\', 40) (\'User:用户自己的信息\', {\'VerifyFlag\': 0, \'HeadImgFlag\': 1, \'Uin\': 2821071261, \'NickName\': \'宁静致远\', \'AppAccountFlag\': 0, \'UserName\': \'@c959c389ab390d9f71d3f528f5a4ee1e81d6c8cd4aaf48d8b1f0077073660c5c\', \'HeadImgUrl\': \'/cgi-bin/mmwebwx-bin/webwxgeticon?seq=1753775271&username=@c959c389ab390d9f71d3f528f5a4ee1e81d6c8cd4aaf48d8b1f0077073660c5c&skey=@crypt_7358fe11_08012eadffc70f5c3189f802236830be\', \'ContactFlag\': 0, \'RemarkPYInitial\': \'\', \'SnsFlag\': 17, \'PYQuanPin\': \'\', \'WebWxPluginSwitch\': 0, \'HideInputBarFlag\': 0, \'RemarkPYQuanPin\': \'\', \'Signature\': \'凶巴巴呛贝贝\', \'Sex\': 1, \'StarFriend\': 0, \'PYInitial\': \'\', \'RemarkName\': \'\'}) (\'ContactList:最近联系人信息\', [ {\'VerifyFlag\': 0, \'Uin\': 0, \'Signature\': \'\', \'AppAccountFlag\': 0, \'HeadImgUrl\': \'/cgi-bin/mmwebwx-bin/webwxgeticon?seq=660872310&username=filehelper&skey=@crypt_7358fe11_08012eadffc70f5c3189f802236830be\', \'PYInitial\': \'WJCSZS\', \'Province\': \'\', \'PYQuanPin\': \'wenjianchuanshuzhushou\', \'DisplayName\': \'\', \'RemarkName\': \'\', \'IsOwner\': 0, \'Sex\': 0, \'EncryChatRoomId\': \'\', \'KeyWord\': \'fil\', \'City\': \'\', \'ChatRoomId\': 0, \'RemarkPYQuanPin\': \'\', \'Alias\': 微信小程序开发--模板(template)使用,数据加载,点击交互