feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -0,0 +1,152 @@
|
||||
"""检票员报表全自动导出(纯接口版)。
|
||||
|
||||
流程:登录 lotsmall -> statisticsSupport 取 authCode/sign/appId/userCode
|
||||
-> verifySaasAuthCode 换 JWT -> preview 取报表元数据
|
||||
-> searchFilter 查询 -> total>0 才 newExport 下载 xlsx(查询无数据直接跳过)
|
||||
|
||||
账号密码写在同目录 account.json:{"account": "...", "password": "..."}
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import requests
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import lotsmall_login_test as login_mod # noqa: E402
|
||||
|
||||
TOKEN_FILE = os.path.join(os.environ["TEMP"], "lotsmall_token.json")
|
||||
OUT_DIR = os.path.join(os.environ["TEMP"], "lotsmall_export")
|
||||
REPORT_ID = 3066
|
||||
REPORT_URL = f"https://platform-report-sh1.zhiyoubao.com/reportView?id={REPORT_ID}"
|
||||
BEGIN = "2026-11-01 00:00:00"
|
||||
END = "2026-11-05 23:59:59"
|
||||
|
||||
ADMIN = "https://www.lotsmall.cn"
|
||||
RPT = "https://platform-report-sh1.zhiyoubao.com"
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0 Safari/537.36"
|
||||
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
|
||||
|
||||
def load_token():
|
||||
try:
|
||||
return json.load(open(TOKEN_FILE, encoding="utf-8")).get("accessToken") or ""
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def admin_session(token):
|
||||
s = requests.Session()
|
||||
s.headers.update({"tyAuthToken": token, "User-Agent": UA, "Referer": ADMIN + "/manage/"})
|
||||
return s
|
||||
|
||||
|
||||
def fetch_report_params(token):
|
||||
"""statisticsSupport 拿报表接入参数;token 失效时返回 None。"""
|
||||
ts = int(time.time() * 1000)
|
||||
url = (f"{ADMIN}/statistics/webApi/statisticsSupport/"
|
||||
f"?timestamp={ts}&reportId={REPORT_ID}&reportUrl={REPORT_URL}&terminalTpe=0")
|
||||
r = admin_session(token).get(url, timeout=20)
|
||||
try:
|
||||
j = r.json()
|
||||
except ValueError:
|
||||
return None
|
||||
if j.get("code") != 200 or not j.get("data"):
|
||||
print("statisticsSupport 失败:", r.text[:200])
|
||||
return None
|
||||
return j["data"]
|
||||
|
||||
|
||||
def ensure_token():
|
||||
token = load_token()
|
||||
if token:
|
||||
info = fetch_report_params(token)
|
||||
if info:
|
||||
return token, info
|
||||
print("token 已过期,重新登录...")
|
||||
if not login_mod.main():
|
||||
raise SystemExit("登录失败,请检查 account.json 里的账号密码")
|
||||
token = load_token()
|
||||
info = fetch_report_params(token)
|
||||
if not info:
|
||||
raise SystemExit("登录后仍取不到报表接入参数")
|
||||
return token, info
|
||||
|
||||
|
||||
def main():
|
||||
token, info = ensure_token()
|
||||
auth_code = info["authCode"]
|
||||
app_id = info.get("appId", "xj")
|
||||
sign = info["sign"]
|
||||
rpt_ts = info["timestamp"]
|
||||
user_code = info.get("bigDataLoginAuthCode")
|
||||
corp_code = info.get("corpCode")
|
||||
print(f"authCode={auth_code} appId={app_id} sign={sign} userCode={user_code} corpCode={corp_code}")
|
||||
|
||||
rs = requests.Session()
|
||||
rs.headers.update({"User-Agent": UA, "Origin": RPT})
|
||||
|
||||
rv = rs.get(f"{RPT}/api/partner/auth/verifySaasAuthCode",
|
||||
params={"authCode": auth_code, "appId": app_id}, timeout=20)
|
||||
print("verifySaasAuthCode:", rv.status_code, rv.text[:200])
|
||||
jwt = ((rv.json().get("result") or {}).get("token")
|
||||
or (rv.json().get("result") or {}).get("accessToken")
|
||||
or (rv.json().get("data") or {}).get("token"))
|
||||
if not jwt:
|
||||
raise SystemExit("未取到 JWT,结构:" + rv.text[:500])
|
||||
|
||||
hdr = {
|
||||
"authCode": auth_code, "appId": app_id, "timestamp": str(rpt_ts), "sign": sign,
|
||||
"Authorization": jwt, "Content-Type": "application/json",
|
||||
"Origin": RPT, "Referer": RPT + "/",
|
||||
}
|
||||
q = {"authCode": auth_code, "appId": app_id, "sign": sign, "timestamp": rpt_ts,
|
||||
"userCode": user_code, "corpCode": corp_code, "terminalTpe": 0}
|
||||
|
||||
pv = rs.get(f"{RPT}/api/report/preview/{REPORT_ID}", params=q, headers=hdr, timeout=20)
|
||||
print("preview:", pv.status_code, pv.text[:200])
|
||||
meta = pv.json().get("result") or {}
|
||||
detail_id = meta.get("reportDetailId") or meta.get("id") or 3275
|
||||
columns = meta.get("reportColumnList") or []
|
||||
|
||||
body = {
|
||||
"shareMode": 0, "reportType": 0, "id": detail_id,
|
||||
"params": {
|
||||
"terminalTpe": "0", "merchant_id": "23985", "userInfoId": "59567",
|
||||
"corpCode": corp_code, "appId": app_id,
|
||||
"userCode": user_code, "subAccountId": "59925", "roleType": "4",
|
||||
"pageIndex": 1, "pageSize": 50,
|
||||
"beginTradeDate": BEGIN, "endTradeDate": END,
|
||||
"id": str(REPORT_ID),
|
||||
},
|
||||
"reportColumnDisplayList": columns,
|
||||
}
|
||||
resp = rs.post(f"{RPT}/api/report/searchFilter", headers=hdr, json=body, timeout=30)
|
||||
print("searchFilter:", resp.status_code, resp.text[:200])
|
||||
rsl = (resp.json().get("result") or {}).get("reportSearchList") or [{}]
|
||||
total = rsl[0].get("total")
|
||||
print("total =", total, "rows =", len(rsl[0].get("rows") or []))
|
||||
|
||||
if not total:
|
||||
print("查询无数据,跳过导出")
|
||||
return True
|
||||
|
||||
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
|
||||
ex = rs.post(f"{RPT}/api/report/newExport", headers=hdr, json=body, timeout=120)
|
||||
print("newExport:", ex.status_code, ex.headers.get("content-disposition"), len(ex.content))
|
||||
if ex.content[:2] != b"PK":
|
||||
print("导出返回非 xlsx:", ex.text[:300])
|
||||
return False
|
||||
out = os.path.join(OUT_DIR, f"检票员检票报表_{int(time.time())}.xlsx")
|
||||
open(out, "wb").write(ex.content)
|
||||
print("已保存:", out)
|
||||
return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(0 if main() else 1)
|
||||
Reference in New Issue
Block a user