feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 259369953f
commit 526116af83
494 changed files with 66923 additions and 2714 deletions
+159
View File
@@ -0,0 +1,159 @@
# -*- coding: utf-8 -*-
"""打款记录下载(h5 账单页,iframe 内 smartBill 三个接口)。
链路(实测):
① 查询 POST /gw/smartBill/paymentlist body{payTime,productCodeList,payStatusList,shopList,pageIndex,pageSize}
② 生成 POST /gw/smartBill/paymentdownload body 同上 + downloadFileType=6
③ 记录 GET /gw/smartBill/paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6
(必须带 downloadFileType + 分页参数,缺了返回 code=500)
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
"""
import json
import os
import time
from datetime import datetime
from .. import config
from . import browser
def _find_frame(page, timeout=30):
deadline = time.time() + timeout
while time.time() < deadline:
try:
for f in page.get_frames():
try:
if 'merchant-bill' in (f.url or ''):
return f
except Exception:
continue
except Exception:
pass
time.sleep(1)
return None
def _history_items(frame):
url = (f'{config.PAYMENT_HISTORY_API}?pageIndex=0&pageSize=20'
f'&downloadFileType={config.PAYMENT_FILE_TYPE}')
data = browser.api_json(frame, 'GET', url) or {}
return (data.get('data') or {}).get('details') or []
def _throttle_seconds(msg):
import re
m = re.search(r'(\d+)\s*秒', msg or '')
return int(m.group(1)) if m else 0
def _age_minutes(add_time):
try:
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
return (datetime.now() - dt).total_seconds() / 60.0
except Exception:
return 1e9
def download(page, d_from, d_to, save_dir, dry_run=False):
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
tag = d_from.replace('-', '') if d_from == d_to else \
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
match_key = d_from
config.log(f'打开打款记录页:{config.PAYMENT_PAGE_URL}', 'DEBUG')
page.get(config.PAYMENT_PAGE_URL)
frame = _find_frame(page)
if not frame:
return {'ok': False, 'message': '未找到账单 iframe(登录态可能已失效)'}
config.log(f'账单 iframe:{frame.url}', 'DEBUG')
# ① 先查询(页面同款顺序:查询出数据后下载按钮才可用)
query = {
'payTime': f'{d_from},{d_to}',
'productCodeList': [], 'payStatusList': [], 'shopList': [],
'pageIndex': 0, 'pageSize': 10,
}
q = browser.api_json(frame, 'POST', config.PAYMENT_LIST_API, query)
if q is None:
return {'ok': False, 'message': '打款记录查询失败'}
qdata = q.get('data') or {}
total = qdata.get('totalCount')
details = qdata.get('details') or []
config.log(f'查询 {d_from}~{d_to}:totalCount={total}')
if details:
s = details[0]
config.log(f' 首条 {s.get("payTime")} | {s.get("productCodeName")} | '
f'{s.get("amount")} | {s.get("payStatusName")}')
if not total:
return {'ok': False, 'message': f'{d_from}~{d_to} 没有打款记录'}
# ② 已有记录时效内复用
before = _history_items(frame)
before_ids = {it.get('id') for it in before}
target = None
cands = [it for it in before
if match_key in (it.get('timeInterval') or '') and it.get('downloadLink')]
fresh = [it for it in cands if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
if fresh and not dry_run:
target = fresh[0]
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
elif cands:
config.log('同区间记录已过期,重新生成以取最新数据')
# ③ 生成 + 轮询
if not target and not dry_run:
payload = dict(query)
payload.pop('pageIndex', None)
payload.pop('pageSize', None)
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
for attempt in range(1, config.RETRY_MAX + 1):
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
if resp and resp.get('code') == 200:
config.log('生成任务已受理')
break
msg = (resp or {}).get('message') or '无响应'
wait = _throttle_seconds(msg)
if wait and attempt < config.RETRY_MAX:
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
'WARN')
time.sleep(wait + 3)
continue
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
deadline = time.time() + config.RECORD_SECONDS
while time.time() < deadline:
time.sleep(config.POLL_SECONDS)
items = _history_items(frame)
for it in items:
if it.get('id') in before_ids:
continue
if match_key not in (it.get('timeInterval') or ''):
continue
target = it
break
if target:
break
config.log(' 等待账单生成…')
if dry_run:
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
if not target:
return {'ok': False, 'message': f'{config.RECORD_SECONDS}s 内未拿到可下载记录'}
link = target.get('downloadLink')
if not link:
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
path = os.path.join(save_dir, f'{config.PAYMENT_NAME_KEY}_{tag}.xlsx')
config.log(f'下载 → {path}')
size = browser.download_file(link, path)
if not size:
return {'ok': False, 'message': '打款记录下载失败'}
info = browser.read_xlsx_summary(path)
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}