feat(xq0079): 新增金色湖畔扫码数据导出插件(1.1.4)
- 天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录导出:账密登录(图形验证码 OCR + AES 密码加密,token 按账号缓存复用)→ 平台导出接口生成 xlsx → 下载中心取文件直存本地 - 支持两套账号串行导出(第 2 套可留空),日期区间界面可选,产物按商户名区分
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:天阙平台接口访问(登录、导出)。"""
|
||||
@@ -0,0 +1,194 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 人工登录通道:弹可见浏览器 + 预填账号密码,验证码由人工输入并点「登录」。
|
||||
|
||||
为什么需要这条通道:
|
||||
接口登录依赖 ddddocr 识别图形验证码(4 位字母数字),识别率不是 100%,
|
||||
每次提交都计入平台失败次数(服务端对「验证码错」和「账号密码错」都回 1003,
|
||||
连续失败有锁号风险)。人工登录不自动提交表单,只做预填,验证码由人看,
|
||||
一次就能过,且不消耗插件的重试轮次。
|
||||
|
||||
实现要点(登录页 DOM 来自实际页面):
|
||||
账号 input#loginAcc(placeholder「请输入商户编号/门店编号/手机号」)
|
||||
密码 input#loginPwd(ant-input-password 内)
|
||||
验证码 input#imageCode + 右侧 <img src="data:image/jpeg;base64,...">
|
||||
登录按钮 button.ant-btn-primary(文案「登 录」)
|
||||
登录成功后前端会整页跳转,并把用户信息(含 token)写入 sessionStorage.user,
|
||||
这里轮询 sessionStorage 取 token——比抓 cookie 稳,天阙业务接口靠 token 头鉴权。
|
||||
|
||||
风控相关(多账号必须看):
|
||||
- 浏览器用户目录按账号隔离(config.get_profile_dir),不共用 DrissionPage 默认的
|
||||
%TEMP%\\DrissionPage\\userData 公共目录,避免两个账号串 cookie / 登录态;
|
||||
- 同一账号每次都用同一个 profile:cookie 保留、指纹稳定,表现接近真人固定浏览器;
|
||||
- 每个实例用独立调试端口,避免与其它插件或已开浏览器抢 9222;
|
||||
- 账号之间由调用方随机停顿几秒再登(config.ACCOUNT_GAP_SECONDS),不并发、
|
||||
不秒连,减少「同设备短时多账号」这类风控特征;
|
||||
- 登录完成后只关窗口,不清 profile(清了下一次又像一台新设备,反而更可疑)。
|
||||
"""
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
def _free_port():
|
||||
"""取一个空闲本地端口,避免与其它插件/已开浏览器抢同一个调试端口。"""
|
||||
with socket.socket() as s:
|
||||
s.bind(("127.0.0.1", 0))
|
||||
return s.getsockname()[1]
|
||||
|
||||
|
||||
def _new_page(account):
|
||||
"""按账号隔离浏览器用户目录(profile)后开窗。
|
||||
|
||||
DrissionPage 默认把 profile 放 %TEMP%\\DrissionPage\\userData\\<端口>,
|
||||
是所有插件共用的同一个配置目录——不同账号/不同插件会串 cookie 与登录态。
|
||||
这里按账号 md5 建独立目录:同账号每次复用(cookie 保留、指纹稳定,像真人固定浏览器),
|
||||
不同账号之间完全隔离;账号间再随机停顿几秒,避免同一秒连登被风控盯上。
|
||||
"""
|
||||
from DrissionPage import ChromiumOptions, ChromiumPage
|
||||
|
||||
profile = config.get_profile_dir(account)
|
||||
opts = ChromiumOptions()
|
||||
opts.set_user_data_path(profile) # 账号级隔离(也避开 %TEMP% 公共目录)
|
||||
opts.set_local_port(_free_port()) # 独立端口,防与其他实例冲突
|
||||
opts.set_argument("--start-maximized")
|
||||
return ChromiumPage(opts), profile
|
||||
|
||||
|
||||
def _alive(page):
|
||||
try:
|
||||
return bool(page.states.is_alive)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _js(page, script, times=5, gap=0.5):
|
||||
"""页面跳转瞬间 run_js 会抛 ContextLostError,重试几次。"""
|
||||
for _ in range(times):
|
||||
try:
|
||||
return page.run_js(script)
|
||||
except Exception:
|
||||
time.sleep(gap)
|
||||
return None
|
||||
|
||||
|
||||
def _wait_form(page, timeout=40):
|
||||
"""等登录表单渲染完成(umi 首屏是 JS 渲染,input 出现才算就绪)。"""
|
||||
for _ in range(timeout):
|
||||
n = _js(page, "return document.querySelectorAll('input').length", times=2) or 0
|
||||
if n >= 3:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def _fill(page, account, password):
|
||||
"""预填账号密码(人工只需输验证码)。字段缺失不影响人工操作。"""
|
||||
try:
|
||||
acc = page.ele('#loginAcc', timeout=5) or page.ele('css:input[placeholder*="商户编号"]', timeout=3)
|
||||
if acc:
|
||||
acc.clear()
|
||||
acc.input(account)
|
||||
except Exception as exc:
|
||||
_log(f"预填账号失败(可手动输入):{exc}", "WARN")
|
||||
|
||||
if not password:
|
||||
return
|
||||
try:
|
||||
pwd = page.ele('#loginPwd', timeout=5) or page.ele('css:input[type="password"]', timeout=3)
|
||||
if pwd:
|
||||
pwd.clear()
|
||||
pwd.input(password)
|
||||
except Exception as exc:
|
||||
_log(f"预填密码失败(可手动输入):{exc}", "WARN")
|
||||
|
||||
|
||||
def _read_user(page):
|
||||
"""读 sessionStorage.user(登录成功后前端写入,含 token)。"""
|
||||
raw = _js(page, "return sessionStorage.getItem('user')", times=2)
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
user = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
if isinstance(user, dict) and user.get("token"):
|
||||
return user
|
||||
return None
|
||||
|
||||
|
||||
def manual_login(account, password, wait_seconds=None):
|
||||
"""人工登录:返回 {success, token, user, message}。
|
||||
|
||||
不开无头窗口:人工要看验证码。登录成功后关闭浏览器(token 已拿到,不需要常驻)。
|
||||
"""
|
||||
wait_seconds = wait_seconds or config.MANUAL_LOGIN_WAIT
|
||||
page = None
|
||||
try:
|
||||
page, profile = _new_page(account)
|
||||
_log(f"浏览器用户目录(该账号专用):{profile}", "DEBUG")
|
||||
|
||||
page.get(config.BASE_URL + config.LOGIN_PAGE)
|
||||
time.sleep(2)
|
||||
if not _wait_form(page, timeout=15):
|
||||
# 这个 profile 上次登录后 cookie 还在,可能直接进了后台
|
||||
user = _read_user(page)
|
||||
if user:
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
_log(f"该账号浏览器里仍是登录态,直接复用:{merchant}")
|
||||
return {"success": True, "token": token, "user": user,
|
||||
"message": "浏览器已有登录态", "merchant": merchant}
|
||||
_log("登录页未出现表单(疑似残留登录态),清理该账号浏览器缓存后重试", "WARN")
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception as exc:
|
||||
_log(f"清理浏览器缓存失败(可手动清理):{exc}", "WARN")
|
||||
page.get(config.BASE_URL + config.LOGIN_PAGE)
|
||||
time.sleep(2)
|
||||
if not _wait_form(page, timeout=30):
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": "登录页 40 秒未渲染完成(网络异常或平台改版)"}
|
||||
|
||||
_fill(page, account, password)
|
||||
_log(f"已打开登录页并预填账号 {account}(密码仅本地预填,可自行修改)")
|
||||
_log(f"请在浏览器里输入图形验证码并点「登 录」,插件会等待 {wait_seconds} 秒…")
|
||||
_log("提示:本方式不自动提交表单,不会消耗接口登录的重试轮次")
|
||||
|
||||
deadline = time.time() + wait_seconds
|
||||
next_tip = time.time() + config.MANUAL_TIP_SECONDS
|
||||
while time.time() < deadline:
|
||||
if not _alive(page):
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": "浏览器被关闭,人工登录已取消"}
|
||||
|
||||
user = _read_user(page)
|
||||
if user:
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
_log(f"人工登录成功:{merchant}(token {token[:12]}…)")
|
||||
return {"success": True, "token": token, "user": user,
|
||||
"message": "人工登录成功", "merchant": merchant}
|
||||
|
||||
if time.time() >= next_tip:
|
||||
_log(f"仍在等待人工登录,剩余 {int(deadline - time.time())} 秒…")
|
||||
next_tip = time.time() + config.MANUAL_TIP_SECONDS
|
||||
time.sleep(config.MANUAL_POLL_SECONDS)
|
||||
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": f"人工登录等待超时({wait_seconds} 秒),未检测到登录成功"}
|
||||
except Exception as exc:
|
||||
return {"success": False, "token": "", "user": {},
|
||||
"message": f"人工登录异常:{exc}"}
|
||||
finally:
|
||||
# 只关窗口,保留该账号的 profile(cookie / 指纹延续,下次打开像本人浏览器)
|
||||
if page is not None:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,152 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 导出模块:天阙交易记录导出(平台服务端生成 xlsx,本地只负责触发 + 取件)。
|
||||
|
||||
链路(2026-11 实测,与网页完全一致):
|
||||
1) POST tranInfoPc/exportNew 提交导出任务(响应体为空,成功与否靠下载中心判断)
|
||||
2) POST download/downLoadList 轮询下载中心,等本次新增且 exportStatus=1 的记录
|
||||
3) GET <record.downloadUrl> OSS 预签名地址,直接下载,不需要带 token
|
||||
4) POST download/read/<id> 标记已读,避免下载中心越堆越多
|
||||
|
||||
已知坑位:
|
||||
- exportNew 返回 0 字节,不能按 JSON 解析。
|
||||
- download/polling 只是前端进度圈,脚本不用它,省掉一堆无意义请求。
|
||||
- 下载中心是全账号共享的历史列表,必须用「提交前的 id 集合 + 增量」认领自己的任务,
|
||||
否则会下到历史文件;文件名里的时间串也不能当唯一标识。
|
||||
- downloadUrl 带 expires/signature,有时效,拿到要立刻下。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
from . import tianque_login as login_mod
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
def submit_export(session, begin, end):
|
||||
"""提交交易记录导出任务。"""
|
||||
payload = dict(config.EXPORT_TEMPLATE)
|
||||
payload["startTime"] = begin
|
||||
payload["endTime"] = end
|
||||
_log(f"提交导出任务:{begin} ~ {end}", "DEBUG")
|
||||
body = login_mod.api_post(session, config.API_EXPORT, payload)
|
||||
if body.get("_empty"):
|
||||
_log(f"导出任务已提交(HTTP {body.get('_status')},空响应属正常)")
|
||||
else:
|
||||
_log(f"导出任务响应:{str(body)[:200]}", "DEBUG")
|
||||
return payload
|
||||
|
||||
|
||||
def download_list(session):
|
||||
"""下载中心列表(新→旧)。"""
|
||||
body = login_mod.api_post(session, config.API_DOWNLOAD_LIST,
|
||||
{"pageNum": 1, "pageSize": config.LIST_PAGE_SIZE})
|
||||
data = (body or {}).get("data") or {}
|
||||
return data.get("content") or []
|
||||
|
||||
|
||||
def wait_new_record(session, before_ids, timeout=None, interval=None):
|
||||
"""等下载中心出现本次新增且导出完成的记录。"""
|
||||
timeout = timeout or config.POLL_TIMEOUT
|
||||
interval = interval or config.POLL_INTERVAL
|
||||
deadline = time.time() + timeout
|
||||
last_desc = ""
|
||||
while time.time() < deadline:
|
||||
for rec in download_list(session):
|
||||
if rec.get("id") in before_ids:
|
||||
continue
|
||||
if config.TRADE_SOURCE and config.TRADE_SOURCE not in (rec.get("fileSource") or ""):
|
||||
continue
|
||||
status = str(rec.get("exportStatus") or "")
|
||||
desc = rec.get("exportStatusDesc") or status
|
||||
if status == config.EXPORT_STATUS_DONE and rec.get("downloadUrl"):
|
||||
return rec
|
||||
if desc != last_desc:
|
||||
_log(f"任务状态:{rec.get('fileName')} → {desc}")
|
||||
last_desc = desc
|
||||
time.sleep(interval)
|
||||
raise RuntimeError(f"等了 {timeout} 秒仍未等到导出完成,可调大 POLL_TIMEOUT 或去平台下载中心确认")
|
||||
|
||||
|
||||
def download_file(session, rec, out_path):
|
||||
"""GET 预签名地址下载,落盘到 out_path。"""
|
||||
url = rec.get("downloadUrl") or ""
|
||||
if not url:
|
||||
raise RuntimeError("下载记录里没有 downloadUrl")
|
||||
_log(f"开始下载:{os.path.basename(out_path)}", "DEBUG")
|
||||
resp = session.get(url, timeout=config.DOWNLOAD_TIMEOUT)
|
||||
resp.raise_for_status()
|
||||
content = resp.content
|
||||
if not content:
|
||||
raise RuntimeError("下载到的文件为空")
|
||||
os.makedirs(os.path.dirname(out_path), exist_ok=True)
|
||||
with open(out_path, "wb") as f:
|
||||
f.write(content)
|
||||
return len(content)
|
||||
|
||||
|
||||
def mark_read(session, rec_id):
|
||||
"""标记已读(失败只告警,不影响产物)。"""
|
||||
if not rec_id:
|
||||
return
|
||||
try:
|
||||
body = login_mod.api_post(session, config.API_MARK_READ + str(rec_id), {})
|
||||
_log(f"已标记已读:{body.get('data') or body.get('message')}", "DEBUG")
|
||||
except Exception as exc:
|
||||
_log(f"标记已读失败(不影响文件):{exc}", "WARN")
|
||||
|
||||
|
||||
def safe_name(text):
|
||||
"""文件名清洗(商户名可能含空格/斜杠等)。"""
|
||||
bad = '\\/:*?"<>|\r\n\t'
|
||||
cleaned = "".join("_" if ch in bad else ch for ch in str(text or "")).strip(" .")
|
||||
return cleaned or "商户"
|
||||
|
||||
|
||||
def export_trade(account, password, save_dir, begin, end, stamp,
|
||||
progress_from=0, progress_to=45, login_mode=None):
|
||||
"""单账号完整导出。返回 {success, merchant, file, size, message}。
|
||||
|
||||
文件名 = {商户名}_交易记录_{日期区间}.xlsx(商户名登录后才拿到,故在函数内生成)。
|
||||
login_mode:自动(接口登录)/ 人工登录(弹浏览器人工过验证码)。
|
||||
"""
|
||||
def step(pct):
|
||||
span = progress_to - progress_from
|
||||
config.progress(progress_from + int(span * pct / 100.0))
|
||||
|
||||
result = {"success": False, "merchant": "", "file": "", "size": 0, "message": ""}
|
||||
|
||||
step(5)
|
||||
login_result = login_mod.ensure_login(account, password, login_mode)
|
||||
if not login_result.get("success"):
|
||||
result["message"] = login_result.get("message") or "登录失败"
|
||||
return result
|
||||
|
||||
session = login_result["session"]
|
||||
merchant = login_result.get("merchant") or account
|
||||
result["merchant"] = merchant
|
||||
file_name = f"{safe_name(merchant)}_{config.FILE_TITLE}_{stamp}.xlsx"
|
||||
step(25)
|
||||
|
||||
before_ids = {rec.get("id") for rec in download_list(session)}
|
||||
_log(f"[{merchant}] 提交前下载中心已有 {len(before_ids)} 条记录", "DEBUG")
|
||||
|
||||
submit_export(session, begin, end)
|
||||
step(40)
|
||||
|
||||
_log(f"[{merchant}] 等待平台生成文件…")
|
||||
rec = wait_new_record(session, before_ids)
|
||||
_log(f"[{merchant}] 导出完成:{rec.get('fileName')}")
|
||||
step(70)
|
||||
|
||||
out_path = os.path.join(save_dir, file_name)
|
||||
size = download_file(session, rec, out_path)
|
||||
mark_read(session, rec.get("id"))
|
||||
step(100)
|
||||
|
||||
result.update({"success": True, "file": out_path, "size": size,
|
||||
"message": f"{os.path.basename(out_path)}({size / 1024:.0f} KB)"})
|
||||
_log(f"[{merchant}] 已落盘:{out_path}({size} 字节)")
|
||||
return result
|
||||
@@ -0,0 +1,311 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0079 登录模块:天阙会生活商户平台账密登录(纯接口,自包含)。
|
||||
|
||||
登录流程(与网页完全一致,2026-11 抓包 + 前端 bundle 核实):
|
||||
1) POST bankLogin/imageCode {} → data.imageKey + data.captchaBase64
|
||||
2) ddddocr 识别 4 位图形验证码(同一 imageKey 只能提交一次,识别不中直接换图)
|
||||
3) POST user/transForm/login {header:{sysType:pc}, data:{loginAcc, loginPwd, imageCode, imageKey}}
|
||||
loginPwd = AES-128-ECB/Pkcs7/Base64(明文密码),key 固定 abcdefgabcdefg12
|
||||
→ code=0000 时 data.users[0].token 即后续业务接口的请求头 token
|
||||
|
||||
两种登录方式(登录方式字段可选):
|
||||
- 自动:上面这套纯接口流程,验证码用 ddddocr 识别;
|
||||
- 人工登录:交给 tianque_browser.manual_login,弹浏览器预填账号密码,人工过验证码,
|
||||
不自动提交表单,不消耗接口登录重试轮次。两种方式都优先复用本机缓存的 token。
|
||||
|
||||
已知坑位:
|
||||
- 站点 HTTPS 用弱 DH 参数,Python/OpenSSL3 直连报 DH_KEY_TOO_SMALL,必须把 SECLEVEL 降到 0。
|
||||
- 登录 body 必须套 {header,data} 信封;漏了信封服务端取不到 data,只会回 code=1003
|
||||
「用户名或密码错误」,非常误导(业务接口相反:扁平 body,套了信封回 0003 参数不完整)。
|
||||
- 1003 同时代表「验证码识别错」和「账号密码错」,服务端不区分,因此只能换图重试有限轮次。
|
||||
- token 按账号缓存,复用时先用只读探针校验,避免拿着过期 token 白跑。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
|
||||
import requests
|
||||
from Crypto.Cipher import AES
|
||||
from Crypto.Util.Padding import pad
|
||||
from requests.adapters import HTTPAdapter
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
|
||||
# ==================== 会话 ====================
|
||||
class _LowSecAdapter(HTTPAdapter):
|
||||
"""站点 DH 参数过弱(OpenSSL 3 默认拒绝),这里降级安全级别。"""
|
||||
|
||||
def init_poolmanager(self, *args, **kwargs):
|
||||
ctx = ssl.create_default_context()
|
||||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
kwargs["ssl_context"] = ctx
|
||||
return super().init_poolmanager(*args, **kwargs)
|
||||
|
||||
|
||||
def new_session():
|
||||
session = requests.Session()
|
||||
session.mount("https://", _LowSecAdapter())
|
||||
session.headers.update({
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
"Origin": config.BASE_URL,
|
||||
"Referer": config.BASE_URL + "/login",
|
||||
"channel": config.CHANNEL,
|
||||
"omp_sui_pc": "pc",
|
||||
"User-Agent": config.UA,
|
||||
})
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 请求封装 ====================
|
||||
def envelope(payload):
|
||||
"""user/transForm/* 这组接口的 body 信封。"""
|
||||
return {"header": {"sysType": "pc"}, "data": payload}
|
||||
|
||||
|
||||
def api_post(session, path, payload=None):
|
||||
"""POST 业务接口。返回解析后的 dict;空响应体返回 {'_empty': True}(exportNew 就是空响应)。"""
|
||||
resp = session.post(config.BASE_URL + path,
|
||||
json=payload if payload is not None else {},
|
||||
timeout=config.TIMEOUT)
|
||||
text = (resp.text or "").strip()
|
||||
if not text:
|
||||
return {"_empty": True, "_status": resp.status_code}
|
||||
try:
|
||||
return resp.json()
|
||||
except ValueError:
|
||||
raise RuntimeError(f"{path} 返回非 JSON(HTTP {resp.status_code}):{text[:200]}")
|
||||
|
||||
|
||||
def resp_code(body):
|
||||
"""业务返回码:新接口用 code,老接口用 errorType。"""
|
||||
if not isinstance(body, dict):
|
||||
return ""
|
||||
code = body.get("code")
|
||||
if code is None:
|
||||
code = body.get("errorType")
|
||||
return "" if code is None else str(code)
|
||||
|
||||
|
||||
def resp_msg(body):
|
||||
if not isinstance(body, dict):
|
||||
return ""
|
||||
return str(body.get("msg") or body.get("message") or "")
|
||||
|
||||
|
||||
# ==================== 密码加密 / 验证码 ====================
|
||||
def enc_password(password):
|
||||
"""AES-128-ECB + Pkcs7 + Base64,与前端 CryptoJS 实现逐字一致。"""
|
||||
cipher = AES.new(config.AES_KEY, AES.MODE_ECB)
|
||||
return base64.b64encode(cipher.encrypt(pad(password.encode("utf-8"), 16))).decode()
|
||||
|
||||
|
||||
def fetch_captcha(session):
|
||||
"""返回 (imageKey, 图片 bytes)。同一 imageKey 登录只能提交一次。"""
|
||||
body = api_post(session, config.API_IMAGE_CODE)
|
||||
data = (body or {}).get("data") or {}
|
||||
image_key = str(data.get("imageKey") or "")
|
||||
b64 = str(data.get("captchaBase64") or "")
|
||||
if not image_key or not b64:
|
||||
raise RuntimeError(f"获取图形验证码失败:{json.dumps(body, ensure_ascii=False)[:200]}")
|
||||
return image_key, base64.b64decode(b64)
|
||||
|
||||
|
||||
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 len(code) == config.CAPTCHA_LEN and code.isascii() and code.isalnum():
|
||||
return code
|
||||
return ""
|
||||
|
||||
|
||||
def do_login(session, account, password, image_key, image_code):
|
||||
payload = envelope({
|
||||
"loginAcc": account,
|
||||
"loginPwd": enc_password(password),
|
||||
"imageCode": image_code,
|
||||
"imageKey": image_key,
|
||||
})
|
||||
return api_post(session, config.API_LOGIN, payload)
|
||||
|
||||
|
||||
# ==================== token 校验与缓存 ====================
|
||||
def verify_token(session):
|
||||
"""只读探针校验 token(业务接口用扁平 body)。返回 (ok, 说明)。"""
|
||||
try:
|
||||
body = api_post(session, config.API_PROBE, {"queryType": "D"})
|
||||
except Exception as exc:
|
||||
return False, f"探针异常:{exc}"
|
||||
code = resp_code(body)
|
||||
if code in config.CODE_OK:
|
||||
return True, "有效"
|
||||
return False, f"code={code} {resp_msg(body)}"
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
tmp = f"{path}.tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def load_cached(account):
|
||||
"""读该账号缓存的 token,返回 dict 或 None。"""
|
||||
path = config.get_token_file()
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
all_data = json.load(f) or {}
|
||||
return (all_data.get("accounts") or {}).get(config.account_key(account))
|
||||
except Exception as exc:
|
||||
_log(f"读取 token 缓存失败(忽略):{exc}", "WARN")
|
||||
return None
|
||||
|
||||
|
||||
def save_cached(account, token, merchant):
|
||||
path = config.get_token_file()
|
||||
try:
|
||||
all_data = {"accounts": {}}
|
||||
if os.path.exists(path):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
all_data = json.load(f) or {}
|
||||
except Exception:
|
||||
all_data = {"accounts": {}}
|
||||
all_data.setdefault("accounts", {})[config.account_key(account)] = {
|
||||
"token": token,
|
||||
"merchant": merchant,
|
||||
"savedAt": int(time.time()),
|
||||
}
|
||||
_atomic_write(path, json.dumps(all_data, ensure_ascii=False, indent=2))
|
||||
_log(f"token 已缓存({merchant or account})", "DEBUG")
|
||||
except Exception as exc:
|
||||
_log(f"token 缓存写入失败(不影响本次运行):{exc}", "WARN")
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def ensure_login(account, password, login_mode=None):
|
||||
"""确保拿到可用 token。
|
||||
|
||||
login_mode:
|
||||
- 自动(默认):接口登录(验证码 OCR),静默不弹浏览器;
|
||||
- 人工登录:弹可见浏览器预填账号密码,人工输验证码并点登录,插件读 sessionStorage 取 token。
|
||||
返回 dict:{success, session, token, user, merchant, message, reused}
|
||||
失败时 success=False,message 说明原因(账号密码错误不重试,避免锁号)。
|
||||
"""
|
||||
account = str(account or "").strip()
|
||||
password = str(password or "").strip()
|
||||
login_mode = login_mode or config.LOGIN_AUTO
|
||||
|
||||
session = new_session()
|
||||
|
||||
# 1) 先试缓存 token(两种登录方式都优先复用它,省一次验证码)
|
||||
cached = load_cached(account)
|
||||
if cached and cached.get("token"):
|
||||
session.headers["token"] = cached["token"]
|
||||
ok, why = verify_token(session)
|
||||
if ok:
|
||||
merchant = cached.get("merchant") or account
|
||||
_log(f"复用缓存登录态:{merchant}(token 仍有效)")
|
||||
return {"success": True, "session": session, "token": cached["token"],
|
||||
"user": {"merchantName": merchant}, "merchant": merchant,
|
||||
"message": "复用缓存登录态", "reused": True}
|
||||
_log(f"缓存 token 已失效({why}),改为{'人工' if login_mode == config.LOGIN_MANUAL else '接口'}登录")
|
||||
|
||||
# 2) 人工登录通道:不自动提交表单,验证码由人看,不消耗重试轮次
|
||||
if login_mode == config.LOGIN_MANUAL:
|
||||
from . import tianque_browser # 延迟导入:只有人工登录才需要 DrissionPage
|
||||
result = tianque_browser.manual_login(account, password)
|
||||
if not result.get("success"):
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": result.get("message") or "人工登录失败"}
|
||||
token = result["token"]
|
||||
merchant = result.get("merchant") or account
|
||||
session.headers["token"] = token
|
||||
ok, why = verify_token(session)
|
||||
if not ok:
|
||||
_log(f"人工登录已拿到 token,但探针校验未通过({why}),仍继续尝试导出", "WARN")
|
||||
save_cached(account, token, merchant)
|
||||
return {"success": True, "session": session, "token": token,
|
||||
"user": result.get("user") or {}, "merchant": merchant,
|
||||
"message": "人工登录成功", "reused": False}
|
||||
|
||||
if not (account and password):
|
||||
return {"success": False, "message": "登录账号/密码缺失:请在插件界面填写并保存配置",
|
||||
"session": session, "token": "", "user": {}, "merchant": "", "reused": False}
|
||||
|
||||
# 3) 账密登录(验证码识别失败换图重试,轮次有限)
|
||||
last_msg = ""
|
||||
for attempt in range(1, config.LOGIN_MAX_ATTEMPTS + 1):
|
||||
_log(f"登录第 {attempt}/{config.LOGIN_MAX_ATTEMPTS} 轮({account})")
|
||||
try:
|
||||
image_key, img = fetch_captcha(session)
|
||||
code = ocr_code(img)
|
||||
except Exception as exc:
|
||||
last_msg = f"获取验证码异常:{exc}"
|
||||
_log(last_msg, "WARN")
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
|
||||
if not code:
|
||||
last_msg = "本轮验证码未识别出来"
|
||||
_log(last_msg, "WARN")
|
||||
continue
|
||||
_log(f"图形验证码 OCR:{code}", "DEBUG")
|
||||
|
||||
try:
|
||||
body = do_login(session, account, password, image_key, code)
|
||||
except Exception as exc:
|
||||
last_msg = f"登录请求异常:{exc}"
|
||||
_log(last_msg, "WARN")
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
|
||||
code_str = resp_code(body)
|
||||
msg = resp_msg(body)
|
||||
if code_str in config.CODE_OK:
|
||||
data = body.get("data") or {}
|
||||
users = data.get("users") or []
|
||||
if not users:
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": f"登录成功但无用户信息:{json.dumps(body, ensure_ascii=False)[:200]}"}
|
||||
user = users[0]
|
||||
token = str(user.get("token") or "")
|
||||
merchant = str(user.get("merchantName") or user.get("userName") or account)
|
||||
session.headers["token"] = token
|
||||
_log(f"登录成功:{merchant}(mno={user.get('mno')})")
|
||||
save_cached(account, token, merchant)
|
||||
return {"success": True, "session": session, "token": token, "user": user,
|
||||
"merchant": merchant, "message": "登录成功", "reused": False}
|
||||
|
||||
last_msg = f"code={code_str} {msg}"
|
||||
_log(f"登录未通过:{last_msg}", "WARN")
|
||||
# 1003 = 验证码错或账号密码错(服务端不区分)→ 换图再试一轮
|
||||
if code_str == config.CODE_BAD_OR_CAPTCHA:
|
||||
time.sleep(config.LOGIN_RETRY_SLEEP)
|
||||
continue
|
||||
# 其它错误(未绑账号等)重试无意义
|
||||
return {"success": False, "session": session, "token": "", "user": {},
|
||||
"merchant": "", "reused": False,
|
||||
"message": f"登录失败:{msg or code_str}(如为账号密码错误,请先在网页端确认,避免锁号)"}
|
||||
|
||||
return {"success": False, "session": session, "token": "", "user": {}, "merchant": "",
|
||||
"reused": False,
|
||||
"message": f"{config.LOGIN_MAX_ATTEMPTS} 轮登录均未通过({last_msg});"
|
||||
f"多为验证码识别率问题,可重跑,若持续失败请核对账号密码"}
|
||||
Reference in New Issue
Block a user