feat: 新增交通银行数据导出插件及测试通道机制
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 数据层(登录 + 检票员检票报表导出)。"""
|
||||
@@ -0,0 +1,222 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 管理端登录模块(纯接口,自包含)。
|
||||
|
||||
流程(2026-11 实测):
|
||||
1) GET /admin/api/checkCode?rand=<ms> 取图片验证码(JPEG 直出,需同一会话 Cookie);
|
||||
2) ddddocr 识别验证码;
|
||||
3) POST /admin/storeMerchant/logining JSON {username, password: RSA加密, checkcode, cipherText:1},
|
||||
返回 user.token 即管理端 tyAuthToken(后续 statisticsSupport 等接口用它)。
|
||||
|
||||
重试策略:验证码类失败最多 3 轮;账号/密码错误立即停止,绝不重试(避免锁号)。
|
||||
token 缓存:%LOCALAPPDATA%\\37duAutomation\\.sessions\\lotsmall_token.json({"accessToken": ...}),
|
||||
每次运行先用缓存 token 调 statisticsSupport 探测,失效再登录。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
|
||||
import requests
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 基础会话 ====================
|
||||
def new_session():
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": config.UA,
|
||||
"Origin": config.ADMIN_BASE,
|
||||
"Referer": config.ADMIN_BASE + "/admin/storeMerchant/login",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def fetch_code_image(session):
|
||||
"""取管理端图片验证码(JPEG 字节);验证码与当前会话 Cookie 绑定。"""
|
||||
resp = session.get(config.ADMIN_BASE + config.API_CHECKCODE,
|
||||
params={"rand": int(time.time() * 1000)}, timeout=config.TIMEOUT)
|
||||
if resp.status_code != 200 or not resp.content:
|
||||
raise RuntimeError(f"获取图片验证码失败(HTTP {resp.status_code})")
|
||||
if resp.content[:2] != b'\xff\xd8': # JPEG 魔数,避免把错误 JSON 当图片
|
||||
raise RuntimeError(f"图片验证码返回非图片:{resp.text[:120]}")
|
||||
return resp.content
|
||||
|
||||
|
||||
def ocr_code(img_bytes):
|
||||
"""ddddocr 识别验证码;长度不在合理区间视为识别失败。"""
|
||||
try:
|
||||
import ddddocr
|
||||
except ImportError:
|
||||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||||
code = ddddocr.DdddOcr(show_ad=False).classification(img_bytes).strip()
|
||||
if config.CAPTCHA_MIN_LEN <= len(code) <= config.CAPTCHA_MAX_LEN:
|
||||
return code
|
||||
return ""
|
||||
|
||||
|
||||
def rsa_encrypt(text):
|
||||
"""RSA PKCS#1 v1.5 加密 + URL 编码(与前端 setRSA 一致)。"""
|
||||
pem = ("-----BEGIN PUBLIC KEY-----\n" + config.RSA_PUBLIC_KEY +
|
||||
"\n-----END PUBLIC KEY-----")
|
||||
key = serialization.load_pem_public_key(pem.encode())
|
||||
cipher = key.encrypt(text.encode(), padding.PKCS1v15())
|
||||
return urllib.parse.quote(base64.b64encode(cipher).decode(), safe="")
|
||||
|
||||
|
||||
def do_login(session, account, password, code):
|
||||
"""账密登录。注意:管理端 apiPost 用 x-www-form-urlencoded(qs 序列化),不能发 JSON。"""
|
||||
payload = {
|
||||
"username": account,
|
||||
"password": rsa_encrypt(password),
|
||||
"checkcode": code,
|
||||
"cipherText": 1,
|
||||
}
|
||||
resp = session.post(config.ADMIN_BASE + config.API_ADMIN_LOGIN, data=payload,
|
||||
headers={"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"},
|
||||
timeout=config.TIMEOUT)
|
||||
try:
|
||||
return resp.json(), resp.text
|
||||
except ValueError:
|
||||
raise RuntimeError(f"登录接口返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
|
||||
|
||||
# ==================== token 缓存 ====================
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截文件。"""
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def load_token():
|
||||
if not os.path.exists(config.TOKEN_FILE):
|
||||
return ""
|
||||
try:
|
||||
with open(config.TOKEN_FILE, encoding='utf-8') as f:
|
||||
return str((json.load(f) or {}).get("accessToken") or "")
|
||||
except Exception as e:
|
||||
_log(f"读取 token 缓存失败:{e}", "WARN")
|
||||
return ""
|
||||
|
||||
|
||||
def save_token(token):
|
||||
try:
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({"accessToken": token}, ensure_ascii=False))
|
||||
_log(f"token 已缓存 → {config.TOKEN_FILE}")
|
||||
except Exception as e:
|
||||
_log(f"token 缓存写入失败(不影响本次运行):{e}", "WARN")
|
||||
|
||||
|
||||
# ==================== 管理端 token 探测 / 报表接入参数 ====================
|
||||
def fetch_report_params(token):
|
||||
"""statisticsSupport 探测 token 并取报表接入参数。
|
||||
|
||||
返回 data(含 authCode/appId/sign/timestamp/bigDataLoginAuthCode/corpCode);
|
||||
token 失效或返回异常时返回 None。
|
||||
"""
|
||||
if not token:
|
||||
return None
|
||||
ts = int(time.time() * 1000)
|
||||
url = (f"{config.ADMIN_BASE}{config.API_STATISTICS_SUPPORT}"
|
||||
f"?timestamp={ts}&reportId={config.REPORT_ID}"
|
||||
f"&reportUrl={config.REPORT_URL}&terminalTpe=0")
|
||||
try:
|
||||
resp = requests.get(url, headers={
|
||||
"tyAuthToken": token,
|
||||
"User-Agent": config.UA,
|
||||
"Referer": config.ADMIN_BASE + "/manage/",
|
||||
}, timeout=config.TIMEOUT)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
_log(f"statisticsSupport 探测异常:{e}", "WARN")
|
||||
return None
|
||||
if data.get("code") == config.CODE_TOKEN_EXPIRED:
|
||||
_log("管理端 token 已失效(请跳转到登录页)")
|
||||
return None
|
||||
if data.get("code") != config.CODE_OK or not data.get("data"):
|
||||
_log(f"statisticsSupport 失败:{str(data)[:200]}", "WARN")
|
||||
return None
|
||||
return data["data"]
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(account, password, force=False):
|
||||
"""确保存在可用的管理端 token。
|
||||
|
||||
先复用缓存 token(statisticsSupport 探测),失效再走账密登录。
|
||||
返回 dict:{success, token, message, relogin}
|
||||
"""
|
||||
account = (account or '').strip()
|
||||
password = (password or '').strip()
|
||||
|
||||
if not force:
|
||||
token = load_token()
|
||||
if token and fetch_report_params(token):
|
||||
_log("已通过缓存的 token 复用管理端登录态")
|
||||
return {"success": True, "token": token, "message": "复用缓存登录态", "relogin": False}
|
||||
|
||||
if not (account and password):
|
||||
msg = "登录账号/密码缺失:请在插件界面填写并保存配置"
|
||||
_log(msg, "ERROR")
|
||||
return {"success": False, "token": "", "message": msg, "relogin": False}
|
||||
|
||||
session = new_session()
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
_log(f"登录第 {attempt}/{config.RETRY_MAX} 轮")
|
||||
try:
|
||||
code = ocr_code(fetch_code_image(session))
|
||||
_log(f"图片验证码 OCR:{code or '识别失败'}")
|
||||
except Exception as e:
|
||||
last_msg = f"获取验证码异常:{e}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
if not code:
|
||||
last_msg = "本轮验证码未识别出来"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
try:
|
||||
resp, raw = do_login(session, account, password, code)
|
||||
except Exception as e:
|
||||
last_msg = f"登录请求异常:{e}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
if not isinstance(resp, dict):
|
||||
last_msg = f"登录返回异常:{raw[:300]}"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
|
||||
if resp.get("success"):
|
||||
user = resp.get("user") or {}
|
||||
token = str(user.get("token") or "")
|
||||
if not token:
|
||||
last_msg = "登录成功但未返回 user.token"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
_log(f"登录成功,token={token[:24]}...")
|
||||
save_token(token)
|
||||
return {"success": True, "token": token, "message": "登录成功", "relogin": True}
|
||||
|
||||
msg = str(resp.get("message") or "")
|
||||
last_msg = f"登录失败:{msg or raw[:300]}"
|
||||
_log(last_msg, "WARN")
|
||||
|
||||
if "双因子" in msg or resp.get("twoFactorValidationSwitch") == "T":
|
||||
return {"success": False, "token": "", "message": "账号开启了双因子验证,无法自动登录", "relogin": False}
|
||||
if "密码" in msg or "账号" in msg:
|
||||
return {"success": False, "token": "", "message": f"账号或密码错误,已停止:{msg}", "relogin": False}
|
||||
|
||||
return {"success": False, "token": "", "message": last_msg or "登录失败", "relogin": False}
|
||||
@@ -0,0 +1,222 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0077 携程数据导出 - 检票员检票报表导出(纯接口,自包含)。
|
||||
|
||||
链路(2026-11 实测):
|
||||
statisticsSupport(管理端 token 换 authCode/appId/sign/timestamp/userCode/corpCode)
|
||||
→ verifySaasAuthCode(换报表平台 JWT)
|
||||
→ preview(取 reportDetailId 与 reportColumnList)
|
||||
→ searchFilter(查询,判 total)
|
||||
→ total > 0 才 newExport(下载 xlsx 二进制)。
|
||||
|
||||
日期口径固定:昨天 00:00:00 ~ 今天 23:59:59;
|
||||
查询无数据(total 为 0 或缺失)直接跳过导出,返回 {"total": 0, "file": ""}。
|
||||
"""
|
||||
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 + "/",
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
def _verify_saas(session, auth_code, app_id):
|
||||
"""authCode/appId 换报表平台 JWT。"""
|
||||
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:{str(body)[:300]}")
|
||||
return jwt
|
||||
|
||||
|
||||
def _auth_headers(info, app_id, jwt):
|
||||
"""报表平台后续接口统一请求头(除 JWT 外还要带 authCode/appId/timestamp/sign)。"""
|
||||
return {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"timestamp": str(info["timestamp"]),
|
||||
"sign": info["sign"],
|
||||
"Authorization": jwt,
|
||||
"Content-Type": "application/json",
|
||||
"Origin": config.REPORT_BASE,
|
||||
"Referer": config.REPORT_BASE + "/",
|
||||
}
|
||||
|
||||
|
||||
def _preview(session, info, app_id, headers):
|
||||
"""取报表元数据:reportDetailId 与 reportColumnList。"""
|
||||
params = {
|
||||
"authCode": info["authCode"],
|
||||
"appId": app_id,
|
||||
"sign": info["sign"],
|
||||
"timestamp": info["timestamp"],
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"corpCode": info.get("corpCode"),
|
||||
"terminalTpe": 0,
|
||||
}
|
||||
url = config.REPORT_BASE + config.API_PREVIEW.format(report_id=config.REPORT_ID)
|
||||
resp = session.get(url, params=params, 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 {}
|
||||
detail_id = result.get("reportDetailId") or result.get("id")
|
||||
columns = result.get("reportColumnList") or []
|
||||
if not detail_id:
|
||||
raise RuntimeError(f"preview 未返回 reportDetailId:{str(body)[:300]}")
|
||||
return detail_id, columns
|
||||
|
||||
|
||||
def _query_body(info, app_id, detail_id, columns, begin, end):
|
||||
"""searchFilter / newExport 共用请求体(newExport 再追加 reportColumnFilterList)。"""
|
||||
return {
|
||||
"shareMode": 0,
|
||||
"reportType": 0,
|
||||
"id": detail_id,
|
||||
"params": {
|
||||
"terminalTpe": config.TERMINAL_TPE,
|
||||
"merchant_id": config.MERCHANT_ID,
|
||||
"userInfoId": config.USER_INFO_ID,
|
||||
"corpCode": info.get("corpCode"),
|
||||
"appId": app_id,
|
||||
"userCode": info.get("bigDataLoginAuthCode"),
|
||||
"subAccountId": config.SUB_ACCOUNT_ID,
|
||||
"roleType": config.ROLE_TYPE,
|
||||
"pageIndex": config.PAGE_INDEX,
|
||||
"pageSize": config.PAGE_SIZE,
|
||||
"beginTradeDate": begin,
|
||||
"endTradeDate": end,
|
||||
"id": str(config.REPORT_ID),
|
||||
},
|
||||
"reportColumnDisplayList": columns,
|
||||
}
|
||||
|
||||
|
||||
def _search(session, headers, body):
|
||||
"""查询报表,返回 total(0 或缺省即无数据)。"""
|
||||
resp = session.post(config.REPORT_BASE + config.API_SEARCH,
|
||||
headers=headers, json=body, timeout=config.TIMEOUT)
|
||||
try:
|
||||
result = (resp.json() or {}).get("result") or {}
|
||||
except ValueError:
|
||||
raise RuntimeError(f"searchFilter 返回非 JSON(HTTP {resp.status_code}):{resp.text[:200]}")
|
||||
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 并落盘,返回文件路径。"""
|
||||
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=''):
|
||||
"""查询并导出「检票员检票报表」。
|
||||
|
||||
返回:{'total': 查询总数, 'file': 落盘路径(无数据时为空字符串)}
|
||||
登录/接口失败抛 RuntimeError(账密错误立即停止,不重试)。
|
||||
"""
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
begin, end = 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) 登录(优先复用缓存 token)
|
||||
login = lotsmall_login.ensure_login(account, password, force=(attempt > 1))
|
||||
if not login.get("success"):
|
||||
msg = login.get("message") or "登录失败"
|
||||
if "账号或密码错误" in msg or "缺失" in msg:
|
||||
raise AuthError(msg)
|
||||
raise RuntimeError(f"登录失败:{msg}")
|
||||
info = lotsmall_login.fetch_report_params(login.get("token"))
|
||||
if not info:
|
||||
raise RuntimeError("取不到报表接入参数(token 可能已失效)")
|
||||
app_id = str(info.get("appId") or config.APP_ID_DEFAULT)
|
||||
for key in ("authCode", "sign", "timestamp"):
|
||||
if not info.get(key):
|
||||
raise RuntimeError(f"statisticsSupport 缺少 {key}:{str(info)[:300]}")
|
||||
config.progress(25)
|
||||
|
||||
# 2) 换 JWT → preview
|
||||
session = _report_session()
|
||||
jwt = _verify_saas(session, info["authCode"], app_id)
|
||||
headers = _auth_headers(info, app_id, jwt)
|
||||
detail_id, columns = _preview(session, info, app_id, headers)
|
||||
_log(f"报表元数据:reportDetailId={detail_id},列数={len(columns)}")
|
||||
config.progress(45)
|
||||
|
||||
# 3) 查询判有无数据(无数据跳过导出)
|
||||
body = _query_body(info, app_id, detail_id, columns, begin, end)
|
||||
total = _search(session, headers, body)
|
||||
if total <= 0:
|
||||
_log("查询无数据,跳过导出")
|
||||
config.progress(100)
|
||||
return {'total': 0, 'file': ''}
|
||||
config.progress(65)
|
||||
|
||||
# 4) 导出
|
||||
body["reportColumnFilterList"] = [{"reportDetailId": detail_id}]
|
||||
path = _export(session, headers, 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}")
|
||||
Reference in New Issue
Block a user