feat: 新增交通银行数据导出插件及测试通道机制

This commit is contained in:
2026-11-05 15:20:34 +08:00
parent b976b80d9d
commit 4e8b3e7d43
230 changed files with 19827 additions and 1440 deletions
@@ -0,0 +1,367 @@
# -*- coding: utf-8 -*-
"""xq0077 携程数据导出 - 检票员检票报表导出(纯接口,自包含)。
链路(2026-11 抓包实测):
1) 管理端登录(见 lotsmall_login:用户中心 → SSO → tyAuthToken + 会话 Cookie)
2) statisticsSupport(管理端)→ authCode/appId/sign/timestamp/userCode
3) getCallbackUrl(管理端)→ reportModuleConfig 回调地址
4) verifySaasAuthCode → JWT-A
5) getMenuFuncOfTenantUser(头 token=JWT-A)→ result.user.token = JWT-B(报表平台鉴权 JWT)
6) getAllConfigs / preview(Authorization=JWT-B + 完整 query)→ reportDetailId + 列定义
7) searchFilter(判有无数据)→ total > 0 才 newExport 下载 xlsx
⚠️ 报表平台的 Authorization 必须是 JWT-B(第 5 步下发),
直接用 verifySaasAuthCode 的 JWT-A 会报「获取登录用户信息失败」。
"""
import hashlib
import os
import time
import urllib.parse
import requests
from .. import config
from . import lotsmall_login
class AuthError(RuntimeError):
"""账密错误/配置缺失:不可重试(避免锁号)。"""
def _log(msg, level="INFO"):
config.log(msg, level)
# ==================== 报表平台会话 ====================
def _report_session():
session = requests.Session()
session.headers.update({
"User-Agent": config.UA,
"Origin": config.REPORT_BASE,
"Referer": config.REPORT_BASE + "/",
"Accept": "application/json, text/plain, */*",
})
return session
def _verify_saas(session, auth_code, app_id):
"""authCode/appId 换 JWT-A。"""
resp = session.get(config.REPORT_BASE + config.API_VERIFY_SAAS,
params={"authCode": auth_code, "appId": app_id},
timeout=config.TIMEOUT)
try:
body = resp.json()
except ValueError:
raise RuntimeError(f"verifySaasAuthCode 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
result = body.get("result") or {}
jwt = (result.get("token") or result.get("accessToken")
or (body.get("data") or {}).get("token"))
if not jwt:
raise RuntimeError(f"未取到 JWT-A:{str(body)[:300]}")
return jwt
def _menu_jwt(session, jwt_a, user_code):
"""用 JWT-A 换报表平台鉴权 JWT-B(getMenuFuncOfTenantUser)。"""
if not user_code:
raise RuntimeError("缺少 bigDataLoginAuthCode,无法换取报表平台凭据")
resp = session.get(config.REPORT_BASE + config.API_USER_MENU_FUNC,
params={"userCode": user_code},
headers={"token": jwt_a, "Authorization": jwt_a},
timeout=config.TIMEOUT)
try:
body = resp.json()
except ValueError:
raise RuntimeError(f"getMenuFuncOfTenantUser 返回非 JSON(HTTP {resp.status_code})")
user = ((body or {}).get("result") or {}).get("user") or {}
jwt_b = str(user.get("token") or "")
if not jwt_b:
raise RuntimeError(f"未取到报表平台 JWT:{str(body)[:300]}")
return jwt_b
# ==================== 管理端辅助数据 ====================
def fetch_callback_url(token, session):
"""报表回调地址(报表平台会回调它取报表参数配置)。"""
if not session:
return ""
try:
resp = session.get(config.ADMIN_BASE + config.API_CALLBACK_URL,
params={"reportId": config.REPORT_ID},
headers={"tyAuthToken": token,
"Referer": config.ADMIN_BASE + "/manage/workspace",
"User-Agent": config.UA}, timeout=config.TIMEOUT)
data = (resp.json() or {}).get("data") or {}
return str(data.get("encodeUrl") or "")
except Exception as e:
_log(f"取回调地址失败(继续):{e}", "WARN")
return ""
def fetch_user_context(token, session):
"""取报表入参所需的真实用户上下文(管理端 /admin/userStore/detail)。
statisticsSupport 返回里没有 corpCode,报表接口缺它会报「获取登录用户信息失败」。
"""
fallback = {
"mainUserInfoId": config.USER_INFO_ID,
"subAccountId": config.SUB_ACCOUNT_ID,
"roleType": config.ROLE_TYPE,
"merchantId": config.MERCHANT_ID,
"corpCode": "",
}
if not session:
return fallback
try:
resp = session.get(config.ADMIN_BASE + config.API_USER_STORE_DETAIL, headers={
"tyAuthToken": token,
"User-Agent": config.UA,
"Referer": config.ADMIN_BASE + "/manage/workspace",
}, timeout=config.TIMEOUT)
body = resp.json() or {}
except Exception as e:
_log(f"取用户上下文异常:{e}", "WARN")
return fallback
user = body.get("user") or {}
if not user:
_log(f"取用户上下文失败:{str(body)[:200]}", "WARN")
return fallback
principal = user.get("principalInfo") or {}
merchant = user.get("merchantInfoDto") or {}
return {
"mainUserInfoId": user.get("mainUserInfoId") or config.USER_INFO_ID,
"subAccountId": user.get("id") or config.SUB_ACCOUNT_ID,
"roleType": principal.get("roleType") or config.ROLE_TYPE,
"merchantId": merchant.get("id") or config.MERCHANT_ID,
"corpCode": principal.get("corpCode") or merchant.get("corpCode") or "",
}
def _access_key(timestamp_ms):
"""报表平台 accessKey:md5(固定盐 + 毫秒时间戳 + '123456')。"""
raw = f'{config.REPORT_ACCESS_SALT}{timestamp_ms}123456'
return hashlib.md5(raw.encode()).hexdigest()
def _query_params(info, ctx, callback, timestamp_ms):
"""报表平台所有 GET 接口共用的 query 参数(与页面 iframe URL 完全一致)。"""
return {
"merchant_id": str(ctx.get("merchantId") or ""),
"userInfoId": str(ctx.get("mainUserInfoId") or ""),
"authCode": info.get("authCode"),
"corpCode": ctx.get("corpCode") or "",
"accessKey": _access_key(timestamp_ms),
"timestamp": timestamp_ms,
"appId": str(info.get("appId") or config.APP_ID_DEFAULT),
"sign": info.get("sign"),
"callbackUrl": callback,
"zybSupplierCode": ",".join(info.get("bindCorpCodes") or []),
"userCode": info.get("bigDataLoginAuthCode"),
"subAccountId": str(ctx.get("subAccountId") or ""),
"roleType": str(ctx.get("roleType") or ""),
}
def _auth_headers(query):
"""报表平台请求头:Authorization=JWT-B,另外带 authCode/appId/timestamp/sign/accessKey。"""
return {
"authCode": query.get("authCode") or "",
"appId": query.get("appId") or "",
"timestamp": str(query.get("timestamp") or ""),
"sign": query.get("sign") or "",
"accessKey": query.get("accessKey") or "",
}
# ==================== 报表接口 ====================
def fetch_preview(session, query, jwt_b):
"""取报表元数据:result(含 reportColumnDisplayList)。"""
headers = _auth_headers(query)
headers["Authorization"] = jwt_b
url = config.REPORT_BASE + config.API_PREVIEW.format(report_id=config.REPORT_ID)
resp = session.get(url, params=query, headers=headers, timeout=config.TIMEOUT)
try:
body = resp.json()
except ValueError:
raise RuntimeError(f"preview 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
result = body.get("result") or {}
if not result:
raise RuntimeError(f"preview 未返回数据:{str(body)[:300]}")
return result
def _query_body(info, ctx, callback, detail_id, column_groups, begin, end, for_export=False):
"""searchFilter / newExport 请求体(字段与页面实际提交完全一致)。
注意:页面 body 里的 callbackUrl 是**未编码**的原始地址(GET query 里才是编码版);
appId 只在 newExport 的 params 里出现,searchFilter 带上会 500。
"""
params = {
"terminalTpe": config.TERMINAL_TPE,
"merchant_id": str(ctx.get("merchantId") or ""),
"userInfoId": str(ctx.get("mainUserInfoId") or ""),
"merchantCode": "",
"corpCode": ctx.get("corpCode") or "",
"corpCodeIsTrim": "",
"zybCorpCode": "",
"distCorpCode": "",
"callbackUrl": urllib.parse.unquote(callback or ""),
"zybSupplierCode": ",".join(info.get("bindCorpCodes") or []),
"zybDistributorCode": "",
"userCode": info.get("bigDataLoginAuthCode"),
"znkfAppKey": "",
"subAccountId": str(ctx.get("subAccountId") or ""),
"roleType": str(ctx.get("roleType") or ""),
"pageIndex": config.PAGE_INDEX,
"pageSize": config.PAGE_SIZE,
"beginTradeDate": begin,
"endTradeDate": end,
"beginTradeDateendTradeDate": end,
"corp_name": None,
"linkName": None,
"linkTel": None,
"productName": None,
"externalOrderCode": None,
"checkName": None,
"id": str(config.REPORT_ID),
}
if for_export:
params["appId"] = str(info.get("appId") or config.APP_ID_DEFAULT)
return {
"shareMode": 0,
"reportType": 0,
"id": detail_id,
"params": params,
"reportColumnDisplayList": [{
"reportColumnDisplayList": (column_groups[0] or {}).get("reportColumnOptionList") or [],
"reportDetailId": detail_id,
}],
}
def _search(session, headers, body):
"""查询报表,返回 total(0 即无数据)。"""
resp = session.post(config.REPORT_BASE + config.API_SEARCH,
headers=headers, json=body, timeout=config.TIMEOUT)
raw = resp.text
if resp.status_code != 200:
raise RuntimeError(f"searchFilter HTTP {resp.status_code}:{raw[:300]}")
try:
payload = resp.json() or {}
except ValueError:
raise RuntimeError(f"searchFilter 返回非 JSON(HTTP {resp.status_code}):{raw[:200]}")
result = payload.get("result")
if result is None:
# 平台异常时会返回 {"timestamp":..,"status":500,...},不能当成「无数据」
raise RuntimeError(f"searchFilter 失败:{raw[:300]}")
items = result.get("reportSearchList") or []
first = items[0] if items else {}
try:
total = int(first.get("total") or 0)
except (TypeError, ValueError):
total = 0
_log(f"查询结果:total={total},rows={len(first.get('rows') or [])}"
f"({config.PAGE_SIZE} 条/页仅用于探测,导出为全量)")
return total
def _export(session, headers, body, save_dir):
"""下载 xlsx 并落盘,返回文件路径。"""
body = dict(body)
body["reportColumnFilterList"] = [{"reportDetailId": body.get("id")}]
resp = session.post(config.REPORT_BASE + config.API_EXPORT,
headers=headers, json=body, timeout=config.DOWNLOAD_TIMEOUT)
if resp.content[:2] != b'PK':
raise RuntimeError(f"导出返回非 xlsx(HTTP {resp.status_code}):{resp.text[:300]}")
cd = resp.headers.get("content-disposition") or ""
if "filename=" in cd:
server_name = cd.split("filename=", 1)[1].strip().strip('"')
_log(f"服务端文件名:{urllib.parse.unquote(server_name)}")
path = os.path.join(save_dir, config.export_filename())
with open(path, 'wb') as f:
f.write(resp.content)
_log(f"导出完成 → {path}({len(resp.content)} bytes)")
return path
# ==================== 主入口 ====================
def run_export(account, password, save_dir='', date_range=None):
"""查询并导出「检票员检票报表」。
date_range:(begin, end) 字符串元组;留空按 config.date_window() 默认口径。
返回:{'total': 查询总数, 'file': 落盘路径(无数据时为空字符串)}
登录/接口失败抛 RuntimeError(账密错误立即停止,不重试)。
"""
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
os.makedirs(save_dir, exist_ok=True)
begin, end = date_range or config.date_window()
_log(f"日期区间:{begin} ~ {end}")
_log(f"保存目录:{save_dir}")
config.progress(5)
last_err = None
for attempt in range(1, config.RETRY_MAX + 1):
try:
# 1) 登录(用户中心 → SSO → 管理端 tyAuthToken + 会话 Cookie)
login = lotsmall_login.ensure_login(account, password, force=(attempt > 1))
if not login.get("success"):
msg = login.get("message") or "登录失败"
if login.get("fatal") or "账号或密码错误" in msg or "缺失" in msg:
raise AuthError(msg)
raise RuntimeError(msg)
token = login.get("token")
session = login.get("session")
config.progress(20)
# 2) 报表接入参数 + 用户上下文 + 回调地址
info = lotsmall_login.fetch_report_params(token, session)
if not info:
raise AuthError("已登录成功,但 statisticsSupport 未返回报表接入参数")
for key in ("authCode", "sign", "timestamp"):
if not info.get(key):
raise RuntimeError(f"statisticsSupport 缺少 {key}:{str(info)[:300]}")
ctx = fetch_user_context(token, session)
callback = fetch_callback_url(token, session)
_log(f"用户上下文:corpCode={ctx.get('corpCode')},roleType={ctx.get('roleType')},"
f"merchantId={ctx.get('merchantId')}", "DEBUG")
config.progress(35)
# 3) 报表平台:换 JWT-A → 换 JWT-B → 预览
rs = _report_session()
jwt_a = _verify_saas(rs, info["authCode"], info.get("appId") or config.APP_ID_DEFAULT)
jwt_b = _menu_jwt(rs, jwt_a, info.get("bigDataLoginAuthCode"))
ts = int(time.time() * 1000)
query = _query_params(info, ctx, callback, ts)
preview = fetch_preview(rs, query, jwt_b)
groups = preview.get("reportColumnDisplayList") or []
detail_id = (groups[0] or {}).get("reportDetailId") if groups else None
if not detail_id:
raise RuntimeError(f"preview 未返回 reportDetailId:{str(preview)[:300]}")
_log(f"报表元数据:reportDetailId={detail_id},列分组={len(groups)}")
config.progress(55)
# 4) 查询判有无数据(无数据跳过导出)
headers = _auth_headers(query)
headers["Authorization"] = jwt_b
body = _query_body(info, ctx, callback, detail_id, groups, begin, end)
total = _search(rs, headers, body)
if total <= 0:
_log("查询无数据,跳过导出")
config.progress(100)
return {'total': 0, 'file': ''}
config.progress(70)
# 5) 导出(newExport 的 params 要额外带 appId)
export_body = _query_body(info, ctx, callback, detail_id, groups, begin, end,
for_export=True)
path = _export(rs, headers, export_body, save_dir)
config.progress(100)
return {'total': total, 'file': path}
except AuthError:
raise
except Exception as e:
last_err = e
_log(f"第 {attempt}/{config.RETRY_MAX} 次导出失败:{e}", "WARN")
time.sleep(1)
raise RuntimeError(f"检票员检票报表导出失败(重试 {config.RETRY_MAX} 次耗尽):{last_err}")