- tests/tianque_probe:天阙会生活商户平台登录(drission)/报表抓包/导出探测脚本,供 XQ0079 排查字段与接口用 - 删除临时脚本 .tmp_check_wf0033.py
294 lines
12 KiB
Python
294 lines
12 KiB
Python
"""天阙会生活商户平台(mch-web.tianquetech.com)接口登录联调脚本。
|
||
|
||
用法:
|
||
1. 在下面「配置区」填 ACCOUNT / PASSWORD(也可写在同目录 account.json)
|
||
2. 运行:d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_login_test.py
|
||
|
||
流程:imageCode 取图(imageKey + captchaBase64)→ ddddocr 识别(同一 imageKey 只能用一次)
|
||
→ AES-128-ECB/PKCS7/Base64 加密密码(key 硬编码 abcdefgabcdefg12)
|
||
→ user/transForm/login 登录(body 必须套 {header,data} 信封)
|
||
→ 登录成功取 data.users[0].token,写入 sessionStorage.user 的等价对象。
|
||
|
||
已知坑位(2026-11 抓前端 bundle 核实):
|
||
- 站点 HTTPS 使用弱 DH 参数,Python/OpenSSL3 直连报 SSL: DH_KEY_TOO_SMALL,必须降 SECLEVEL。
|
||
- 登录接口是 /management/easypay/api/user/transForm/login;老接口 bankLogin/loginByAccount
|
||
是另一个入口(只校验图形验证码就报 IMG_WRONG,密码走不同校验),直连它永远「用户名或密码错误」。
|
||
- user/transForm/* 这组接口的 body 要套一层信封:{"header":{"sysType":"pc"},"data":{真实参数}}。
|
||
漏了信封服务端拿不到 data,只会返回 code=1003「用户名或密码错误」,非常误导。
|
||
但 tranInfo/bankAcc 等业务接口仍是扁平 body,套信封会返回 0003「参数不完整」。
|
||
- 请求头固定带 channel: WELIFE-PC、omp_sui_pc: pc;登录成功后业务接口带 token 头。
|
||
- transForm/login 成功码是 code=0000;失败返回 code + msg,且「验证码错」和「密码错」同样返回
|
||
1003「用户名或密码错误」(前端不做区分),所以只能换图重试。
|
||
"""
|
||
|
||
import base64
|
||
import json
|
||
import os
|
||
import ssl
|
||
import sys
|
||
from datetime import datetime
|
||
|
||
import requests
|
||
from Crypto.Cipher import AES
|
||
from Crypto.Util.Padding import pad
|
||
from requests.adapters import HTTPAdapter
|
||
|
||
# Windows 控制台默认 GBK,统一按 UTF-8 输出,避免 PowerShell/VSCode 终端中文乱码
|
||
if hasattr(sys.stdout, "reconfigure"):
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
# ==================== 配置区 ====================
|
||
ACCOUNT = "***REMOVED***" # 663 账号或手机号
|
||
PASSWORD = "***REMOVED***" # 登录密码(明文,脚本内部加密)
|
||
MAX_ATTEMPTS = 5 # 提交轮次上限(服务端不区分验证码错/密码错,只能换图重试)
|
||
SAVE_TOKEN = True # 登录成功后把用户信息落到临时文件,便于后续接口联调
|
||
VERIFY_TOKEN = True # 登录成功后调用一次交易汇总接口验证 token 是否可用
|
||
SAVE_CAPTCHA = True # 每轮验证码原图落盘,便于人工核对 OCR 是否识别错
|
||
CAPTCHA_KEEP = 30 # 最多保留最近多少张验证码图片
|
||
CAPTCHA_LEN = 4 # 验证码位数,识别结果长度/字符不符直接换图,不浪费提交次数
|
||
DEBUG_DUMP = True # 打印实际提交的请求体(含密码密文),便于和浏览器 F12 抓包逐字对比
|
||
# ===============================================
|
||
|
||
CAPTCHA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "captcha")
|
||
|
||
BASE = "https://mch-web.tianquetech.com"
|
||
TIMEOUT = 20
|
||
AES_KEY = b"abcdefgabcdefg12" # 前端硬编码:CryptoJS AES ECB + Pkcs7
|
||
|
||
# 接口路径(与前端 umi bundle 实际调用一致)
|
||
URL_IMAGE_CODE = "/management/easypay/api/bankLogin/imageCode"
|
||
URL_LOGIN = "/management/easypay/api/user/transForm/login"
|
||
URL_PROBE = "/management/easypay/api/tranInfo/queryTranSumByDate" # 只读探针,用于校验 token
|
||
|
||
TOKEN_FILE = os.path.join(os.environ.get("TEMP", "."), "tianque_token.json")
|
||
|
||
ERR_IMG_WRONG = "IMG_WRONG"
|
||
ERR_LOGIN = "LOGIN_ERROR"
|
||
ERR_ROLE_UNBIND = "ROLE_UN_BIND"
|
||
CODE_OK = ("0000", "200")
|
||
CODE_BAD_OR_CAPTCHA = "1003" # transForm/login:验证码错与账号密码错共用此码
|
||
|
||
# 同目录 account.json 兜底配置:{"account": "...", "password": "..."}
|
||
_ACC_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "account.json")
|
||
if os.path.exists(_ACC_FILE):
|
||
try:
|
||
_acc = json.load(open(_ACC_FILE, encoding="utf-8"))
|
||
ACCOUNT = ACCOUNT or _acc.get("account", "")
|
||
PASSWORD = PASSWORD or _acc.get("password", "")
|
||
except Exception as exc: # 配置写坏不应阻断,直接提示
|
||
print(f"读取 account.json 失败:{exc}")
|
||
|
||
|
||
def log(msg):
|
||
print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True)
|
||
|
||
|
||
class _LowSecAdapter(HTTPAdapter):
|
||
"""站点 DH 参数过弱(OpenSSL 3 默认拒绝),这里降级安全级别。"""
|
||
|
||
def init_poolmanager(self, *args, **kwargs):
|
||
ctx = ssl.create_default_context()
|
||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||
kwargs["ssl_context"] = ctx
|
||
return super().init_poolmanager(*args, **kwargs)
|
||
|
||
|
||
def new_session():
|
||
s = requests.Session()
|
||
s.mount("https://", _LowSecAdapter())
|
||
s.headers.update({
|
||
"Content-Type": "application/json",
|
||
"Accept": "application/json, text/plain, */*",
|
||
"Origin": BASE,
|
||
"Referer": BASE + "/login",
|
||
"channel": "WELIFE-PC",
|
||
"omp_sui_pc": "pc",
|
||
"User-Agent": (
|
||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||
),
|
||
})
|
||
return s
|
||
|
||
|
||
def post_json(session, path, payload=None):
|
||
r = session.post(BASE + path, json=payload if payload is not None else {}, timeout=TIMEOUT)
|
||
try:
|
||
return r.json()
|
||
except ValueError:
|
||
raise RuntimeError(f"{path} 返回非 JSON(HTTP {r.status_code}):{r.text[:200]}")
|
||
|
||
|
||
def enc_password(pwd):
|
||
cipher = AES.new(AES_KEY, AES.MODE_ECB)
|
||
return base64.b64encode(cipher.encrypt(pad(pwd.encode("utf-8"), 16))).decode()
|
||
|
||
|
||
def ocr_image(img_bytes):
|
||
try:
|
||
import ddddocr
|
||
except ImportError:
|
||
raise RuntimeError("未安装 ddddocr,请先 pip install ddddocr")
|
||
return ddddocr.DdddOcr(show_ad=False).classification(img_bytes).strip()
|
||
|
||
|
||
def ocr_code_ok(code):
|
||
"""验证码是 4 位 ASCII 字母数字;识别出中文/位数不符说明识别错了,直接换图。"""
|
||
return len(code) == CAPTCHA_LEN and code.isascii() and code.isalnum()
|
||
|
||
|
||
def fetch_captcha(session):
|
||
"""返回 (imageKey, 验证码图片 bytes),同一 imageKey 登录只能提交一次。"""
|
||
data = post_json(session, URL_IMAGE_CODE)
|
||
body = data.get("data") or {}
|
||
image_key = body.get("imageKey") or ""
|
||
b64 = body.get("captchaBase64") or ""
|
||
if not image_key or not b64:
|
||
raise RuntimeError(f"获取图形验证码失败:{json.dumps(data, ensure_ascii=False)[:300]}")
|
||
return image_key, base64.b64decode(b64)
|
||
|
||
|
||
def save_captcha(img_bytes, image_key, code):
|
||
"""把本轮验证码原图落盘,文件名带 OCR 结果,方便人工核对识别是否正确。"""
|
||
if not SAVE_CAPTCHA:
|
||
return ""
|
||
os.makedirs(CAPTCHA_DIR, exist_ok=True)
|
||
|
||
# 顺手清理旧图,只保留最近 CAPTCHA_KEEP 张
|
||
olds = sorted(
|
||
(os.path.join(CAPTCHA_DIR, f) for f in os.listdir(CAPTCHA_DIR) if f.lower().endswith((".jpg", ".png"))),
|
||
key=os.path.getmtime,
|
||
)
|
||
for f in olds[: max(0, len(olds) - CAPTCHA_KEEP + 1)]:
|
||
try:
|
||
os.remove(f)
|
||
except OSError:
|
||
pass
|
||
|
||
ext = "jpg" if img_bytes[:2] == b"\xff\xd8" else "png"
|
||
name = f"{datetime.now():%Y%m%d-%H%M%S}_ocr-{code or 'empty'}_{image_key}.{ext}"
|
||
path = os.path.join(CAPTCHA_DIR, name)
|
||
with open(path, "wb") as f:
|
||
f.write(img_bytes)
|
||
return path
|
||
|
||
|
||
def envelope(payload):
|
||
"""前端请求封装给 POST body 套的信封:{"header":{"sysType":"pc"},"data":{...}}。
|
||
少了这层,服务端取不到 data,只会回 code=1003「用户名或密码错误」。"""
|
||
return {"header": {"sysType": "pc"}, "data": payload}
|
||
|
||
|
||
def do_login(session, account, password, image_key, image_code):
|
||
payload = {
|
||
"loginAcc": account.strip(),
|
||
"loginPwd": enc_password(password.strip()),
|
||
"imageCode": image_code,
|
||
"imageKey": image_key,
|
||
}
|
||
return post_json(session, URL_LOGIN, envelope(payload))
|
||
|
||
|
||
def verify_token(session, token):
|
||
"""用只读接口探一下 token,仅作提示,不影响登录结论。
|
||
注意:业务接口(tranInfo 等)走扁平 body,不要套信封;套了会返回 0003 参数不完整。"""
|
||
try:
|
||
data = post_json(session, URL_PROBE, {"queryType": "D"})
|
||
except Exception as exc:
|
||
return f"探针请求异常:{exc}"
|
||
code = str(data.get("code", ""))
|
||
if code in CODE_OK:
|
||
return f"token 有效(探针 code={code})"
|
||
return f"探针返回 code={code} msg={data.get('msg') or data.get('message')}"
|
||
|
||
|
||
def main():
|
||
if not ACCOUNT or not PASSWORD:
|
||
log("请先在脚本顶部配置区填写 ACCOUNT / PASSWORD(或同目录 account.json)")
|
||
return False
|
||
|
||
session = new_session()
|
||
|
||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||
log(f"===== 第 {attempt}/{MAX_ATTEMPTS} 轮 =====")
|
||
try:
|
||
image_key, png = fetch_captcha(session)
|
||
except Exception as exc:
|
||
log(f"获取验证码失败:{exc}")
|
||
return False
|
||
|
||
code = ocr_image(png)
|
||
log(f"图形验证码 OCR:{code or '识别为空'}")
|
||
saved = save_captcha(png, image_key, code)
|
||
if saved:
|
||
log(f"验证码原图:{saved}")
|
||
if not code:
|
||
continue
|
||
if not ocr_code_ok(code):
|
||
log(f"识别结果格式不符(应为 {CAPTCHA_LEN} 位字母数字),换一张重试")
|
||
continue
|
||
|
||
try:
|
||
resp = do_login(session, ACCOUNT, PASSWORD, image_key, code)
|
||
except Exception as exc:
|
||
log(f"登录请求异常:{exc}")
|
||
return False
|
||
|
||
code_str = str(resp.get("code", ""))
|
||
err = resp.get("errorType")
|
||
msg = resp.get("msg") or resp.get("message") or ""
|
||
if code_str in CODE_OK and not err:
|
||
data = resp.get("data") or {}
|
||
users = data.get("users") or []
|
||
if not users:
|
||
log(f"登录返回成功但无用户信息:{json.dumps(resp, ensure_ascii=False)[:300]}")
|
||
return False
|
||
|
||
count = data.get("userInfoCount") or len(users)
|
||
log(f"登录成功,可选账号数 userInfoCount={count},accountId={data.get('accountId')}")
|
||
if count > 1:
|
||
log("注意:该账号下挂多个商户,网页端会弹账号选择,脚本默认取第一个 users[0]")
|
||
|
||
user = users[0]
|
||
token = user.get("token") or ""
|
||
log(f"登录账号:{user.get('loginAcc') or user.get('accountName') or ACCOUNT}"
|
||
f" token={token[:24]}...(共 {len(token)} 字符)")
|
||
log("firstLogin 标记:" + str(user.get("firstLogin")))
|
||
|
||
if VERIFY_TOKEN and token:
|
||
session.headers["token"] = token
|
||
log("token 校验:" + verify_token(session, token))
|
||
|
||
if SAVE_TOKEN:
|
||
with open(TOKEN_FILE, "w", encoding="utf-8") as f:
|
||
json.dump({"token": token, "user": user, "savedAt": datetime.now().isoformat()},
|
||
f, ensure_ascii=False, indent=2)
|
||
log(f"用户信息已保存:{TOKEN_FILE}")
|
||
return True
|
||
|
||
if err == ERR_IMG_WRONG:
|
||
log("图形验证码未通过,换一张重试")
|
||
continue
|
||
|
||
if err == ERR_ROLE_UNBIND:
|
||
log("该手机号未关联任何账号(ROLE_UN_BIND),需先在网页端换绑手机号")
|
||
return False
|
||
|
||
# transForm/login 对「验证码错」和「账号密码错」返回同一个 code=1003,只能换图再试一轮
|
||
if code_str == CODE_BAD_OR_CAPTCHA:
|
||
log(f"登录未通过(code={code_str} {msg})——验证码识别错或账号密码错,换图重试")
|
||
continue
|
||
|
||
log(f"未预期错误:code={code_str} errorType={err} msg={msg},停止重试")
|
||
return False
|
||
|
||
log(f"{MAX_ATTEMPTS} 轮均未通过(多为验证码 OCR 识别率问题,可重跑;若始终失败请核对账号密码)")
|
||
return False
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(0 if main() else 1)
|