feat(xq0078): 新增金色湖畔小程序数据导出插件(1.0.4)
- 金贵微信端管理平台(vip6.wechat.goldenyun.cn)门票使用统计导出:接口登录 → 搜索接口取核销明细 → 调平台导出接口生成 xlsx - 核销时间日期段界面可选(默认昨天 00:00:00 ~ 今天 23:59:59);导出接口异常时按同一份数据本地生成同列序 xlsx 兜底
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:平台接口访问(登录 / 搜索 / 导出)。"""
|
||||
@@ -0,0 +1,240 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金贵微信端管理平台 - 门票使用统计(票券消费明细)查询与导出。
|
||||
|
||||
接口机制(从列表页 JS 逆向确认):
|
||||
1) 搜索接口 POST /wechat/memberreport/ticketconsumelistreport
|
||||
body = 列表页 frmList 序列化(Query.BeginTime/EndTime/... + Pager.*),返回 JSON 数组,
|
||||
元素字段:TicketTypeName / TicketGroupId / TicketID / SellPrice / UseDateStr /
|
||||
UseBillid / UseName / UseVpnName。
|
||||
2) 导出接口 POST /wechat/export/downloadexcel
|
||||
它不接受查询条件,只接受「文件名 + 一整段 <table> HTML」;页面是前端把搜索 JSON
|
||||
拼成表格塞进隐藏域再提交。两个隐藏域 name 每次页面加载都变(数字 ticks + GUID),
|
||||
必须现场从列表页解析。
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ---------------------------- 列表页 / 导出表单字段 ----------------------------
|
||||
|
||||
def open_list_page(session):
|
||||
url = f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}"
|
||||
config.logger.info('打开门票使用统计页: %s', url)
|
||||
resp = session.get(url, timeout=config.TIMEOUT)
|
||||
resp.encoding = 'utf-8'
|
||||
if config.LOGIN_PATH in resp.url and 'id="Password"' in resp.text:
|
||||
raise RuntimeError('列表页被重定向回登录页:会话已失效,请重新执行')
|
||||
resp.raise_for_status()
|
||||
return resp.text
|
||||
|
||||
|
||||
def parse_export_fields(html):
|
||||
"""解析 exportForm 两个动态隐藏域 name:纯数字=文件名,GUID 形态=表格 HTML。"""
|
||||
start = html.find('id="exportForm"')
|
||||
if start == -1:
|
||||
raise RuntimeError('列表页未找到 exportForm,无法确定导出字段名(平台页面可能改版)')
|
||||
end = html.find('</form>', start)
|
||||
segment = html[start:end if end != -1 else len(html)]
|
||||
|
||||
names = re.findall(r'<input\s+name="([^"]+)"\s+type="hidden"', segment)
|
||||
if len(names) < 2:
|
||||
names = re.findall(r'name="([^"]+)"[^>]*type="hidden"', segment)
|
||||
digits = [n for n in names if n.isdigit() and 10 <= len(n) <= 20]
|
||||
guids = [n for n in names if n.count('-') >= 2]
|
||||
if not digits or not guids:
|
||||
raise RuntimeError(f'导出表单字段名解析失败:{names}')
|
||||
config.logger.info('导出表单字段名:文件名=%s / 表格=%s', digits[0], guids[0])
|
||||
return {'filename': digits[0], 'content': guids[0]}
|
||||
|
||||
|
||||
# ---------------------------- 搜索 ----------------------------
|
||||
|
||||
def build_query(begin, end, page_index=0):
|
||||
return {
|
||||
'Query.BeginTime': begin,
|
||||
'Query.EndTime': end,
|
||||
'Query.TicketGroupId': '',
|
||||
'Query.UseBillid': '',
|
||||
'Query.UseName': '',
|
||||
'Query.UseVpnCode': '',
|
||||
'Query.TypeCode': '',
|
||||
'Pager.TotalAmount': '0',
|
||||
'Pager.PageSize': str(config.PAGE_SIZE),
|
||||
'Pager.PageIndex': str(page_index),
|
||||
}
|
||||
|
||||
|
||||
def _post_search(session, query):
|
||||
url = f"{config.BASE_URL}{config.APP_PATH}{config.SEARCH_PATH}"
|
||||
headers = {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Referer': f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}",
|
||||
}
|
||||
resp = session.post(url, data=query, headers=headers, timeout=config.TIMEOUT)
|
||||
resp.encoding = 'utf-8'
|
||||
if resp.status_code >= 500:
|
||||
raise requests.RequestException(f'搜索接口 HTTP {resp.status_code}')
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f'搜索接口 HTTP {resp.status_code}:{resp.text[:200]}')
|
||||
|
||||
body = (resp.text or '').strip()
|
||||
if not body:
|
||||
return []
|
||||
if body.startswith('<'):
|
||||
raise RuntimeError(f'搜索接口返回 HTML 而非 JSON(可能会话失效):{body[:200]}')
|
||||
try:
|
||||
data = resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f'搜索接口返回无法解析:{body[:200]}')
|
||||
if isinstance(data, dict):
|
||||
for key in ('Data', 'data', 'Rows', 'rows', 'Items', 'items'):
|
||||
if isinstance(data.get(key), list):
|
||||
data = data[key]
|
||||
break
|
||||
return data if isinstance(data, list) else []
|
||||
|
||||
|
||||
def post_search(session, query):
|
||||
"""带重试的搜索调用(仅网络异常/5xx 重试,避免无意义重放)。"""
|
||||
last = None
|
||||
for attempt in range(1, config.SEARCH_MAX_RETRY + 1):
|
||||
try:
|
||||
return _post_search(session, query)
|
||||
except requests.RequestException as e:
|
||||
last = e
|
||||
config.logger.warning('搜索第 %s/%s 次失败:%s', attempt, config.SEARCH_MAX_RETRY, e)
|
||||
time.sleep(2)
|
||||
raise RuntimeError(f'搜索接口连续 {config.SEARCH_MAX_RETRY} 次失败:{last}')
|
||||
|
||||
|
||||
def fetch_all_rows(session, begin, end):
|
||||
"""按页拉全量并去重(接口若忽略分页,第一次即返回全部)。"""
|
||||
rows, seen, page = [], set(), 0
|
||||
while page < config.MAX_PAGES:
|
||||
batch = post_search(session, build_query(begin, end, page))
|
||||
config.logger.info('第 %s 页返回 %s 条', page + 1, len(batch))
|
||||
if not batch:
|
||||
break
|
||||
new_count = 0
|
||||
for row in batch:
|
||||
key = (str(row.get('TicketID')), str(row.get('TicketGroupId')), str(row.get('UseDateStr')))
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
rows.append(row)
|
||||
new_count += 1
|
||||
if new_count == 0 or len(batch) < config.PAGE_SIZE:
|
||||
break
|
||||
page += 1
|
||||
config.logger.info('去重后合计 %s 条', len(rows))
|
||||
return rows
|
||||
|
||||
|
||||
# ---------------------------- 导出 ----------------------------
|
||||
|
||||
def _price(value):
|
||||
try:
|
||||
return f"{float(value or 0):.2f}"
|
||||
except (TypeError, ValueError):
|
||||
return '0.00'
|
||||
|
||||
|
||||
def rows_to_table_html(rows):
|
||||
"""拼成与页面完全一致结构的表格 HTML(导出接口只认这段 HTML)。"""
|
||||
head = ('<table class="table mytable extend table-bordered single-selected new-table-header-on" '
|
||||
'id="detail-List"><thead> <tr>'
|
||||
+ ''.join(f'<th>{c}</th>' for c in config.COLUMNS)
|
||||
+ '</tr></thead><tbody>')
|
||||
body = []
|
||||
for row in rows:
|
||||
body.append(
|
||||
'<tr><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td><td>{}</td></tr>'.format(
|
||||
row.get('TicketTypeName') or '',
|
||||
row.get('TicketGroupId') or '',
|
||||
row.get('TicketID') or '',
|
||||
_price(row.get('SellPrice')),
|
||||
row.get('UseDateStr') or '',
|
||||
row.get('UseBillid') or config.EMPTY_BILL_TEXT,
|
||||
row.get('UseName') or '',
|
||||
row.get('UseVpnName') or '',
|
||||
))
|
||||
return head + ''.join(body) + '</tbody></table>'
|
||||
|
||||
|
||||
def _decode_body(resp):
|
||||
"""按 BOM 解码响应体(平台用 Encoding.Unicode 输出 HTML 表格,即 UTF-16LE)。"""
|
||||
raw = resp.content or b''
|
||||
if raw[:2] == b'\xff\xfe':
|
||||
return raw[2:].decode('utf-16-le', 'ignore')
|
||||
if raw[:2] == b'\xfe\xff':
|
||||
return raw[2:].decode('utf-16-be', 'ignore')
|
||||
return raw.decode(resp.encoding or 'utf-8', 'ignore')
|
||||
|
||||
|
||||
def export_via_server(session, fields, rows):
|
||||
"""调服务端导出接口。
|
||||
|
||||
返回 dict:
|
||||
{'kind': 'xlsx', 'content': bytes} 平台返回真 xlsx(PK 文件头)
|
||||
{'kind': 'html_excel', 'text': str} 平台返回 HTML 伪装 Excel(UTF-16 的 <table>…)
|
||||
{'kind': 'none', 'text': str} 未拿到可识别内容(调用方走本地兜底)
|
||||
"""
|
||||
url = f"{config.BASE_URL}{config.APP_PATH}{config.EXPORT_PATH}"
|
||||
payload = {
|
||||
fields['filename']: config.EXPORT_TITLE,
|
||||
fields['content']: rows_to_table_html(rows),
|
||||
}
|
||||
headers = {
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
'Referer': f"{config.BASE_URL}{config.APP_PATH}{config.LIST_PATH}",
|
||||
}
|
||||
config.logger.info('调用导出接口(%s 条)…', len(rows))
|
||||
resp = session.post(url, data=payload, headers=headers, timeout=config.TIMEOUT)
|
||||
config.logger.info('导出响应:状态=%s Content-Type=%s Content-Disposition=%s 长度=%s 文件头=%r',
|
||||
resp.status_code, resp.headers.get('Content-Type'),
|
||||
resp.headers.get('Content-Disposition'),
|
||||
len(resp.content), resp.content[:4])
|
||||
|
||||
if resp.status_code == 200 and resp.content[:2] == b'PK':
|
||||
return {'kind': 'xlsx', 'content': resp.content}
|
||||
|
||||
text = _decode_body(resp)
|
||||
if resp.status_code == 200 and '<table' in text.lower():
|
||||
# 平台「导出」= 把表格 HTML 直接吐回(Excel 能识别但不是标准工作簿,
|
||||
# 用 .xls 扩展名打开还会提示格式不符);数据本身与搜索接口完全一致
|
||||
config.logger.info('平台导出接口返回 HTML 版 Excel(%.1f KB),数据可用',
|
||||
len(resp.content) / 1024.0)
|
||||
return {'kind': 'html_excel', 'text': text}
|
||||
|
||||
config.logger.warning('导出接口未返回可识别文件,响应预览:%s',
|
||||
text[:200].replace('\n', ' '))
|
||||
return {'kind': 'none', 'text': text}
|
||||
|
||||
|
||||
def write_xlsx_local(rows, path):
|
||||
"""兜底:按搜索接口 JSON 直接用 openpyxl 生成同列序的 xlsx。"""
|
||||
from openpyxl import Workbook
|
||||
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = config.EXPORT_TITLE[:31]
|
||||
ws.append(config.COLUMNS)
|
||||
for row in rows:
|
||||
ws.append([
|
||||
row.get('TicketTypeName') or '',
|
||||
row.get('TicketGroupId') or '',
|
||||
row.get('TicketID') or '',
|
||||
float(_price(row.get('SellPrice'))),
|
||||
row.get('UseDateStr') or '',
|
||||
row.get('UseBillid') or config.EMPTY_BILL_TEXT,
|
||||
row.get('UseName') or '',
|
||||
row.get('UseVpnName') or '',
|
||||
])
|
||||
for letter, width in zip('ABCDEFGH', (46, 20, 18, 10, 20, 20, 12, 22)):
|
||||
ws.column_dimensions[letter].width = width
|
||||
wb.save(path)
|
||||
return path
|
||||
@@ -0,0 +1,119 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金贵微信端管理平台登录(接口登录,无需浏览器)。
|
||||
|
||||
登录页为传统 ASP.NET MVC 表单:
|
||||
POST /chqhpwq.web/login?returnurl=<目标页>
|
||||
表单字段:VpnCode(门店 GUID) / VpnName / UserName / Password / Channel
|
||||
无验证码、无 CSRF Token、无前端密码加密;失败时服务端回渲染登录页并在
|
||||
validation-summary-errors 里给出「帐号密码错误!」。
|
||||
"""
|
||||
import re
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
|
||||
_ERROR_HINTS = ('帐号密码错误', '账号密码错误', '密码错误', '已被锁定', '锁定', '验证码', '无权')
|
||||
|
||||
|
||||
def new_session():
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0 Safari/537.36'),
|
||||
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
||||
'Accept-Language': 'zh-CN,zh;q=0.9',
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def fetch_login_page(session):
|
||||
url = f"{config.BASE_URL}{config.APP_PATH}{config.LOGIN_PATH}"
|
||||
config.logger.info('获取登录页: %s', url)
|
||||
resp = session.get(url, timeout=config.TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
resp.encoding = 'utf-8'
|
||||
return resp.text
|
||||
|
||||
|
||||
def parse_vpn_list(html):
|
||||
"""解析门店列表:<li data-id="GUID" data-name="门店名">门店名</li>"""
|
||||
block = html
|
||||
start = html.find('class="vpn-list"')
|
||||
if start != -1:
|
||||
end = html.find('</ul>', start)
|
||||
block = html[start:end if end != -1 else len(html)]
|
||||
|
||||
vpns = []
|
||||
for match in re.finditer(r'<li([^>]*)>([^<]*)</li>', block):
|
||||
code = re.search(r'data-id="([^"]+)"', match.group(1))
|
||||
if not code:
|
||||
continue
|
||||
name = re.search(r'data-name="([^"]*)"', match.group(1))
|
||||
vpns.append({'code': code.group(1), 'name': (name.group(1) if name else match.group(2)).strip()})
|
||||
return vpns
|
||||
|
||||
|
||||
def pick_vpn(vpns, want_name=''):
|
||||
"""按门店名匹配,未命中则取登录页第一个门店。"""
|
||||
want = str(want_name or '').strip()
|
||||
if want:
|
||||
for vpn in vpns:
|
||||
if vpn['name'] == want:
|
||||
return vpn
|
||||
for vpn in vpns:
|
||||
if want in vpn['name'] or vpn['name'] in want:
|
||||
return vpn
|
||||
config.logger.warning('未匹配到门店「%s」,回退登录页第一个门店', want)
|
||||
if not vpns:
|
||||
raise RuntimeError('登录页未解析到门店列表,无法选择门店登录')
|
||||
return vpns[0]
|
||||
|
||||
|
||||
def _extract_error(html):
|
||||
for match in re.finditer(r'validation-summary-errors[^>]*>\s*<ul>(.*?)</ul>', html, re.S):
|
||||
items = [re.sub(r'<[^>]+>', '', li).strip()
|
||||
for li in re.findall(r'<li[^>]*>(.*?)</li>', match.group(1), re.S)]
|
||||
items = [i for i in items if i]
|
||||
if items:
|
||||
return ' / '.join(items)
|
||||
for hint in _ERROR_HINTS:
|
||||
if hint in html:
|
||||
return f'页面出现关键字「{hint}」'
|
||||
return ''
|
||||
|
||||
|
||||
def login(username, password, vpn_name=''):
|
||||
"""返回已认证的 requests.Session;失败抛 RuntimeError(凭据错误不重试,避免锁号)。"""
|
||||
username = str(username or '').strip()
|
||||
password = str(password or '').strip() # 防误存首尾空格导致平台判密码错误
|
||||
if not username or not password:
|
||||
raise RuntimeError('登录账号或密码为空:请在插件界面填写并保存配置')
|
||||
|
||||
session = new_session()
|
||||
html = fetch_login_page(session)
|
||||
vpn = pick_vpn(parse_vpn_list(html), vpn_name)
|
||||
config.logger.info('登录门店:%s(%s)', vpn['name'], vpn['code'])
|
||||
|
||||
from urllib.parse import quote
|
||||
return_url = quote(config.APP_PATH + config.LIST_PATH, safe='')
|
||||
url = f"{config.BASE_URL}{config.APP_PATH}{config.LOGIN_PATH}?returnurl={return_url}"
|
||||
payload = {
|
||||
'VpnCode': vpn['code'],
|
||||
'VpnName': vpn['name'],
|
||||
'UserName': username,
|
||||
'Password': password,
|
||||
'Channel': config.CHANNEL_WECHAT,
|
||||
}
|
||||
resp = session.post(url, data=payload, timeout=config.TIMEOUT, allow_redirects=True)
|
||||
resp.encoding = 'utf-8'
|
||||
config.logger.info('登录响应:状态=%s 最终URL=%s', resp.status_code, resp.url)
|
||||
|
||||
error = _extract_error(resp.text)
|
||||
if error:
|
||||
hint = '(请检查账号密码首尾空格后重试)' if '密码' in error else ''
|
||||
raise RuntimeError(f'登录失败:{error}{hint}。为免触发平台失败计数锁定,本次不重试')
|
||||
if config.LOGIN_PATH in resp.url and 'id="Password"' in resp.text:
|
||||
raise RuntimeError('登录失败:仍停留在登录页,请确认账号密码与门店是否正确')
|
||||
config.logger.info('登录成功,Cookie=%s', ', '.join(session.cookies.keys()) or '无')
|
||||
return session
|
||||
Reference in New Issue
Block a user