195 lines
8.7 KiB
Python
195 lines
8.7 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""交通银行数据导出 - webhost 场景插件(XQ0076)
|
||
|
||
流程(纯接口,不点页面):
|
||
1) 账密自动登录商户服务门户(政策页同意 + 跳过 APP 扫码授权全自动;交行 token 在 sessionStorage,
|
||
关浏览器即失效,故每次运行都要登一次),并 hook 页面请求捕获正式 JWT;
|
||
2) 注入国密通道(借用页面自带 KeyouCryptography:SM4-ECB + SM2 签名),
|
||
接口:MSNGTQ/0002 查明细 → 有无数据判定 → MSNGTO/0012 提交导出 →
|
||
0013 轮询状态 → downloadMchtFile 取 OSS 直链 → 下载 zip → 解压 csv;
|
||
3) 全程限流(默认 1s/次,轮询 3s),避免触发银行风控。
|
||
"""
|
||
import datetime
|
||
import os
|
||
import time
|
||
|
||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||
|
||
from . import config
|
||
from .data import bank_api, bank_export, bank_login
|
||
|
||
|
||
def _parse_date(text):
|
||
return datetime.datetime.strptime(str(text).strip(), config.DATE_FMT).date()
|
||
|
||
|
||
def resolve_range(fields):
|
||
"""计算导出区间(date 对象,含首尾)。
|
||
|
||
优先级:`date_from` 有值 → 按自定义区间;
|
||
否则按 `date_mode`:yesterday=昨天单日 / today=今天单日 /
|
||
month_to_today=本月1日至今 / **prev_today(默认)= 昨天 ~ 今天(时间段)**。
|
||
"""
|
||
today = datetime.date.today()
|
||
raw_from = str(fields.get('date_from') or '').strip()
|
||
raw_to = str(fields.get('date_to') or '').strip()
|
||
if raw_from:
|
||
d0 = _parse_date(raw_from)
|
||
d1 = _parse_date(raw_to) if raw_to else d0
|
||
if d1 < d0:
|
||
d0, d1 = d1, d0
|
||
return d0, d1
|
||
|
||
mode = str(fields.get('date_mode') or 'prev_today').strip().lower()
|
||
if mode == 'today':
|
||
return today, today
|
||
if mode == 'yesterday':
|
||
y = today - datetime.timedelta(days=1)
|
||
return y, y
|
||
if mode == 'month_to_today':
|
||
return today.replace(day=1), today
|
||
# 默认:昨天 ~ 今天(与页面不选日期时的默认时间段一致)
|
||
return today - datetime.timedelta(days=1), today
|
||
|
||
|
||
def _diagnose_decrypt(page):
|
||
"""DEBUG 专用:让页面自己发一次交易流水查询,捕获它真实的响应解密方式。
|
||
|
||
背景:我们手动加密的请求服务端能受理(返回合法密文),但响应解密参数与请求不同,
|
||
需要观察页面自身解密调用(方法名 / 入参 / 密钥)才能对齐。
|
||
"""
|
||
config.log('【诊断】开始捕获页面自身的响应解密方式…', 'WARN')
|
||
try:
|
||
page.get(config.SITE_URL + '#/' + config.TRADE_HASH)
|
||
time.sleep(8)
|
||
bank_api.diagnose_init(page)
|
||
clicked = False
|
||
for el in page.eles('tag:button'):
|
||
try:
|
||
if el.states.is_displayed and ''.join((el.text or '').split()) == '查询':
|
||
el.click()
|
||
clicked = True
|
||
break
|
||
except Exception:
|
||
continue
|
||
config.log(f'【诊断】页面查询按钮点击:{clicked}', 'WARN')
|
||
time.sleep(10)
|
||
report = bank_api.diagnose_report(page)
|
||
if not report:
|
||
config.log('【诊断】未捕获到解密调用(解密可能封装在闭包内,非 window 对象方法)', 'WARN')
|
||
for it in report:
|
||
config.log(f"【诊断】{it.get('t')} args={it.get('a')} ret={it.get('r')}", 'WARN')
|
||
except Exception as e:
|
||
config.log(f'【诊断】异常:{e}', 'WARN')
|
||
|
||
|
||
class BankCommExportPlugin(ScenePlugin):
|
||
id = 'xq0076'
|
||
name = '交通银行数据导出'
|
||
version = '1.2.4'
|
||
description = ('交通银行商户服务门户(merchantapp.bankcomm.com)商户验券交易流水导出:'
|
||
'账密自动登录(政策同意 + 跳过扫码全自动),接口查询判有无数据后导出,'
|
||
'下载 zip 并解压 csv(GBK),全程限流')
|
||
platform = '' # 交行自带账密登录,不使用底座共享登录态
|
||
uses_month = False
|
||
capabilities = ['xq0076']
|
||
permissions = {'platforms': []}
|
||
# 与 plugin.json.fields 一致
|
||
fields = {
|
||
'username': {'type': 'string', 'title': '登录账号', 'default': '',
|
||
'description': '手机号 / BOC / MER 账号'},
|
||
'password': {'type': 'string', 'title': '商服密码', 'default': '',
|
||
'description': '商户服务门户登录密码(明文存本地配置)'},
|
||
'date_mode': {'type': 'string', 'title': '日期口径', 'default': 'prev_today',
|
||
'description': 'prev_today=昨天~今天(默认)/ yesterday=昨天单日 / today=今天 / month_to_today=本月至今 / custom=自定义'},
|
||
'date_from': {'type': 'string', 'title': '开始日期', 'default': '',
|
||
'description': 'yyyy-MM-dd;留空=按日期口径(默认昨天~今天)'},
|
||
'date_to': {'type': 'string', 'title': '结束日期', 'default': '',
|
||
'description': 'yyyy-MM-dd;留空=与开始日期同一天'},
|
||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': '',
|
||
'description': '留空=D:\\资料\\银行\\交通银行数据导出'},
|
||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||
}
|
||
|
||
def run(self, fields, ctx) -> dict:
|
||
fields = fields or {}
|
||
config.set_log(ctx.log)
|
||
config.set_progress(ctx.progress)
|
||
config.set_debug(bool(fields.get('debug_mode')))
|
||
|
||
username = str(fields.get('username') or '').strip()
|
||
password = str(fields.get('password') or '').strip()
|
||
if not (username and password):
|
||
raise RuntimeError('请在插件界面填写交行商户门户的登录账号与商服密码')
|
||
|
||
d0, d1 = resolve_range(fields)
|
||
save_dir = str(fields.get('save_dir') or '').strip().strip('"') or config.default_output_dir()
|
||
os.makedirs(save_dir, exist_ok=True)
|
||
# 商户号由门户页面自动识别(默认已带),商户账号就是登录账号,界面不再开放填写
|
||
mcht_id = ''
|
||
mcht_acc = username
|
||
|
||
config.log(f'导出区间:{d0} ~ {d1}')
|
||
config.log(f'保存目录:{save_dir}')
|
||
config.progress(5)
|
||
|
||
page = bank_login.open_browser()
|
||
try:
|
||
login = bank_login.ensure_login(page, username, password)
|
||
if not login.get('success'):
|
||
raise RuntimeError(f"登录失败:{login.get('message')}")
|
||
config.progress(25)
|
||
|
||
# 关键:SM4 key 与 SM2 私钥都是「会话级」的,必须让页面自己发一次请求把它们抓下来
|
||
bank_api.install_capture(page)
|
||
page.get(config.SITE_URL + '#/' + config.TRADE_HASH)
|
||
time.sleep(config.PAGE_SETTLE + 3)
|
||
bank_api.wait_session_keys(page, timeout=45)
|
||
time.sleep(config.KEY_SETTLE) # 让刚才页面查询的限流窗口过去,避免 AM00049
|
||
bank_api.install_auth_hook(page)
|
||
try:
|
||
bank_api.wait_token(page, timeout=60)
|
||
except Exception as e:
|
||
config.log(f'取登录票据失败:{e}', 'WARN')
|
||
config.progress(35)
|
||
|
||
result = bank_export.export_trade_flow(
|
||
page, d0, d1, save_dir=save_dir,
|
||
mcht_id=mcht_id, mcht_acc=mcht_acc, tag='商户验券')
|
||
config.progress(95)
|
||
finally:
|
||
if config.KEEP_BROWSER:
|
||
config.log('浏览器已保留(下次运行可直接复用登录态,可手动关闭)')
|
||
else:
|
||
try:
|
||
page.quit()
|
||
except Exception:
|
||
pass
|
||
|
||
config.progress(100)
|
||
if result.get('skipped'):
|
||
return {
|
||
'summary': f"无数据,未导出({d0} ~ {d1})",
|
||
'detail': {'range': f'{d0} ~ {d1}', 'skipped': True, 'reason': result.get('reason')},
|
||
'path': save_dir,
|
||
}
|
||
|
||
files = [result.get('zip')] + list(result.get('csv') or [])
|
||
return {
|
||
'summary': f"商户验券流水导出完成:{os.path.basename(result.get('zip') or '')}",
|
||
'detail': {
|
||
'range': f'{d0} ~ {d1}',
|
||
'zip': result.get('zip'),
|
||
'csv': result.get('csv') or [],
|
||
'size': result.get('size'),
|
||
'task_id': result.get('task_id'),
|
||
'state': result.get('state'),
|
||
'files': files,
|
||
'save_dir': save_dir,
|
||
},
|
||
'path': save_dir,
|
||
}
|
||
|
||
|
||
PLUGINS.append(BankCommExportPlugin())
|