build(desktop): 升级 electron-shell 版本至 1.6.3 并调整插件执行超时配置
- 插件执行超时默认延长至 6 小时,支持插件单独配置超时时间 - 新增插件根目录迁移逻辑,解决旧版权限问题 - 新增多个服务端实体、DTO、配置模块等基础代码 - 新增插件 UI 模板及相关静态资源
This commit is contained in:
@@ -1,201 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""金色印象通联数据导出 - webhost 场景插件(XQ0045 + XQ0046 合并版)
|
||||
|
||||
通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:
|
||||
- XQ0045 按日:导某一天(YYYY-MM-DD)的交易;
|
||||
- XQ0046 按月:导某个月(YYYY-MM)的交易;
|
||||
服务端导出接口忽略商户参数、始终返回账号全量结果集(实测),因此每个日期只导一份
|
||||
全量文件(含账号下所有商户),直存本地,不再按商户拆分。
|
||||
|
||||
个性化设计:
|
||||
- 通联登录账号密码由插件界面配置经 fields 注入(plugin_configs 本机保存,下次免填);
|
||||
- 浏览器现场真登录(固定默认用户目录 + ddddocr 验证码识别),登录后转 requests.Session
|
||||
直调导出接口(服务端有 Referer 外链校验,插件内统一带 Referer);
|
||||
- 日期支持多个(逗号分隔,逐个导出);mode=日+月 时按日期串格式自动识别日/月;
|
||||
- 交易查询 xlsx 下载后自动按商户分组拆成 3 个工作簿:综合门店(5 家门店商户)、
|
||||
品牌管理公司(重庆金色印象品牌管理有限公司)、其他账号(其余商户),原全量文件保留。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import allinpay_login, allinpay_export, xlsx_split
|
||||
|
||||
MODE_DAY = '日'
|
||||
MODE_MONTH = '月'
|
||||
MODE_BOTH = '日+月'
|
||||
|
||||
CONTENT_TRX = '交易查询'
|
||||
CONTENT_BILL = '账单'
|
||||
CONTENT_BOTH = '两个都导'
|
||||
|
||||
|
||||
def _default_save_dir():
|
||||
return str(Path(config.get_desktop()) / f"金色印象通联数据_{datetime.now():%Y%m%d}")
|
||||
|
||||
|
||||
def _default_day():
|
||||
"""昨日(YYYY-MM-DD),日期留空时由插件按执行日推算(定时任务无需固定日期)。"""
|
||||
return f"{date.today() - timedelta(days=1):%Y-%m-%d}"
|
||||
|
||||
|
||||
def _default_month():
|
||||
"""上月(YYYY-MM),月份留空时由插件按执行日推算。"""
|
||||
first = date.today().replace(day=1)
|
||||
return f"{first - timedelta(days=1):%Y-%m}"
|
||||
|
||||
|
||||
def _build_tasks(mode, day_date, month_date):
|
||||
"""按执行模式组合 (模式, 日期) 任务列表(留空默认值已在 run() 解析区补齐)。"""
|
||||
tasks = []
|
||||
if mode in (MODE_DAY, MODE_BOTH) and day_date:
|
||||
tasks.append((MODE_DAY, day_date))
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and month_date:
|
||||
tasks.append((MODE_MONTH, month_date))
|
||||
if not tasks:
|
||||
raise RuntimeError("请选择按日导出的日期和/或按月导出的月份")
|
||||
return tasks
|
||||
|
||||
|
||||
class TongLianExportPlugin(ScenePlugin):
|
||||
id = "xq0045_xq0046"
|
||||
name = "金色印象通联数据导出"
|
||||
version = "1.0.12"
|
||||
description = ("通联支付交易数据自动导出:XQ0045 按日 / XQ0046 按月,"
|
||||
"账号全量数据导出(含全部商户),服务端生成文件直存本地,"
|
||||
"并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿")
|
||||
platform = "" # 通联自带登录页(验证码),插件内现场真登录,不使用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ["xq0045_xq0046"]
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致(ui=true 前端自渲染,此处分层作为参数契约文档)
|
||||
fields = {
|
||||
"mode": {"type": "string", "title": "执行模式", "default": MODE_BOTH,
|
||||
"enum": [MODE_BOTH, MODE_DAY, MODE_MONTH]},
|
||||
"content": {"type": "string", "title": "导出内容", "default": CONTENT_BOTH,
|
||||
"enum": [CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL]},
|
||||
"day_date": {"type": "string", "format": "date", "title": "按日导出(数据起始日)", "default": "",
|
||||
"description": "留空=昨日(插件按执行日推算)"},
|
||||
"month_date": {"type": "string", "format": "month", "title": "按月导出", "default": "",
|
||||
"description": "留空=上月(插件按执行日推算)"},
|
||||
"tl_username": {"type": "string", "title": "通联登录账号", "default": ""},
|
||||
"tl_password": {"type": "string", "title": "通联登录密码", "default": ""},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": ""},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx) -> dict:
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
|
||||
# ---------- 解析与校验 ----------
|
||||
mode = str(fields.get("mode") or MODE_BOTH).strip()
|
||||
content = str(fields.get("content") or CONTENT_BOTH).strip()
|
||||
username = str(fields.get("tl_username") or "").strip()
|
||||
password = str(fields.get("tl_password") or "")
|
||||
day_date = str(fields.get("day_date") or "").strip()
|
||||
month_date = str(fields.get("month_date") or "").strip()
|
||||
save_dir = str(fields.get("save_dir") or "").strip().strip('"') or _default_save_dir()
|
||||
|
||||
if not username or not password:
|
||||
raise RuntimeError("通联登录账号/密码缺失:请在插件界面填写并保存配置后重试")
|
||||
if mode not in (MODE_BOTH, MODE_DAY, MODE_MONTH):
|
||||
raise RuntimeError(f"未知执行模式:{mode}")
|
||||
if content not in (CONTENT_BOTH, CONTENT_TRX, CONTENT_BILL):
|
||||
raise RuntimeError(f"未知导出内容:{content}")
|
||||
|
||||
do_trx = content in (CONTENT_TRX, CONTENT_BOTH)
|
||||
do_bill = content in (CONTENT_BILL, CONTENT_BOTH)
|
||||
# 日期留空 = 插件内按执行日推算默认值(按日→昨日、按月→上月),
|
||||
# 定时任务方案无需固定日期,到点自动导最近的昨日/上月
|
||||
if mode in (MODE_DAY, MODE_BOTH) and not day_date:
|
||||
day_date = _default_day()
|
||||
ctx.log(f"按日导出未选日期,默认导昨日:{day_date}")
|
||||
if mode in (MODE_MONTH, MODE_BOTH) and not month_date:
|
||||
month_date = _default_month()
|
||||
ctx.log(f"按月导出未选月份,默认导上月:{month_date}")
|
||||
tasks = _build_tasks(mode, day_date, month_date)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"导出内容:{content},模式:{mode},任务 {len(tasks)} 项,保存目录:{save_dir}")
|
||||
|
||||
# ---------- 登录 ----------
|
||||
ctx.progress(3)
|
||||
ctx.log("开始通联平台登录(接口优先,浏览器兜底)…")
|
||||
session = allinpay_login.tl_login(username, password)
|
||||
if session is None:
|
||||
raise RuntimeError("通联平台登录失败(账号密码错误或验证码多次识别失败),详见日志")
|
||||
ctx.progress(10)
|
||||
|
||||
saved, failed = [], []
|
||||
|
||||
# ---------- 交易查询导出(15~70:每个任务导一份账号全量,服务端忽略商户参数) ----------
|
||||
if do_trx:
|
||||
# 服务端 cusid 不能传空串(传空会直接 504),但会忽略其筛选语义、始终返回
|
||||
# 账号全量结果集;故取账号下首个真实商户号作为种子参数即可。
|
||||
ctx.log("获取账号商户列表(取首个商户号作查询种子,服务端返回全量)…")
|
||||
cus_list = allinpay_export.get_cus_list(session)
|
||||
seed_cusid = cus_list[0]['key'] if cus_list else ''
|
||||
ctx.log(f"账号下商户 {len(cus_list)} 个,查询种子商户号:{seed_cusid}")
|
||||
if not seed_cusid:
|
||||
raise RuntimeError("获取商户列表失败:账号下无商户,无法发起导出")
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"交易[{m} {d}](账号全量)"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
start, end = allinpay_export.build_date_range(m, d)
|
||||
ctx.log(f" 查询区间 {start} ~ {end}")
|
||||
fid = allinpay_export.start_export(session, seed_cusid, start, end)
|
||||
ctx.log(f" 导出任务已提交 fid={fid},等待服务端生成…")
|
||||
allinpay_export.wait_export_done(session, fid)
|
||||
url = allinpay_export.get_download_url(session, fid)
|
||||
ctx.log(" 开始下载导出文件…")
|
||||
path = allinpay_export.download_file(session, url, save_dir, f"{m}交易查询结果_{d}")
|
||||
saved.append(path)
|
||||
# 按商户分组拆分(综合门店/品牌管理公司/其他账号),失败不影响原始文件
|
||||
try:
|
||||
ctx.log(" 按商户分组拆分为 3 个工作簿…")
|
||||
saved.extend(xlsx_split.split_trx_file(path))
|
||||
except Exception as e:
|
||||
ctx.log(f" 按商户拆分失败(原始全量文件已保存):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
ctx.log(f" 交易导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(15 + int(55 * done / max(1, units)))
|
||||
ctx.progress(70)
|
||||
|
||||
# ---------- 账单导出(70~95,主账号 zip 下载 + 解压) ----------
|
||||
if do_bill:
|
||||
units = len(tasks)
|
||||
done = 0
|
||||
for m, d in tasks:
|
||||
done += 1
|
||||
label = f"账单[{m} {d}]"
|
||||
ctx.log(f"--- [{done}/{units}] 导出 {label} ---")
|
||||
try:
|
||||
bill_type = 'month' if m == MODE_MONTH else 'day'
|
||||
_, extract_dir = allinpay_export.bill_download(
|
||||
session, d, bill_type, save_dir)
|
||||
saved.append(extract_dir)
|
||||
except Exception as e:
|
||||
ctx.log(f" 账单导出失败:{e}", "ERROR")
|
||||
failed.append(f"{label}[{e}]")
|
||||
ctx.progress(70 + int(25 * done / max(1, units)))
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
notes = [f"已保存 {len(saved)} 个文件/目录:"] + [f" {p}" for p in saved]
|
||||
if failed:
|
||||
notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}")
|
||||
summary = (f"通联数据导出完成(部分失败):成功 {len(saved)} 个,"
|
||||
f"失败 {len(failed)} 项 → {save_dir}")
|
||||
else:
|
||||
summary = f"通联数据导出完成:共 {len(saved)} 个文件/目录 → {save_dir}"
|
||||
return {"summary": summary, "rows": [], "notes": notes}
|
||||
|
||||
|
||||
PLUGINS.append(TongLianExportPlugin())
|
||||
@@ -1,120 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0045_xq0046 金色印象通联数据导出 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log() 输出日志(转发到 ctx.log,无 ctx 时回落到 print)。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 通联平台 ====================
|
||||
LOGIN_URL = 'https://cus.allinpay.com/login'
|
||||
MAIN_URL = 'https://cus.allinpay.com/main.dsr' # 已登录首页(预热/Referer 来源)
|
||||
SEARCH_URL = 'https://cus.allinpay.com/tranx25/search'
|
||||
STATUS_URL = 'https://cus.allinpay.com/export/statusdownload'
|
||||
DOWNLOAD_INFO_URL = 'https://cus.allinpay.com/export/downloadexport/'
|
||||
BILL_URL = 'https://cus.allinpay.com/checkacct25/download'
|
||||
TRXCODE_URL = 'https://cus.allinpay.com/unauth/queryInterCode'
|
||||
TRXSTATE_URL = 'https://cus.allinpay.com/unauth/queryRecordState'
|
||||
|
||||
# 服务端有 Referer 外链校验:直接访问会被重定向回 /main.dsr
|
||||
SEARCH_HEADERS = {'Referer': MAIN_URL}
|
||||
|
||||
# ==================== 导出参数 ====================
|
||||
EXPORT_CURRENT = 'onebtnexpt' # 导出当前页
|
||||
EXPORT_ALL = 'all' # 导出全部(默认用这个)
|
||||
|
||||
# ==================== 交易查询结果按商户分组拆分 ====================
|
||||
# 交易查询 xlsx 下载后自动拆成 3 个工作簿:命中组1 → 综合门店,命中组2 → 品牌管理公司,
|
||||
# 其余全部 → 其他账号;匹配规则=商户名称精确匹配(仅统一全角括号与首尾空白)。
|
||||
# 每个拆分工作簿保留原文件两个 sheet(sheet1 交易明细 + 汇总),各自按本表商户名称列过滤。
|
||||
SPLIT_GROUPS = [
|
||||
("综合门店", [
|
||||
"南岸区金色印象足浴馆227601",
|
||||
"南岸区子石印象足浴馆(个体工商户)329909",
|
||||
"九龙坡区金印养生足浴馆600402",
|
||||
"金色印象",
|
||||
"金色印象2",
|
||||
]),
|
||||
("品牌管理公司", [
|
||||
"重庆金色印象品牌管理有限公司518344",
|
||||
]),
|
||||
]
|
||||
SPLIT_OTHER_NAME = "其他账号" # 未命中任何分组的商户归入此组
|
||||
|
||||
# 异步导出状态轮询:每 6 秒一次,最多 12 次(服务端超时上限约 10 次/60 秒)
|
||||
STATUS_POLL_INTERVAL = 6
|
||||
STATUS_POLL_MAX = 12
|
||||
|
||||
# 登录/验证码 —— 风控敏感:每次提交都计入服务端登录尝试次数,从严控制重试,
|
||||
# 避免连续多次提交触发平台「登录失败次数已达上限」锁定(曾实测踩雷,账号被锁 2 小时)
|
||||
RETRY_MAX = 1 # 浏览器兜底登录轮数(失败即停,不反复登录)
|
||||
CAPTCHA_RETRY = 3 # 浏览器每轮验证码重试次数
|
||||
API_CAPTCHA_RETRY = 3 # 接口登录验证码重试次数
|
||||
LOGIN_FAIL_BACKOFF = 8 # 登录提交失败后的退避秒数(让风控计数沉降)
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
|
||||
# ==================== 默认保存目录 ====================
|
||||
_DESKTOP = os.path.join(os.path.expanduser('~'), 'Desktop')
|
||||
|
||||
|
||||
def get_desktop():
|
||||
return _DESKTOP
|
||||
|
||||
|
||||
# ==================== 浏览器用户目录 ====================
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留(免验证码),且不占用用户日常 Chrome 配置。
|
||||
|
||||
放 %LOCALAPPDATA% 下而非系统临时目录,避免被磁盘清理工具清掉导致登录态丢失。
|
||||
"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
return os.path.join(base, '37duAutomation', 'browser_sessions', 'xq0045_xq0046')
|
||||
|
||||
|
||||
# ==================== 登录会话复用 ====================
|
||||
def get_session_file():
|
||||
"""已登录会话 cookies 落盘路径:跨 run 复用通联登录,避免每次执行都重新登录。"""
|
||||
base = os.environ.get('LOCALAPPDATA') or os.path.expanduser('~')
|
||||
d = os.path.join(base, '37duAutomation', 'sessions')
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return os.path.join(d, 'allinpay_xq0045_xq0046.json')
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:统一转发到 config.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
log(msg % args if args else msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
log(msg % args if args else msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
log(msg % args if args else msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
log(msg % args if args else msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
@@ -1 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -1,259 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联平台交易数据导出(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
服务端行为已探明(探针 workflows/share/debug_tranx25 实测验证):
|
||||
- 请求必须带 Referer,否则被重定向回 /main.dsr;
|
||||
- 商户列表内嵌在搜索页 JS:var childcuslist = '[{"key":"商户号","value":"商户名"},...]';
|
||||
- 查询:POST /tranx25/search,data={issubmit,cusid,startDate,endDate,export:false,pageIndex,
|
||||
canemptycusid},响应为整页 HTML(结果表格 #dataTable);
|
||||
- 导出(异步三步):
|
||||
1) POST /tranx25/search 带 export=all → JSON {"code":"0","message":"<fid>"}(code=1 失败);
|
||||
2) POST /export/statusdownload {id:fid} 每 6 秒轮询至 code=0(就绪);
|
||||
3) POST /export/downloadexport/ {id:fid} → {"code":"0","message":"<下载URL>"} → GET 落文件。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# ==================== HTTP 封装(统一带 Referer) ====================
|
||||
def _get(session, url, **kw):
|
||||
return session.get(url, headers=config.SEARCH_HEADERS, timeout=20, **kw)
|
||||
|
||||
|
||||
def _post(session, url, data=None, **kw):
|
||||
return session.post(url, data=data, headers=config.SEARCH_HEADERS, timeout=30, **kw)
|
||||
|
||||
|
||||
def _parse_code_message(text):
|
||||
"""解析服务端返回的 JS 风格对象(单引号,如 {code:'0',message:'fid'})。
|
||||
|
||||
前端用 eval('('+data+')') 解析,说明响应不是标准 JSON;
|
||||
先试标准 JSON,失败再正则提取 code/message。返回 (code, message)。
|
||||
"""
|
||||
text = (text or '').strip()
|
||||
try:
|
||||
j = json.loads(text)
|
||||
return str(j.get('code')), str(j.get('message') or '')
|
||||
except Exception:
|
||||
pass
|
||||
m_code = re.search(r"code\s*:\s*'?([^',}]+)'?", text)
|
||||
m_msg = re.search(r"message\s*:\s*'([^']*)'", text)
|
||||
code = m_code.group(1).strip() if m_code else ''
|
||||
msg = m_msg.group(1) if m_msg else ''
|
||||
if not (m_code or m_msg):
|
||||
raise RuntimeError(f"响应无法解析(可能会话失效被踢回页面):{text[:200]}")
|
||||
return code, msg
|
||||
|
||||
|
||||
# ==================== 商户列表 ====================
|
||||
def get_cus_list(session):
|
||||
"""GET 搜索页解析 childcuslist → [{'key': 商户号, 'value': 商户名}, ...]。"""
|
||||
resp = _get(session, config.SEARCH_URL)
|
||||
m = re.search(r"var childcuslist\s*=\s*'([^']*)'", resp.text)
|
||||
if not m:
|
||||
raise RuntimeError("搜索页未找到 childcuslist(会话可能失效,请重新登录)")
|
||||
data = json.loads(m.group(1))
|
||||
if not isinstance(data, list):
|
||||
raise RuntimeError("childcuslist 解析异常")
|
||||
return data
|
||||
|
||||
|
||||
# ==================== 异步导出三步 ====================
|
||||
def start_export(session, cusid, start, end):
|
||||
"""发起导出 → 返回 fid。
|
||||
|
||||
服务端实测(探针 exp_probe + 实跑 + 测速验证):
|
||||
- export=all 会忽略日期参数、导出当天全量(错误行为);
|
||||
- export=onebtnexpt(导出当前查询结果集)才按日期区间导出;
|
||||
- cusid 必须非空:传空串时服务端直接 504 Gateway Timeout(实测 60s 超时);
|
||||
但服务端忽略 cusid 的筛选语义——传任意真实商户号都返回账号全量结果集
|
||||
(不同商户同日期返回同一 fid、同一文件),故用账号下首个商户号即可。
|
||||
因此必须先查询(export=false)建立结果集,再用 onebtnexpt 导出。
|
||||
"""
|
||||
base = {
|
||||
'issubmit': 'issubmit',
|
||||
'cusid': cusid,
|
||||
'startDate': start,
|
||||
'endDate': end,
|
||||
'pageIndex': '1',
|
||||
'canemptycusid': 'true',
|
||||
}
|
||||
# 1) 查询建立结果集(export=false)
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': 'false'})
|
||||
# 2) 导出当前结果集(onebtnexpt)
|
||||
code, msg = _parse_code_message(
|
||||
_post(session, config.SEARCH_URL, {**base, 'export': config.EXPORT_CURRENT}).text)
|
||||
if code == '1':
|
||||
raise RuntimeError(f"导出失败:{msg}")
|
||||
fid = msg
|
||||
if not fid:
|
||||
raise RuntimeError("导出响应缺少 fid")
|
||||
return fid
|
||||
|
||||
|
||||
def wait_export_done(session, fid):
|
||||
"""轮询导出状态,直到就绪(code=0)或超时。
|
||||
|
||||
状态契约(探针实测):code='0'=文件就绪;code='1'=生成中。
|
||||
其它码(如 '2' 失败)只告警不判就绪,避免误把失败态当成功去取下载地址;
|
||||
超时错误里带最后状态,便于定位。
|
||||
"""
|
||||
last = ""
|
||||
for i in range(1, config.STATUS_POLL_MAX + 1):
|
||||
code, msg = _parse_code_message(_post(session, config.STATUS_URL, {'id': fid}).text)
|
||||
last = f"code={code} {msg}".strip()
|
||||
if code == '0':
|
||||
config.log(f"[导出] fid={fid} 文件就绪(轮询 {i} 次)")
|
||||
return True
|
||||
if code != '1':
|
||||
config.log(f"[导出] fid={fid} 状态异常({last}),继续等待", "WARN")
|
||||
else:
|
||||
# 每次轮询都打进度,避免长时间静默被误认为卡死
|
||||
config.log(f"[导出] fid={fid} 文件生成中(第 {i} 次轮询,已等待 {i * config.STATUS_POLL_INTERVAL} 秒)…")
|
||||
time.sleep(config.STATUS_POLL_INTERVAL)
|
||||
raise RuntimeError(f"导出超时(服务端未在时限内生成文件,最后状态:{last})")
|
||||
|
||||
|
||||
def get_download_url(session, fid):
|
||||
"""获取下载地址。"""
|
||||
code, msg = _parse_code_message(_post(session, config.DOWNLOAD_INFO_URL, {'id': fid}).text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"获取下载地址失败:{msg}")
|
||||
return msg
|
||||
|
||||
|
||||
# ==================== 下载校验 ====================
|
||||
def _check_download_content_type(resp):
|
||||
"""下载响应 Content-Type 校验:HTML/文本说明可能被踢回登录页,直接报错。"""
|
||||
ct = (resp.headers.get('Content-Type') or '').lower()
|
||||
if 'html' in ct or ct.startswith('text/'):
|
||||
raise RuntimeError(
|
||||
f"下载返回非文件内容(Content-Type={ct or 'unknown'}),会话可能已失效,请重新登录")
|
||||
|
||||
|
||||
def _is_zip_file(path):
|
||||
"""文件头魔数校验:zip/xlsx 均以 PK 开头。"""
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
return f.read(2) == b'PK'
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _safe_extract(zip_path, extract_dir):
|
||||
"""解压 zip,并拦截路径穿越条目(.. / 绝对路径)。"""
|
||||
with zipfile.ZipFile(zip_path) as zf:
|
||||
for info in zf.infolist():
|
||||
parts = Path(info.filename).parts
|
||||
if info.filename.startswith('/') or '..' in parts or ':' in parts:
|
||||
raise RuntimeError(f"压缩包含非法路径条目,已中止解压:{info.filename}")
|
||||
zf.extractall(extract_dir)
|
||||
|
||||
|
||||
def download_file(session, url, folder, stem):
|
||||
"""下载导出文件到 folder/,文件名 stem + 扩展名(优先 Content-Disposition,默认 .xlsx)。
|
||||
返回最终文件路径。带 Content-Type 与文件魔数校验,防会话失效时把 HTML 落成伪文件。"""
|
||||
resp = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
resp.raise_for_status()
|
||||
_check_download_content_type(resp)
|
||||
ext = '.xlsx'
|
||||
cd = resp.headers.get('Content-Disposition', '')
|
||||
m = re.search(r'filename\*?=(?:UTF-8\'\')?"?([^\";]+)"?', cd, re.I)
|
||||
if m:
|
||||
nm = m.group(1).strip().strip('"')
|
||||
if '.' in nm:
|
||||
ext = '.' + nm.rsplit('.', 1)[1].lower()
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
path = os.path.join(folder, f"{stem}{ext}")
|
||||
total = int(resp.headers.get('Content-Length') or 0)
|
||||
received, last_log = 0, time.time()
|
||||
with open(path, 'wb') as f:
|
||||
for chunk in resp.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
received += len(chunk)
|
||||
now = time.time()
|
||||
if now - last_log >= 8: # 每 8 秒报一次下载进度,避免长下载静默
|
||||
last_log = now
|
||||
mb = received / 1048576
|
||||
if total:
|
||||
pct = received * 100 // max(1, total)
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB / {total / 1048576:.1f}MB({pct}%)…")
|
||||
else:
|
||||
config.log(f"[导出] 下载中 {mb:.1f}MB…")
|
||||
if not _is_zip_file(path): # xlsx 本质是 zip,文件头须为 PK
|
||||
os.remove(path)
|
||||
raise RuntimeError(f"下载文件不是有效 xlsx(文件头异常),已删除:{path}")
|
||||
config.log(f"[导出] 已保存:{path}({received / 1048576:.1f} MB)")
|
||||
return path
|
||||
|
||||
|
||||
# ==================== 日期范围 ====================
|
||||
def build_date_range(mode, date_str):
|
||||
"""按模式把日期字符串转成查询区间 (start, end)。
|
||||
mode='月':date_str=YYYY-MM → 当月 1 日 10:00:00 ~ 下月 1 日 10:00:00(对账 10 点切日口径);
|
||||
mode='日':date_str=YYYY-MM-DD(数据起始日,默认昨天)→ 当天 00:00:00 ~ 次日 23:59:59
|
||||
(即默认 = 昨天0点 ~ 今天24点,今天数据少基本无影响)。"""
|
||||
if mode == '月':
|
||||
ym = datetime.strptime(date_str, '%Y-%m')
|
||||
next_month = (ym.replace(day=1) + timedelta(days=32)).replace(day=1)
|
||||
return (ym.strftime('%Y-%m-01 10:00:00'),
|
||||
next_month.strftime('%Y-%m-01 10:00:00'))
|
||||
d = datetime.strptime(date_str, '%Y-%m-%d')
|
||||
nxt = d + timedelta(days=1)
|
||||
return d.strftime('%Y-%m-%d 00:00:00'), nxt.strftime('%Y-%m-%d 23:59:59')
|
||||
|
||||
|
||||
def default_dates(mode):
|
||||
"""未填日期时的默认值:日=昨天;月=上月。"""
|
||||
today = datetime.now()
|
||||
if mode == '月':
|
||||
first_this = today.replace(day=1)
|
||||
last_month = first_this - timedelta(days=1)
|
||||
return last_month.strftime('%Y-%m')
|
||||
yesterday = today - timedelta(days=1)
|
||||
return yesterday.strftime('%Y-%m-%d')
|
||||
|
||||
|
||||
# ==================== 账单导出(主账号,zip 下载 + 解压) ====================
|
||||
def bill_download(session, date_str, bill_type, folder):
|
||||
"""通联账单下载(只导主账号/当前商户)。
|
||||
|
||||
POST /checkacct25/download:日账单 ?reportdate=YYYYMMDD;月账单 ?type=month&reportdate=YYYYMM。
|
||||
服务端返回 {"code":"0","message":"<zip 下载 URL>"},GET 下载 zip 并解压。
|
||||
date_str = YYYY-MM-DD(日)或 YYYY-MM(月);bill_type = 'day' | 'month'。
|
||||
返回 (zip_path, extract_dir)。
|
||||
"""
|
||||
reportdate = date_str.replace('-', '')
|
||||
params = {'reportdate': reportdate}
|
||||
if bill_type == 'month':
|
||||
params['type'] = 'month'
|
||||
resp = _post(session, config.BILL_URL, params=params)
|
||||
code, msg = _parse_code_message(resp.text)
|
||||
if code != '0':
|
||||
raise RuntimeError(f"账单下载失败:{msg}")
|
||||
url = msg
|
||||
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
zr = session.get(url, headers=config.SEARCH_HEADERS, timeout=180, stream=True)
|
||||
zr.raise_for_status()
|
||||
_check_download_content_type(zr)
|
||||
prefix = '日账单' if bill_type == 'day' else '月账单'
|
||||
zip_path = os.path.join(folder, f"{prefix}_{date_str}.zip")
|
||||
with open(zip_path, 'wb') as f:
|
||||
for chunk in zr.iter_content(chunk_size=8192):
|
||||
f.write(chunk)
|
||||
if not _is_zip_file(zip_path):
|
||||
os.remove(zip_path)
|
||||
raise RuntimeError(f"账单下载不是有效 zip(文件头异常),已删除:{zip_path}")
|
||||
|
||||
extract_dir = os.path.join(folder, f"{prefix}_{date_str}")
|
||||
_safe_extract(zip_path, extract_dir)
|
||||
config.log(f"[账单] 已下载并解压:{extract_dir}")
|
||||
return zip_path, extract_dir
|
||||
@@ -1,564 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""通联支付商户服务平台登录模块(xq0045_xq0046 插件内自包含)。
|
||||
|
||||
自 workflows/share/allinpay_login.py 迁移,插件化改造点:
|
||||
- 账号密码由插件界面配置经 fields 注入(不再读 .env);
|
||||
- print → config.log;返回 requests.Session(登录后会话直接可用,无需浏览器常驻)。
|
||||
|
||||
登录方式(接口优先,浏览器兜底):
|
||||
1) 接口登录(首选,已实测一次成功):GET /login(拿 SESSION + 页面内嵌 publicKey +
|
||||
隐藏表单字段 token/logintype/isscanlogin)
|
||||
→ GET /getvalidCode?type=cuserrorCode 验证码图 → ddddocr 双模型交叉识别(4位)
|
||||
→ JSEncrypt 兼容 RSA 加密密码(PKCS#1 v1.5 + base64)→ POST /login(userid/
|
||||
encpassword/cuserrorCode + 表单隐藏字段,带 Referer)→ 302 离开 /login 即成功;
|
||||
2) 浏览器兜底:DrissionPage 现场登录(验证码元素截图 + ddddocr),成功后从浏览器
|
||||
cookies 构建 requests.Session。
|
||||
|
||||
登录页(账号登录 tab,DOM 参考 aa.md):
|
||||
账号 #userid / 密码 #password(初始 readonly,onfocus 移除;提交时页面 JS 加密进 #encpassword)
|
||||
验证码 #captcha + 图 <img src="/getvalidCode?type=cuserrorCode">(URL 型,元素截图 + ddddocr)
|
||||
登录按钮 button[onclick*="valandsubmit"](触发 valandsubmit JS 加密密码后提交表单)
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
HUMAN_DELAY = (0.4, 1.2)
|
||||
_VALIDCODE_URL = config.LOGIN_URL.replace('/login', '/getvalidCode?type=cuserrorCode')
|
||||
_PUBKEY_RE = re.compile(r"var publicKey='([^']+)'")
|
||||
_LOGIN_FORM_RE = re.compile(r'<form[^>]*id=["\']?accountForm|action=["\']?/login')
|
||||
|
||||
_ocr = None
|
||||
_ocr_beta = None
|
||||
|
||||
|
||||
def _get_ocr():
|
||||
"""ddddocr 单例(懒加载),接口/浏览器登录共用。"""
|
||||
global _ocr
|
||||
if _ocr is None:
|
||||
import ddddocr
|
||||
_ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return _ocr
|
||||
|
||||
|
||||
def _get_ocr_beta():
|
||||
"""ddddocr beta 模型单例:与默认模型交叉校验,提升易混字符识别置信度。"""
|
||||
global _ocr_beta
|
||||
if _ocr_beta is None:
|
||||
import ddddocr
|
||||
_ocr_beta = ddddocr.DdddOcr(show_ad=False, beta=True)
|
||||
return _ocr_beta
|
||||
|
||||
|
||||
# 命中即终止登录(重试验证码无济于事)
|
||||
_ERR_TERMINAL = ('锁定', '次数已达上限', '密码错误', '账号或密码', '用户名不存在',
|
||||
'用户不存在', '不存在该账号', '密码已过期', '登录失败次数')
|
||||
# 风控锁定提示(出现即停止一切登录尝试,浏览器兜底也跳过,避免给锁定“续期”)
|
||||
_LOCK_HINT_RE = re.compile(r'锁定|次数已达上限|次数已达|2小时')
|
||||
|
||||
|
||||
class LoginLockedError(Exception):
|
||||
"""通联账号被风控锁定(服务端提示「次数已达上限」等)。命中后不再做任何登录尝试。"""
|
||||
|
||||
|
||||
def _extract_errormsg(text):
|
||||
"""读取服务端回显的登录错误文案(登录页内嵌 var errormsg='...')。空串=无明确提示。
|
||||
|
||||
实测:验证码错误时 errormsg 为空(页面静默重渲染);账号/密码类错误会回显
|
||||
(如“用户名不存在/密码错误”)。
|
||||
"""
|
||||
m = re.search(r"var errormsg='([^']*)'", text or '')
|
||||
return m.group(1).strip() if m and m.group(1) else ''
|
||||
|
||||
|
||||
def _parse_login_form(html):
|
||||
"""解析登录表单隐藏字段,随 POST 一并提交(与真实浏览器一致,防服务端收紧校验):
|
||||
token(CSRF 随机值,随页面下发)、logintype、isscanlogin。缺失时回退默认值。
|
||||
"""
|
||||
def _v(name, default=''):
|
||||
m = re.search(r'name="%s"\s+value="([^"]*)"' % name, html or '')
|
||||
return m.group(1) if m else default
|
||||
return {'token': _v('token'), 'logintype': _v('logintype', 'userid_login'),
|
||||
'isscanlogin': _v('isscanlogin', '0')}
|
||||
|
||||
|
||||
def _read_captcha_confident(session, max_refresh=3):
|
||||
"""获取验证码并交叉识别:默认模型与 beta 模型结果一致才采用(对 0/O、1/l/I 等
|
||||
易混字符更稳),不一致则刷新验证码重试——仅刷新不提交,不消耗服务端登录尝试次数。
|
||||
|
||||
返回 (code, agreed);多次未达成一致时回退默认模型结果(保持原行为),
|
||||
连续读不出 4 位验证码时返回 (None, False)。
|
||||
"""
|
||||
ocr, ocr_beta = _get_ocr(), _get_ocr_beta()
|
||||
last_code = ''
|
||||
for _ in range(max(1, max_refresh)):
|
||||
try:
|
||||
img = session.get(_VALIDCODE_URL, timeout=20).content
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 获取验证码图异常:{e}")
|
||||
return None, False
|
||||
code = ocr.classification(img).strip()
|
||||
if len(code) != 4:
|
||||
continue
|
||||
last_code = code
|
||||
if ocr_beta.classification(img).strip() == code:
|
||||
return code, True
|
||||
if not last_code:
|
||||
return None, False
|
||||
return last_code, False
|
||||
|
||||
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _rsa_encrypt(pubkey, pwd):
|
||||
"""JSEncrypt 兼容:RSA PKCS#1 v1.5 加密 + base64。
|
||||
|
||||
页面 publicKey 是 SPKI/X.509 SubjectPublicKeyInfo(BEGIN PUBLIC KEY)裸 DER,
|
||||
用 cryptography 解析后按 PKCS#1 v1.5 填充加密(1024 位公钥,明文 ≤117 字节)。
|
||||
"""
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
from cryptography.hazmat.primitives.asymmetric import padding
|
||||
from cryptography.hazmat.primitives.serialization import load_der_public_key
|
||||
pub = load_der_public_key(base64.b64decode(pubkey), default_backend())
|
||||
ct = pub.encrypt(pwd.encode(), padding.PKCS1v15())
|
||||
return base64.b64encode(ct).decode()
|
||||
|
||||
|
||||
def _api_login(username, password):
|
||||
"""接口登录(纯 requests,不弹浏览器)。成功返回 requests.Session,失败返回 None。
|
||||
|
||||
服务端行为(探针实测复核):
|
||||
- /login 页面内嵌固定 RSA 公钥(publicKey,1024 位 PKCS#1);
|
||||
- 验证码 4 位,GET /getvalidCode?type=cuserrorCode 返回图片(session 绑定);
|
||||
- 表单含隐藏字段 token(CSRF)/logintype/isscanlogin,POST /login 需带 Referer
|
||||
(外链校验);验证码错误时服务端静默重渲染登录页(errormsg 为空),账号/密码
|
||||
类错误在 errormsg 回显;成功 302 离开 /login。
|
||||
"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
if len(password.encode()) > 117:
|
||||
# 页面公钥 1024 位,PKCS#1 v1.5 明文上限 117 字节;超长无法加密,
|
||||
# 明确提示后走浏览器兜底登录
|
||||
config.log("[通联登录] 密码过长(>117 字节),接口登录无法加密,将回退浏览器登录")
|
||||
return None
|
||||
html = session.get(config.LOGIN_URL, timeout=20).text
|
||||
m = _PUBKEY_RE.search(html)
|
||||
if not m:
|
||||
config.log("[通联登录] 接口登录失败:未找到 publicKey")
|
||||
return None
|
||||
pubkey = m.group(1)
|
||||
enc = _rsa_encrypt(pubkey, password)
|
||||
form_extra = _parse_login_form(html)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 接口登录准备异常:{e}")
|
||||
return None
|
||||
|
||||
for attempt in range(config.API_CAPTCHA_RETRY):
|
||||
code, agreed = _read_captcha_confident(session)
|
||||
if not code:
|
||||
config.log("[通联登录] 连续未能识别出 4 位验证码,停止接口登录")
|
||||
return None
|
||||
agree_note = "" if agreed else "(双模型未一致,按默认模型提交)"
|
||||
config.log(f"[通联登录] 接口登录 第 {attempt + 1}/{config.API_CAPTCHA_RETRY} 次验证码识别:{code!r}{agree_note}")
|
||||
data = {'userid': username, 'encpassword': enc, 'cuserrorCode': code}
|
||||
data.update({k: v for k, v in form_extra.items() if v})
|
||||
try:
|
||||
resp = session.post(config.LOGIN_URL, data=data,
|
||||
headers={'Referer': config.LOGIN_URL},
|
||||
timeout=20, allow_redirects=True)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提交登录异常:{e}")
|
||||
return None
|
||||
if '/login' not in resp.url:
|
||||
config.log(f"[通联登录] 接口登录成功:{resp.url}")
|
||||
return session
|
||||
# 仍在登录页:验证码错/账号密码错/风控。每次提交都计入服务端尝试次数,
|
||||
# 失败后退避并停止(不连续重试,避免触发登录次数风控锁定)
|
||||
errormsg = _extract_errormsg(resp.text)
|
||||
if errormsg:
|
||||
config.log(f"[通联登录] 服务端提示:{errormsg}")
|
||||
if '锁定' in errormsg or '次数' in errormsg:
|
||||
config.log("[通联登录] 检测到风控锁定提示,立即停止登录尝试")
|
||||
raise LoginLockedError(errormsg)
|
||||
if any(k in errormsg for k in _ERR_TERMINAL):
|
||||
return None
|
||||
time.sleep(config.LOGIN_FAIL_BACKOFF)
|
||||
config.log("[通联登录] 接口登录验证码多次未通过,停止重试")
|
||||
return None
|
||||
|
||||
|
||||
def _on_target(page):
|
||||
"""登录成功判定:URL 离开 /login。"""
|
||||
try:
|
||||
return '/login' not in (page.url or '')
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _find_input(page, selectors):
|
||||
for sel in selectors:
|
||||
ele = page.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(page):
|
||||
"""定位验证码输入框 + 图片(从 #captcha 容器向上找,避免命中验证码登录 tab 的图)。"""
|
||||
code_input = page.ele('#captcha', timeout=config.TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(1) # div.input-group#captcha_div
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = page.ele('css:.tab-pane.active img[src*="getvalidCode"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""URL 型验证码(/getvalidCode)直接元素截图;兼容 base64 内嵌 src。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。复用全局单例,避免重复加载模型。"""
|
||||
return _get_ocr().classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _refresh_captcha(page, img):
|
||||
"""点击验证码图片刷新(onclick=cusjsUtil.changeCode)。URL 型验证码无法可靠比对,点击后等渲染。"""
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.8)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _ensure_account_tab(page):
|
||||
"""确保「账号登录」tab 激活(默认激活;若页面记住验证码登录则切回)。"""
|
||||
uid = page.ele('#userid', timeout=2)
|
||||
if uid:
|
||||
try:
|
||||
if uid.states.is_displayed:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
tab_btn = page.ele('css:a[href="#account"], css:a[data-target="#account"]', timeout=3) \
|
||||
or page.ele('tag:a@@text():账号登录', timeout=3)
|
||||
if tab_btn:
|
||||
try:
|
||||
tab_btn.click()
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def _wait_login_result(page):
|
||||
"""提交后轮询判定登录结果。
|
||||
|
||||
返回:True=登录成功;str=失败提示文案;''=超时未判定。
|
||||
调用方据此可区分「验证码/账号错」与「风控锁定」。
|
||||
"""
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 登录成功:{page.url}")
|
||||
return True
|
||||
for sel in ('css:.invalid-feedback', 'css:.alert-danger', 'css:.toast'):
|
||||
try:
|
||||
eles = page.eles(sel, timeout=0.3)
|
||||
except Exception:
|
||||
continue
|
||||
for ele in eles:
|
||||
try:
|
||||
text = ele.text.strip()
|
||||
except Exception:
|
||||
text = ''
|
||||
if text:
|
||||
config.log(f"[通联登录] 失败提示:{text}")
|
||||
return text
|
||||
return ''
|
||||
|
||||
|
||||
def _input_value(ele):
|
||||
"""读取输入框当前值(页面刷新后表单清空,用于判断是否需要重填)。"""
|
||||
try:
|
||||
return ele.value or ''
|
||||
except Exception:
|
||||
try:
|
||||
return ele.attr('value') or ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _fill_account(page, username, password):
|
||||
"""确保账号密码已填(每轮提交前调用)。
|
||||
|
||||
通联登录失败后页面会整页刷新、表单被清空;这里做幂等填充——
|
||||
账号/密码已存在则跳过,被清空则重新输入,避免后续重试提交空表单。
|
||||
"""
|
||||
user_input = page.ele('#userid', timeout=config.TIMEOUT)
|
||||
if not user_input:
|
||||
config.log("[通联登录] 找不到账号输入框")
|
||||
return False
|
||||
if _input_value(user_input) != username:
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(page, ['#password', 'css:input[type="password"]:not([name="encpassword"])'])
|
||||
if not pwd_input:
|
||||
config.log("[通联登录] 找不到密码输入框")
|
||||
return False
|
||||
if not _input_value(pwd_input):
|
||||
pwd_input.click() # 触发 onfocus 移除 readonly
|
||||
_human_pause(0.2, 0.5)
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
return True
|
||||
|
||||
|
||||
def _try_login_once(page, username, password):
|
||||
"""完成一次填表 + 验证码 + 提交,返回 bool。
|
||||
每轮提交前都会确保账号密码已填(页面刷新后自动重填)。"""
|
||||
_ensure_account_tab(page)
|
||||
|
||||
for attempt in range(config.CAPTCHA_RETRY):
|
||||
if not _fill_account(page, username, password):
|
||||
return False
|
||||
config.log(f"[通联登录] 第 {attempt + 1}/{config.CAPTCHA_RETRY} 次验证码识别")
|
||||
img, code_input = _find_captcha(page)
|
||||
if not img or not code_input:
|
||||
config.log("[通联登录] 找不到验证码图片或输入框")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] ddddocr 识别异常:{e}")
|
||||
return False
|
||||
config.log(f"[通联登录] 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(page, img)
|
||||
continue
|
||||
code_input.click() # 触发 onfocus 移除 readonly
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = page.ele('css:.tab-pane.active button[onclick*="valandsubmit"]', timeout=config.TIMEOUT) \
|
||||
or page.ele('tag:button@@text():登录', timeout=config.TIMEOUT)
|
||||
if not btn:
|
||||
config.log("[通联登录] 找不到登录提交按钮")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
result = _wait_login_result(page)
|
||||
if result is True:
|
||||
return True
|
||||
if result and _LOCK_HINT_RE.search(result):
|
||||
config.log("[通联登录] 检测到风控锁定提示,停止浏览器登录")
|
||||
return False
|
||||
_refresh_captcha(page, img)
|
||||
return False
|
||||
|
||||
|
||||
def _build_session(page):
|
||||
"""从浏览器 cookies 构建 requests.Session(仅保留 allinpay.com 域)。"""
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
try:
|
||||
for c in page.cookies():
|
||||
domain = (c.get('domain') or '')
|
||||
if 'allinpay.com' not in domain:
|
||||
continue
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=domain.lstrip('.'), path=c.get('path', '/'))
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 提取 cookies 异常:{e}")
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 会话落盘复用(跨 run,子进程隔离下也生效) ====================
|
||||
def _dump_cookies(session):
|
||||
"""把 requests.Session 的 cookies 序列化为可持久化列表。"""
|
||||
out = []
|
||||
for c in session.cookies:
|
||||
out.append({'name': c.name, 'value': c.value, 'domain': c.domain or '',
|
||||
'path': c.path or '/'})
|
||||
return out
|
||||
|
||||
|
||||
def save_session(username, session):
|
||||
"""登录成功后把会话 cookies 落盘,供下次运行直接复用。失败不影响本次执行。"""
|
||||
try:
|
||||
data = {'username': username, 'cookies': _dump_cookies(session)}
|
||||
with open(config.get_session_file(), 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 保存会话失败(不影响本次执行):{e}")
|
||||
|
||||
|
||||
def _session_valid(session):
|
||||
"""会话探活:GET 首页,未落回 /login 且页面内容不含登录表单即视为有效。
|
||||
|
||||
平台为单点登录(多地互斥):一旦其它设备/浏览器用同一账号重新登录,
|
||||
本会话立即失效。此时 main.dsr 仍返回 200,但页面内容是登录表单
|
||||
(<form id="accountForm" action="/login">)而非业务首页——仅看 URL 会误判
|
||||
为有效,导致后续 API 全部失败,必须校验页面内容。
|
||||
"""
|
||||
try:
|
||||
resp = session.get(config.MAIN_URL, headers=config.SEARCH_HEADERS,
|
||||
timeout=15, allow_redirects=True)
|
||||
if resp.status_code != 200 or '/login' in resp.url:
|
||||
return False
|
||||
return not _LOGIN_FORM_RE.search(resp.text)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def load_session(username):
|
||||
"""读取并重建上次登录会话;有效则返回 requests.Session,否则返回 None。"""
|
||||
path = config.get_session_file()
|
||||
try:
|
||||
with open(path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if data.get('username') != username:
|
||||
config.log("[通联登录] 本地会话账号与当前账号不一致,重新登录")
|
||||
return None
|
||||
session = requests.Session()
|
||||
session.headers.update({"User-Agent": _UA})
|
||||
for c in data.get('cookies') or []:
|
||||
session.cookies.set(c['name'], c['value'],
|
||||
domain=c['domain'] or '', path=c['path'] or '/')
|
||||
if _session_valid(session):
|
||||
return session
|
||||
config.log("[通联登录] 本地会话已失效,重新登录")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 读取本地会话异常:{e}")
|
||||
return None
|
||||
|
||||
|
||||
def tl_login(username, password):
|
||||
"""通联平台登录(本地会话复用 → 接口登录 → 浏览器兜底)。
|
||||
|
||||
成功返回 requests.Session,失败返回 None。登录成功后会话 cookies 落盘,
|
||||
下次运行直接复用免登录(探活失败才重新登录)。
|
||||
"""
|
||||
username = (username or '').strip()
|
||||
raw_password = password or ''
|
||||
# 清洗密码首尾空白(含全角空格等):配置被误存前导空格时,直接拿原值登录必被
|
||||
# 服务端判“账户名或登录密码不正确”,累计触发风控锁定。密码内部空格保留。
|
||||
password = raw_password.strip()
|
||||
if password != raw_password:
|
||||
config.log("[通联登录] 已清洗密码首尾空白字符(如真实密码首尾确有空格,请到插件界面更正后重试)")
|
||||
if not (username and password):
|
||||
config.log("[通联登录] 账号/密码缺失(请在插件界面填写并保存配置)")
|
||||
return None
|
||||
|
||||
# 1) 复用本地已保存会话(免重新登录)
|
||||
session = load_session(username)
|
||||
if session is not None:
|
||||
config.log("[通联登录] 复用本地已登录会话,免重新登录(单点登录:请勿同时在其")
|
||||
config.log("[通联登录] 它设备/浏览器登录同一账号,否则本会话会被踢下线)")
|
||||
return session
|
||||
|
||||
# 2) 接口登录(首选,不弹浏览器)
|
||||
config.log("[通联登录] 本地会话失效,开始重新登录(单点登录:本次登录会顶掉其它")
|
||||
config.log("[通联登录] 设备/浏览器上的同一账号登录)")
|
||||
try:
|
||||
session = _api_login(username, password)
|
||||
except LoginLockedError as e:
|
||||
# 账号已被风控锁定:浏览器兜底同样会被拒,且每次提交都会给锁定“续期”,
|
||||
# 直接停止,等锁定解除后再跑(服务端一般提示 2 小时后恢复)。
|
||||
config.log(f"[通联登录] 账号已被风控锁定({e}),跳过浏览器登录,请稍后再试")
|
||||
return None
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
config.log("[通联登录] 接口登录未成功,回退浏览器登录")
|
||||
# 3) 浏览器兜底
|
||||
session = _browser_login(username, password)
|
||||
if session is not None:
|
||||
save_session(username, session)
|
||||
return session
|
||||
|
||||
|
||||
def _browser_login(username, password):
|
||||
"""浏览器兜底登录(DrissionPage + ddddocr 图形验证码,元素截图)。
|
||||
|
||||
返回:成功 → requests.Session(从浏览器 cookies 构建);失败 → None。
|
||||
固定默认用户目录保留登录态:已登录会话直接复用(免验证码)。
|
||||
调用方使用完毕无需额外操作(本函数已 page.quit())。
|
||||
"""
|
||||
co = ChromiumOptions()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
# 独立固定用户目录(%LOCALAPPDATA% 下,非临时目录):登录态跨次保留免验证码,
|
||||
# 且不占用用户日常 Chrome 配置、不被系统磁盘清理清掉
|
||||
co.set_user_data_path(config.get_browser_profile_dir())
|
||||
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
page = None
|
||||
try:
|
||||
config.log(f"[通联登录] 浏览器登录 第 {attempt}/{config.RETRY_MAX} 次 → {config.LOGIN_URL}")
|
||||
page = ChromiumPage(co)
|
||||
page.get(config.LOGIN_URL)
|
||||
_human_pause(1.0, 2.0)
|
||||
|
||||
if _on_target(page):
|
||||
config.log(f"[通联登录] 检测到已登录会话,直接复用:{page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
|
||||
if _try_login_once(page, username, password):
|
||||
config.log(f"[通联登录] 登录成功 → {page.url}")
|
||||
session = _build_session(page)
|
||||
page.quit()
|
||||
return session
|
||||
except Exception as e:
|
||||
config.log(f"[通联登录] 异常:{e}")
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
config.log("[通联登录] 浏览器登录重试多次均失败")
|
||||
return None
|
||||
@@ -1,116 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""交易查询结果 xlsx 按商户分组拆分(金色印象定制)。
|
||||
|
||||
原文件含两个 sheet:sheet1(第 1 行标题、第 2 行表头、第 3 行起明细)、
|
||||
汇总(第 1 行表头、第 2 行起汇总)。拆分规则:
|
||||
- 每个 sheet 按各自「商户名称」列过滤行,分组定义见 config.SPLIT_GROUPS;
|
||||
- 未命中任何分组的商户全部归入 config.SPLIT_OTHER_NAME(其他账号);
|
||||
- 每组生成一个新工作簿(保留原有两个 sheet 与标题行/表头行),
|
||||
与原文件同目录,命名 <原文件名>_<组名>.xlsx;原全量文件保持不动。
|
||||
仅复制单元格值、数字格式与列宽,不复制行高样式,导出文件为纯数据表足够使用。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
from .. import config
|
||||
|
||||
_KEY_HEADER = '商户名称' # 定位表头行的关键列名
|
||||
|
||||
|
||||
def _norm(v):
|
||||
"""商户名称归一化:去首尾空白 + 全角括号转半角,用于精确匹配。"""
|
||||
if v is None:
|
||||
return ''
|
||||
return str(v).strip().replace('(', '(').replace(')', ')')
|
||||
|
||||
|
||||
def _locate_header(ws):
|
||||
"""在前 3 行内定位含「商户名称」的表头行号与列号;找不到返回 (None, None)。"""
|
||||
max_row = min(3, ws.max_row or 1)
|
||||
for r in range(1, max_row + 1):
|
||||
for c in range(1, (ws.max_column or 1) + 1):
|
||||
if _norm(ws.cell(r, c).value) == _KEY_HEADER:
|
||||
return r, c
|
||||
return None, None
|
||||
|
||||
|
||||
def _copy_row(ws, src_row):
|
||||
"""把源行追加到 ws 末尾(值 + 非默认数字格式)。"""
|
||||
ws.append([c.value for c in src_row])
|
||||
for c_new, c_src in zip(ws[ws.max_row], src_row):
|
||||
fmt = c_src.number_format
|
||||
if fmt and fmt != 'General':
|
||||
c_new.number_format = fmt
|
||||
|
||||
|
||||
def _copy_layout(ws_src, ws):
|
||||
"""复制列宽,保证拆分文件可读性与原文件一致。"""
|
||||
for col, dim in ws_src.column_dimensions.items():
|
||||
if dim.width:
|
||||
ws.column_dimensions[col].width = dim.width
|
||||
|
||||
|
||||
def split_trx_file(path):
|
||||
"""按商户分组拆分交易查询 xlsx,返回新生成的工作簿路径列表。
|
||||
|
||||
任一环节失败由调用方兜底(原始全量文件不受影响)。
|
||||
"""
|
||||
path = Path(path)
|
||||
wb = openpyxl.load_workbook(path)
|
||||
|
||||
# ---- 预处理:每个 sheet 定位表头,并把数据行按组分桶 ----
|
||||
labels = [label for label, _ in config.SPLIT_GROUPS]
|
||||
other = config.SPLIT_OTHER_NAME
|
||||
all_labels = labels + [other]
|
||||
group_sets = [(label, {_norm(n) for n in names}) for label, names in config.SPLIT_GROUPS]
|
||||
|
||||
sheet_meta = {} # sheet名 -> (header_row, cus_col) 或 None(无商户列)
|
||||
bucket_rows = {} # (sheet名, 组名) -> [源数据行, ...]
|
||||
for name in wb.sheetnames:
|
||||
ws = wb[name]
|
||||
header_row, cus_col = _locate_header(ws)
|
||||
if not header_row:
|
||||
config.log(f" sheet[{name}] 未找到「{_KEY_HEADER}」列,拆分文件中该 sheet 原样保留")
|
||||
sheet_meta[name] = None
|
||||
continue
|
||||
sheet_meta[name] = (header_row, cus_col)
|
||||
for label in all_labels:
|
||||
bucket_rows[(name, label)] = []
|
||||
for row in ws.iter_rows(min_row=header_row + 1):
|
||||
key = _norm(row[cus_col - 1].value)
|
||||
hit = other
|
||||
for label, names in group_sets:
|
||||
if key in names:
|
||||
hit = label
|
||||
break
|
||||
bucket_rows[(name, hit)].append(row)
|
||||
|
||||
# ---- 逐组落盘 ----
|
||||
out_paths = []
|
||||
for label in all_labels:
|
||||
out = openpyxl.Workbook()
|
||||
out.remove(out.active)
|
||||
for name in wb.sheetnames:
|
||||
ws_src, ws = wb[name], out.create_sheet(name)
|
||||
meta = sheet_meta.get(name)
|
||||
if not meta:
|
||||
for row in ws_src.iter_rows():
|
||||
_copy_row(ws, row)
|
||||
else:
|
||||
header_row, _ = meta
|
||||
for r in range(1, header_row): # 标题行(如 sheet1 导出时间行)原样保留
|
||||
_copy_row(ws, ws_src[r])
|
||||
_copy_row(ws, ws_src[header_row]) # 表头行
|
||||
for row in bucket_rows[(name, label)]:
|
||||
_copy_row(ws, row)
|
||||
_copy_layout(ws_src, ws)
|
||||
out_path = path.with_name(f"{path.stem}_{label}{path.suffix}")
|
||||
out.save(out_path)
|
||||
detail = '、'.join(
|
||||
f"{name} {len(bucket_rows[(name, label)])} 行"
|
||||
for name in wb.sheetnames if sheet_meta.get(name)
|
||||
)
|
||||
config.log(f" 拆分[{label}]:{detail} → {out_path}")
|
||||
out_paths.append(str(out_path))
|
||||
return out_paths
|
||||
@@ -1,69 +0,0 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0045_xq0046",
|
||||
"name": "金色印象通联数据导出",
|
||||
"version": "1.0.12",
|
||||
"description": "通联支付商户服务平台(cus.allinpay.com)交易数据自动导出:XQ0045 按日、XQ0046 按月,账号全量数据导出(含全部商户),服务端生成文件直存本地,并按商户分组自动拆分为综合门店/品牌管理公司/其他账号 3 个工作簿",
|
||||
"category": "报表",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0045_xq0046"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"title": "执行模式",
|
||||
"default": "日+月",
|
||||
"enum": ["日", "月", "日+月"],
|
||||
"description": "日/月/日+月:决定日期选择器粒度;交易查询与账单导出共用日期选择器,插件内部自动换算各自区间"
|
||||
},
|
||||
"content": {
|
||||
"type": "string",
|
||||
"title": "导出内容",
|
||||
"default": "两个都导",
|
||||
"enum": ["两个都导", "交易查询", "账单"],
|
||||
"description": "交易查询=逐商户导交易明细(xlsx);账单=主账号日/月账单(zip 下载并解压)"
|
||||
},
|
||||
"day_date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"title": "按日导出",
|
||||
"default": "",
|
||||
"description": "留空=昨日(插件按执行日推算,定时任务无需固定日期);交易查询区间 = 所选日 00:00 ~ 次日 24:00;账单 = 所选日账单"
|
||||
},
|
||||
"month_date": {
|
||||
"type": "string",
|
||||
"format": "month",
|
||||
"title": "按月导出",
|
||||
"default": "",
|
||||
"description": "留空=上月(插件按执行日推算,定时任务无需固定月份);交易查询区间 = 当月1日 10:00 ~ 下月1日 10:00(对账10点切日);账单 = 该月账单"
|
||||
},
|
||||
"tl_username": {
|
||||
"type": "string",
|
||||
"title": "通联登录账号",
|
||||
"default": "",
|
||||
"description": "商户服务平台登录账号(保存在本机,下次免填)"
|
||||
},
|
||||
"tl_password": {
|
||||
"type": "string",
|
||||
"title": "通联登录密码",
|
||||
"default": "",
|
||||
"format": "password",
|
||||
"description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=桌面/金色印象通联数据_YYYYMMDD;交易查询每日期一份全量文件(日_日期.xlsx / 月_月份.xlsx),账单按 账单_YYYYMM 目录存放"
|
||||
}
|
||||
},
|
||||
"required": ["tl_username", "tl_password"]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
ddddocr>=1.4
|
||||
cryptography>=39.0
|
||||
openpyxl>=3.1
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>金色印象通联数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0045_xq0046/assets/index-qs3ay3HR.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0045_xq0046/assets/index-C-Ir0bBb.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user