Files
37duAutomation/plugins/XQ0001-0100/XQ0079 金色湖畔扫码数据导出/data/tianque_login.py
T
puddy 359f94742c feat(xq0079): 新增金色湖畔扫码数据导出插件(1.1.4)
- 天阙会生活商户平台(mch-web.tianquetech.com)扫码交易记录导出:账密登录(图形验证码 OCR + AES 密码加密,token 按账号缓存复用)→ 平台导出接口生成 xlsx → 下载中心取文件直存本地

- 支持两套账号串行导出(第 2 套可留空),日期区间界面可选,产物按商户名区分
2026-11-06 15:52:20 +08:00

312 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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"多为验证码识别率问题,可重跑,若持续失败请核对账号密码"}