- tests/tianque_probe:天阙会生活商户平台登录(drission)/报表抓包/导出探测脚本,供 XQ0079 排查字段与接口用 - 删除临时脚本 .tmp_check_wf0033.py
225 lines
8.9 KiB
Python
225 lines
8.9 KiB
Python
"""天阙会生活商户平台:纯接口导出交易记录(不启浏览器,不依赖 DrissionPage)。
|
||
|
||
用法:
|
||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_export.py
|
||
|
||
流程(与网页完全一致,报文来自真实抓包):
|
||
1. 验证码 + AES 加密密码 → user/transForm/login 拿 token
|
||
2. POST tranInfoPc/exportNew 提交导出任务(返回空 body,任务异步生成)
|
||
3. POST download/downLoadList 轮询下载中心,等新增那条 fileSource=交易记录 且 exportStatus=1
|
||
4. 取记录里的 downloadUrl(OSS 预签名地址,直接 GET 即可,无需 token)落盘到 export/
|
||
5. POST download/read/<id> 标记已读,避免下载中心越堆越多
|
||
|
||
已知坑位:
|
||
- exportNew 参数照抄网页即可,timeType=01 表示自定义时间;响应是空 body(0 字节),
|
||
不能按 JSON 解析,成功与否靠下载中心列表判断。
|
||
- downloadUrl 带 expires/accessKey/signature,有时效,拿到要立刻下。
|
||
- 下载中心是「按任务」的:先记下提交前的 id 集合,之后只认新增记录,避免下到历史文件。
|
||
- 登录接口 body 需要 {header:{sysType:pc},data:{...}} 信封,业务接口是扁平 body。
|
||
"""
|
||
|
||
import json
|
||
import os
|
||
import sys
|
||
import time
|
||
from datetime import datetime, timedelta
|
||
|
||
if hasattr(sys.stdout, "reconfigure"):
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
import tianque_login_test as m # 复用登录原语:验证码、OCR、AES 加密、低安全 SSL 会话
|
||
|
||
# ==================== 配置区 ====================
|
||
EXPORT_KIND = "trade" # trade=交易记录;后续扩展:settle=结算记录
|
||
START_DAYS_AGO = 3 # 起始时间:N 天前的 00:00:00
|
||
END_TODAY = True # True=结束时间取今天 23:59:59
|
||
CUSTOM_START = "" # 也可直接写死 "2026-11-01 00:00:00",非空则优先
|
||
CUSTOM_END = ""
|
||
|
||
POLL_TIMEOUT = 180 # 等文件生成的最长秒数
|
||
POLL_INTERVAL = 5 # 轮询间隔
|
||
LIST_PAGE_SIZE = 10
|
||
OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "export")
|
||
DO_MARK_READ = True # 下载后标记已读(与网页点击下载行为一致)
|
||
KEEP_RAW = False # True 时把 downLoadList 原始响应也落盘,便于排查
|
||
# ===============================================
|
||
|
||
BASE = "https://mch-web.tianquetech.com"
|
||
URL_EXPORT = "/management/easypay/api/tranInfoPc/exportNew"
|
||
URL_DOWNLOAD_LIST = "/management/easypay/api/download/downLoadList"
|
||
URL_MARK_READ = "/management/easypay/api/download/read/"
|
||
URL_POLLING = "/management/easypay/api/download/polling"
|
||
|
||
# 下载中心里 fileSource 的取值,用来认自己刚触发的那条记录
|
||
SOURCE_OF_KIND = {
|
||
"trade": "交易记录",
|
||
"settle": "结算记录",
|
||
}
|
||
|
||
# 交易记录导出参数:照抄网页抓包(payTypePc/tranStsPc/payWayPcList 的 0 均表示「全部」)
|
||
TRADE_EXPORT_TEMPLATE = {
|
||
"payTypePc": "0",
|
||
"storeId": "",
|
||
"userId": "",
|
||
"tranStsPc": "0",
|
||
"payWayPcList": ["0"],
|
||
"trmNo": "",
|
||
"tradeSources": "",
|
||
"timeType": "01",
|
||
}
|
||
|
||
|
||
def log(msg):
|
||
print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True)
|
||
|
||
|
||
def api_post(session, path, payload=None):
|
||
"""业务接口 POST。注意 exportNew 会返回空 body,不能无脑 r.json()。"""
|
||
r = session.post(BASE + path, json=payload if payload is not None else {}, timeout=30)
|
||
text = (r.text or "").strip()
|
||
if not text:
|
||
return {"_empty": True, "_status": r.status_code}
|
||
try:
|
||
return r.json()
|
||
except ValueError:
|
||
return {"_raw": text[:500], "_status": r.status_code}
|
||
|
||
|
||
def login():
|
||
"""验证码 + 密码登录,返回 (session, user)。复用 tianque_login_test 的原语。"""
|
||
if not (m.ACCOUNT and m.PASSWORD):
|
||
raise RuntimeError("请先在 tianque_login_test.py 顶部配置 ACCOUNT / PASSWORD")
|
||
|
||
session = m.new_session()
|
||
for attempt in range(1, m.MAX_ATTEMPTS + 1):
|
||
log(f"登录第 {attempt}/{m.MAX_ATTEMPTS} 轮")
|
||
image_key, png = m.fetch_captcha(session)
|
||
code = m.ocr_image(png)
|
||
if not m.ocr_code_ok(code):
|
||
log(f"验证码识别结果不可用({code or '空'}),换图")
|
||
continue
|
||
|
||
resp = m.do_login(session, m.ACCOUNT, m.PASSWORD, image_key, code)
|
||
if str(resp.get("code", "")) in m.CODE_OK:
|
||
users = (resp.get("data") or {}).get("users") or []
|
||
if not users:
|
||
raise RuntimeError(f"登录成功但无用户信息:{json.dumps(resp, ensure_ascii=False)[:200]}")
|
||
user = users[0]
|
||
session.headers["token"] = user["token"]
|
||
log(f"登录成功:{user.get('merchantName') or user.get('userName')} mno={user.get('mno')}")
|
||
return session, user
|
||
|
||
log(f"登录未通过:code={resp.get('code')} {resp.get('msg') or resp.get('message')}")
|
||
raise RuntimeError("登录失败(多为验证码识别率问题,重跑即可)")
|
||
|
||
|
||
def time_range():
|
||
"""导出时间范围。"""
|
||
if CUSTOM_START and CUSTOM_END:
|
||
return CUSTOM_START, CUSTOM_END
|
||
now = datetime.now()
|
||
start = (now - timedelta(days=START_DAYS_AGO)).strftime("%Y-%m-%d 00:00:00")
|
||
end = now.strftime("%Y-%m-%d 23:59:59") if END_TODAY else now.strftime("%Y-%m-%d %H:%M:%S")
|
||
return start, end
|
||
|
||
|
||
def download_list(session):
|
||
"""下载中心列表(新→旧)。"""
|
||
resp = api_post(session, URL_DOWNLOAD_LIST, {"pageNum": 1, "pageSize": LIST_PAGE_SIZE})
|
||
data = resp.get("data") or {}
|
||
return data.get("content") or []
|
||
|
||
|
||
def submit_export(session, start, end):
|
||
"""提交导出任务。"""
|
||
payload = dict(TRADE_EXPORT_TEMPLATE)
|
||
payload["startTime"] = start
|
||
payload["endTime"] = end
|
||
resp = api_post(session, URL_EXPORT, payload)
|
||
if resp.get("_empty"):
|
||
log(f"导出任务已提交(HTTP {resp.get('_status')},空响应属正常)")
|
||
else:
|
||
log(f"导出任务已提交:{json.dumps(resp, ensure_ascii=False)[:200]}")
|
||
return payload
|
||
|
||
|
||
def wait_new_record(session, before_ids, source_kw, timeout=POLL_TIMEOUT, interval=POLL_INTERVAL):
|
||
"""等下载中心出现本次新增且导出完成的记录。"""
|
||
deadline = time.time() + timeout
|
||
last_desc = ""
|
||
while time.time() < deadline:
|
||
for rec in download_list(session):
|
||
if rec.get("id") in before_ids:
|
||
continue
|
||
if source_kw and source_kw not in (rec.get("fileSource") or ""):
|
||
continue
|
||
status = str(rec.get("exportStatus") or "")
|
||
desc = rec.get("exportStatusDesc") or status
|
||
if status == "1" and rec.get("downloadUrl"):
|
||
return rec
|
||
if desc != last_desc:
|
||
log(f"任务状态:{rec.get('fileName')} -> {desc}")
|
||
last_desc = desc
|
||
time.sleep(interval)
|
||
raise RuntimeError(f"等了 {timeout}s 仍未等到导出完成,可调大 POLL_TIMEOUT 或去下载中心手动确认")
|
||
|
||
|
||
def download_file(session, rec):
|
||
"""GET 预签名 OSS 地址直接下载,按平台给的文件名落盘。"""
|
||
os.makedirs(OUT_DIR, exist_ok=True)
|
||
name = rec.get("fileName") or f"tianque_{rec.get('id')}.xlsx"
|
||
path = os.path.join(OUT_DIR, name)
|
||
url = rec["downloadUrl"]
|
||
log("开始下载:" + url.split("?")[0])
|
||
r = session.get(url, timeout=180)
|
||
r.raise_for_status()
|
||
with open(path, "wb") as f:
|
||
f.write(r.content)
|
||
log(f"已落盘:{path}({len(r.content)} 字节)")
|
||
return path
|
||
|
||
|
||
def mark_read(session, rec_id):
|
||
if not DO_MARK_READ:
|
||
return
|
||
resp = api_post(session, URL_MARK_READ + rec_id, {})
|
||
log(f"已标记已读:{rec_id} -> {resp.get('data') or resp.get('message')}")
|
||
|
||
|
||
def main():
|
||
start, end = time_range()
|
||
log(f"导出类型={EXPORT_KIND} 时间范围 {start} ~ {end}")
|
||
|
||
session, _ = login()
|
||
|
||
before_ids = {rec.get("id") for rec in download_list(session)}
|
||
log(f"提交前下载中心已有 {len(before_ids)} 条记录")
|
||
|
||
submit_export(session, start, end)
|
||
|
||
rec = wait_new_record(session, before_ids, SOURCE_OF_KIND.get(EXPORT_KIND, ""))
|
||
log(f"导出完成:{rec.get('fileName')} 创建时间={rec.get('createDate')}")
|
||
|
||
path = download_file(session, rec)
|
||
mark_read(session, rec.get("id"))
|
||
|
||
if KEEP_RAW:
|
||
raw_path = os.path.join(OUT_DIR, "downLoadList_raw.json")
|
||
with open(raw_path, "w", encoding="utf-8") as f:
|
||
json.dump(download_list(session), f, ensure_ascii=False, indent=2)
|
||
log(f"原始列表已存:{raw_path}")
|
||
|
||
log(f"完成,文件:{path}")
|
||
return True
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
sys.exit(0 if main() else 1)
|
||
except KeyboardInterrupt:
|
||
log("手动中断")
|
||
sys.exit(1)
|