- 天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录导出:账密登录(图形验证码 OCR + AES 密码加密,token 按账号缓存复用)→ 平台导出接口生成 xlsx → 下载中心取文件直存本地 - 支持两套账号串行导出(第 2 套可留空),日期区间界面可选,产物按商户名区分
153 lines
6.3 KiB
Python
153 lines
6.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""xq0079 导出模块:天阙交易记录导出(平台服务端生成 xlsx,本地只负责触发 + 取件)。
|
||
|
||
链路(2026-11 实测,与网页完全一致):
|
||
1) POST tranInfoPc/exportNew 提交导出任务(响应体为空,成功与否靠下载中心判断)
|
||
2) POST download/downLoadList 轮询下载中心,等本次新增且 exportStatus=1 的记录
|
||
3) GET <record.downloadUrl> OSS 预签名地址,直接下载,不需要带 token
|
||
4) POST download/read/<id> 标记已读,避免下载中心越堆越多
|
||
|
||
已知坑位:
|
||
- exportNew 返回 0 字节,不能按 JSON 解析。
|
||
- download/polling 只是前端进度圈,脚本不用它,省掉一堆无意义请求。
|
||
- 下载中心是全账号共享的历史列表,必须用「提交前的 id 集合 + 增量」认领自己的任务,
|
||
否则会下到历史文件;文件名里的时间串也不能当唯一标识。
|
||
- downloadUrl 带 expires/signature,有时效,拿到要立刻下。
|
||
"""
|
||
import os
|
||
import time
|
||
|
||
from .. import config
|
||
from . import tianque_login as login_mod
|
||
|
||
|
||
def _log(msg, level="INFO"):
|
||
config.log(msg, level)
|
||
|
||
|
||
def submit_export(session, begin, end):
|
||
"""提交交易记录导出任务。"""
|
||
payload = dict(config.EXPORT_TEMPLATE)
|
||
payload["startTime"] = begin
|
||
payload["endTime"] = end
|
||
_log(f"提交导出任务:{begin} ~ {end}", "DEBUG")
|
||
body = login_mod.api_post(session, config.API_EXPORT, payload)
|
||
if body.get("_empty"):
|
||
_log(f"导出任务已提交(HTTP {body.get('_status')},空响应属正常)")
|
||
else:
|
||
_log(f"导出任务响应:{str(body)[:200]}", "DEBUG")
|
||
return payload
|
||
|
||
|
||
def download_list(session):
|
||
"""下载中心列表(新→旧)。"""
|
||
body = login_mod.api_post(session, config.API_DOWNLOAD_LIST,
|
||
{"pageNum": 1, "pageSize": config.LIST_PAGE_SIZE})
|
||
data = (body or {}).get("data") or {}
|
||
return data.get("content") or []
|
||
|
||
|
||
def wait_new_record(session, before_ids, timeout=None, interval=None):
|
||
"""等下载中心出现本次新增且导出完成的记录。"""
|
||
timeout = timeout or config.POLL_TIMEOUT
|
||
interval = interval or config.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 config.TRADE_SOURCE and config.TRADE_SOURCE not in (rec.get("fileSource") or ""):
|
||
continue
|
||
status = str(rec.get("exportStatus") or "")
|
||
desc = rec.get("exportStatusDesc") or status
|
||
if status == config.EXPORT_STATUS_DONE 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} 秒仍未等到导出完成,可调大 POLL_TIMEOUT 或去平台下载中心确认")
|
||
|
||
|
||
def download_file(session, rec, out_path):
|
||
"""GET 预签名地址下载,落盘到 out_path。"""
|
||
url = rec.get("downloadUrl") or ""
|
||
if not url:
|
||
raise RuntimeError("下载记录里没有 downloadUrl")
|
||
_log(f"开始下载:{os.path.basename(out_path)}", "DEBUG")
|
||
resp = session.get(url, timeout=config.DOWNLOAD_TIMEOUT)
|
||
resp.raise_for_status()
|
||
content = resp.content
|
||
if not content:
|
||
raise RuntimeError("下载到的文件为空")
|
||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||
with open(out_path, "wb") as f:
|
||
f.write(content)
|
||
return len(content)
|
||
|
||
|
||
def mark_read(session, rec_id):
|
||
"""标记已读(失败只告警,不影响产物)。"""
|
||
if not rec_id:
|
||
return
|
||
try:
|
||
body = login_mod.api_post(session, config.API_MARK_READ + str(rec_id), {})
|
||
_log(f"已标记已读:{body.get('data') or body.get('message')}", "DEBUG")
|
||
except Exception as exc:
|
||
_log(f"标记已读失败(不影响文件):{exc}", "WARN")
|
||
|
||
|
||
def safe_name(text):
|
||
"""文件名清洗(商户名可能含空格/斜杠等)。"""
|
||
bad = '\\/:*?"<>|\r\n\t'
|
||
cleaned = "".join("_" if ch in bad else ch for ch in str(text or "")).strip(" .")
|
||
return cleaned or "商户"
|
||
|
||
|
||
def export_trade(account, password, save_dir, begin, end, stamp,
|
||
progress_from=0, progress_to=45, login_mode=None):
|
||
"""单账号完整导出。返回 {success, merchant, file, size, message}。
|
||
|
||
文件名 = {商户名}_交易记录_{日期区间}.xlsx(商户名登录后才拿到,故在函数内生成)。
|
||
login_mode:自动(接口登录)/ 人工登录(弹浏览器人工过验证码)。
|
||
"""
|
||
def step(pct):
|
||
span = progress_to - progress_from
|
||
config.progress(progress_from + int(span * pct / 100.0))
|
||
|
||
result = {"success": False, "merchant": "", "file": "", "size": 0, "message": ""}
|
||
|
||
step(5)
|
||
login_result = login_mod.ensure_login(account, password, login_mode)
|
||
if not login_result.get("success"):
|
||
result["message"] = login_result.get("message") or "登录失败"
|
||
return result
|
||
|
||
session = login_result["session"]
|
||
merchant = login_result.get("merchant") or account
|
||
result["merchant"] = merchant
|
||
file_name = f"{safe_name(merchant)}_{config.FILE_TITLE}_{stamp}.xlsx"
|
||
step(25)
|
||
|
||
before_ids = {rec.get("id") for rec in download_list(session)}
|
||
_log(f"[{merchant}] 提交前下载中心已有 {len(before_ids)} 条记录", "DEBUG")
|
||
|
||
submit_export(session, begin, end)
|
||
step(40)
|
||
|
||
_log(f"[{merchant}] 等待平台生成文件…")
|
||
rec = wait_new_record(session, before_ids)
|
||
_log(f"[{merchant}] 导出完成:{rec.get('fileName')}")
|
||
step(70)
|
||
|
||
out_path = os.path.join(save_dir, file_name)
|
||
size = download_file(session, rec, out_path)
|
||
mark_read(session, rec.get("id"))
|
||
step(100)
|
||
|
||
result.update({"success": True, "file": out_path, "size": size,
|
||
"message": f"{os.path.basename(out_path)}({size / 1024:.0f} KB)"})
|
||
_log(f"[{merchant}] 已落盘:{out_path}({size} 字节)")
|
||
return result
|