第五步: 获取联系人信息---day4代码
settings.py
"""Django settings for weixin project.Generated by 'django-admin startproject' using Django 2.0.1.For more information on this file, seehttps://docs.djangoproject.com/en/2.0/topics/settings/For the full list of settings and their values, seehttps://docs.djangoproject.com/en/2.0/ref/settings/"""import os# Build paths inside the project like this: os.path.join(BASE_DIR, ...)BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))# Quick-start development settings - unsuitable for production# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/# SECURITY WARNING: keep the secret key used in production secret!SECRET_KEY = '*g4b=9ct3o#*1pr0o2$h+p$eb!czq!)83u933x8$(n7uj++!f%'# SECURITY WARNING: don't run with debug turned on in production!DEBUG = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'App.apps.AppConfig',]MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',]ROOT_URLCONF = 'weixin.urls'TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]WSGI_APPLICATION = 'weixin.wsgi.application'# Database# https://docs.djangoproject.com/en/2.0/ref/settings/#databasesDATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }}# Password validation# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validatorsAUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', },]# Internationalization# https://docs.djangoproject.com/en/2.0/topics/i18n/LANGUAGE_CODE = 'en-us'TIME_ZONE = 'UTC'USE_I18N = TrueUSE_L10N = TrueUSE_TZ = True# Static files (CSS, JavaScript, Images)# https://docs.djangoproject.com/en/2.0/howto/static-files/STATIC_URL = '/static/'TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),)STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'),)
views.py
from django.shortcuts import render, redirect, HttpResponseimport reimport timeimport jsonimport requests# Create your views here.QCODE = NoneCURRENT_TIME = NoneLOGIN_COOKIE_DICT = {}TICKET_COOKIE_DICT = {}TICKET_DICT = {}TIP = 1 # 解决201后还不停pending的问题...USER_INIT_DATA = {}BASE_URL = "http://wx.qq.com"BASE_SYNC_URL = "https://webpush.weixin.qq.com"def login(request): # https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&_=1486951705941 base_qode_url = 'https://login.wx.qq.com/jslogin?appid=wx782c26e4c19acffb&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&lang=zh_CN&={0}' global CURRENT_TIME # 更改全局变量需要更改添加global global QCODE CURRENT_TIME = str(time.time()) # 时间戳【返回是float类型,转换为str类型】 q_code_url = base_qode_url.format(CURRENT_TIME) response = requests.get(q_code_url) # 获取到随记字符串,返回是个response对象 # code:# type(code): # code.text : window.QRLogin.code = 200; window.QRLogin.uuid = "gb8OTUPMpA=="; print('Response对象: ', response, type(response)) print('Response内容: ', response.text) code = re.findall('uuid = "(.*)"', response.text)[0] # findall返回一个列表,注意空格 QCODE = code print("随记字符:", QCODE) return render(request, 'login.html', {"code": QCODE})def pooling(request): # https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid=AY0FL0UZwA==&tip=1&r=1700853510&_=1523012536082 # 201: 扫码,未确认 # 200: 扫码,确认 # 408: 等待中... global TIP # 解决201后还不停pending的问题... ret = {'status': 408, 'data': None} base_login_url = "https://login.wx.qq.com/cgi-bin/mmwebwx-bin/login?loginicon=true&uuid={0}&tip={1}&r=-1700853510&_={2}" login_url = base_login_url.format(QCODE, TIP, CURRENT_TIME) response_login = requests.get(login_url) print('长轮询URL', login_url) print('长轮询状态码以及内容:', response_login.text) if 'window.code=201' in response_login.text: userAvatar = re.findall("userAvatar = '(.*)';", response_login.text)[0] ret['data'] = userAvatar ret['status'] = 201 TIP = 0 elif 'window.code=200' in response_login.text: global BASE_URL global BASE_SYNC_URL # 用户已经确认后获取Cookie内容 LOGIN_COOKIE_DICT.update(response_login.cookies.get_dict()) redirect_url = re.findall('window.redirect_uri="(.*)";', response_login.text)[0] if redirect_url.startswith('https://wx2.qq.com'): BASE_URL = 'https://wx2.qq.com' BASE_SYNC_URL = 'https://webpush.wx2.qq.com' else: BASE_URL = "http://wx.qq.com" BASE_SYNC_URL = "https://webpush.weixin.qq.com" # 微信正常的:https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=ATsWUC3qlrRteYUWzz_8hBMH@qrticket_0&uuid=QY2NxTcDcw==&lang=zh_CN&scan=1523018755&fun=new&version=v2&lang=zh_CN # 我们获取的:https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=AYTBkpgzEWsIgHOjaQK1tvSs@qrticket_0&uuid=AfxTcp1JXQ==&lang=zh_CN&scan=1523017763 print('用户确认后获取的URL:', redirect_url) redirect_url += '&fun=new&version=v2&lang=zh_CN' print('用户确认后改装的跳转URL:', redirect_url) # 用户已经确认后获取票据内容 response_ticket = requests.get(redirect_url, cookies=LOGIN_COOKIE_DICT) TICKET_COOKIE_DICT.update(response_ticket.cookies.get_dict()) ''' 获取的凭据内容: ''' print('获取的凭据内容: ', response_ticket.text) # 利用这个凭据进行下一次的数据访问 ''' 格式化输出凭据内容 ret 0 message None skey @crypt_29bab75e_996fb921b5a09570d7793598f2e213dc wxsid g++XySA396Bnwljx wxuin 1600696821 pass_ticket fbBFzsSbFhlD1kpNMJ7f39vrBwGqZTezGU7%2FpDZS1rzAueLDfKw%2FfoWp8sT8MdP6 isgrayscale 1 ''' from bs4 import BeautifulSoup soup = BeautifulSoup(response_ticket.text, 'html.parser') for tag in soup.find(): # 格式化打印XML内容 TICKET_DICT[tag.name] = tag.string # 字典内部元素修改不需要global,重新赋值需要global ret['status'] = 200 # 解决我们后台的报错问题,因为前台一直在pending获取数据根后台我们拿到的数据不一致 return HttpResponse(json.dumps(ret))# 获初始化用户信息def index(request): # 用户初始化URL: https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=1687552055&lang=zh_CN&pass_ticket=eSd509Kzdhcw4%252BDOYB7s0iV8ik2D%252FxYdOL5fwTSm9cvAaa7sLxZoz3mE88unS4sT #【20180410】base_userInit_url = 'https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxinit?r=1692953835&lang=zh_CN&pass_ticket=%s' base_userInit_url = BASE_URL + '/cgi-bin/mmwebwx-bin/webwxinit?r=1692953835&lang=zh_CN&pass_ticket=%s' userInit_url = base_userInit_url % TICKET_DICT['pass_ticket'] form_data = { 'BaseRequest': { "DeviceID": "e891769838090373", 'Sid': TICKET_DICT['wxsid'], 'Skey': TICKET_DICT['skey'], 'Uin': TICKET_DICT['wxuin'], }, } all_cookiies_dict = {} all_cookiies_dict.update(LOGIN_COOKIE_DICT) all_cookiies_dict.update(TICKET_COOKIE_DICT) response_list = requests.post(userInit_url, json=form_data, cookies=all_cookiies_dict) # response_list.encoding('utf8') 错误的 response_list.encoding = 'utf-8' # 正确的 print('用户基本信息:', response_list.text) userInit_data = json.loads(response_list.text) print('用户字典:') for k, v in userInit_data.items(): print(k, v) USER_INIT_DATA.update(userInit_data) # 获取的值放入全局变量USER_INIT_DATA里 ''' USER_INIT_DATA User { 'RemarkName': '', 'AppAccountFlag': 0, 'WebWxPluginSwitch': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=1001009474& 'Signature': "That's all、", 'VerifyFlag': 0, 'UserName': '@b5c4f49bd9d6c69177777fc7ffcd30c361', 'Uin': 1600696821, 'RemarkPYQuanPin': '', 'Sex': 1, 'ContactFlag': 0, 'PYInitial': '', 'NickName': 'HHHHHH', 'RemarkPYInitial': '', 'SnsFlag': 17, 'HideInputBarFlag': 0, 'HeadImgFlag': 1, 'StarFriend': 0, 'PYQuanPin': ''} ''' return render(request, 'index.html', {"data": USER_INIT_DATA})def contactList(request): # 获取用户列表: https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket=iH0mJhfpq1FrP44X18ovjrVFJfYqEszXSXGuuknxYJ4MATxoaFuPys&r=152302957&seq=0&skey=@crypt_29c62c055f8ff7e6d66c2fa05fb7 # 【20180410】base_contactList_url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket={0}&r={1}&seq=0&skey={2}" base_contactList_url = BASE_URL + "/cgi-bin/mmwebwx-bin/webwxgetcontact?lang=zh_CN&pass_ticket={0}&r={1}&seq=0&skey={2}" contactList_url = base_contactList_url.format(TICKET_DICT['pass_ticket'], str(time.time()), TICKET_DICT['skey']) all_cookiies_dict = {} all_cookiies_dict.update(LOGIN_COOKIE_DICT) all_cookiies_dict.update(TICKET_COOKIE_DICT) response = requests.get(contactList_url, cookies=all_cookiies_dict) response.encoding = 'utf-8' print('联系人列表:', response.text) contact_list = json.loads(response.text) contact_list_dict = json.loads(response.text) for k, v in contact_list.items(): print(k, v) print("获取用户列表__type(contact_list_dict):", type(contact_list_dict)) return render(request, 'contactList.html', {"obj": contact_list_dict}) 0 @crypt_ea9ae4c7_090ef27aeb8539e92003afd7658c8f49 dDQOkKqhrvLnFm1o 1289256384 YWQzZ0sOdkr1Eq%2BExvGbyfBq2mbIwksh%2BipMvTyNVUxBwnfqhXKn4wTBPMhpHh%2B%2F 1
url.py
from django.contrib import adminfrom django.urls import pathfrom App import viewsurlpatterns = [ path('admin/', admin.site.urls), path('login/', views.login), path('polling/', views.pooling), path('index/', views.index), path('contactList/', views.contactList),]
login.html
WeChat By FTL1012
index.html
用户信息 个人信息
{ { data.User.UserName }} -------- { { data.User.NickName }}最近联系人列表
- {% for item in data.ContactList %}
- { { item.UserName }} -- { { item.NickName }} -- { { item.PYQuanPin }} {% endfor %}
- {% for item in data.MPSubscribeMsgList %}
- { { item.NickName }}
- { { row.Digest }}
- { { row.Title }} {% endfor %}
- {% for row in item.MPArticleList %}
contactList.html
联系人列表 发送消息
联系人列表
- {% for row in obj.MemberList %}
- { { row.NickName }} - { { row.UserName }} -{ { row.Province }} {% endfor %}
页面请求: