- 新增 tests/_env.py:统一读仓库根 .env(仅标准库,进程内缓存) - tianque 探针 6 个脚本改读 tq_login_username / tq_login_password,account.json 仅兜底 - workflows/share/erp_login.py 的 __main__ 去掉硬编码 ERP 账号密码(改由 .env 提供) - docs/需求单/README.md 的负责人手机号做脱敏
216 lines
7.5 KiB
Python
216 lines
7.5 KiB
Python
"""天阙会生活商户平台:用 DrissionPage 真浏览器登录,拿到 token 后再用 requests 调业务接口。
|
||
|
||
思路:接口直连登录一直报「用户名或密码错误」,但同一账号密码在浏览器里能正常登录,
|
||
说明密文/参数没问题,差异在客户端环境。这里直接用浏览器完成登录动作,
|
||
再把浏览器 sessionStorage 里的 token 交给 requests 用——绕开登录环节的环境差异。
|
||
|
||
用法:
|
||
d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_login_drission.py
|
||
|
||
配置:账号密码取 tianque_login_test.py 顶部,或同目录 account.json
|
||
"""
|
||
|
||
import base64
|
||
import json
|
||
import os
|
||
import ssl
|
||
import sys
|
||
import time
|
||
from datetime import datetime
|
||
|
||
import requests
|
||
from requests.adapters import HTTPAdapter
|
||
|
||
if hasattr(sys.stdout, "reconfigure"):
|
||
try:
|
||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||
except Exception:
|
||
pass
|
||
|
||
# ==================== 配置区 ====================
|
||
HEADLESS = False # 是否无头运行(无头时更方便定时任务,但验证码识别率略低)
|
||
MAX_SUBMIT = 4 # 验证码识别错时最多重试次数
|
||
LOGIN_TIMEOUT = 40 # 等 token 出现的秒数
|
||
VERIFY_TOKEN = True # 登录后用 requests 调一次交易汇总接口,验证 token 可用于纯 HTTP
|
||
# ===============================================
|
||
|
||
LOGIN_URL = "https://mch-web.tianquetech.com/login"
|
||
BASE = "https://mch-web.tianquetech.com"
|
||
URL_PROBE = "/management/easypay/api/tranInfo/queryTranSumByDate"
|
||
|
||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||
TOKEN_FILE = os.path.join(os.environ.get("TEMP", "."), "tianque_token.json")
|
||
|
||
# 账号密码只放仓库根 .env(tq_login_username / tq_login_password),account.json 仅兜底
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
from _env import get as _env_get # noqa: E402
|
||
|
||
_ACC = _env_get("tq_login_username")
|
||
_PWD = _env_get("tq_login_password")
|
||
|
||
_ACC_FILE = os.path.join(_HERE, "account.json")
|
||
if os.path.exists(_ACC_FILE):
|
||
try:
|
||
_conf = json.load(open(_ACC_FILE, encoding="utf-8"))
|
||
_ACC = _ACC or _conf.get("account", "")
|
||
_PWD = _PWD or _conf.get("password", "")
|
||
except Exception as exc:
|
||
print(f"读取 account.json 失败:{exc}")
|
||
|
||
ACCOUNT = _ACC
|
||
PASSWORD = _PWD
|
||
|
||
|
||
def log(msg):
|
||
print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True)
|
||
|
||
|
||
def ocr_data_url(src):
|
||
if not src or "base64," not in src:
|
||
return ""
|
||
import ddddocr
|
||
return ddddocr.DdddOcr(show_ad=False).classification(base64.b64decode(src.split("base64,", 1)[1])).strip()
|
||
|
||
|
||
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_ready(page, timeout=40):
|
||
for _ in range(timeout):
|
||
n = js(page, "return document.querySelectorAll('input').length")
|
||
if (n or 0) >= 3:
|
||
return True
|
||
time.sleep(1)
|
||
return False
|
||
|
||
|
||
def browser_login(page):
|
||
acc = page.ele('css:input[placeholder*="商户"]', timeout=10) or page.ele('css:input[type="text"]', timeout=3)
|
||
pwd = page.ele('css:input[type="password"]', timeout=5)
|
||
code_ele = page.ele('css:input[placeholder*="验证码"]', timeout=5)
|
||
if not (acc and pwd and code_ele):
|
||
log("登录表单元素没找齐,页面结构可能变了")
|
||
return None
|
||
|
||
acc.clear()
|
||
acc.input(ACCOUNT)
|
||
pwd.clear()
|
||
pwd.input(PASSWORD)
|
||
log(f"已填入账号 {ACCOUNT!r}、密码(长度 {len(PASSWORD)})")
|
||
|
||
for attempt in range(1, MAX_SUBMIT + 1):
|
||
img = page.ele('css:img[src^="data:image/jpeg"]', timeout=5)
|
||
code = ocr_data_url(img.attr("src") if img else "")
|
||
log(f"第 {attempt} 次:验证码 OCR = {code or '识别为空'}")
|
||
if not code:
|
||
if img:
|
||
img.click()
|
||
time.sleep(1)
|
||
continue
|
||
|
||
code_ele.clear()
|
||
code_ele.input(code)
|
||
btn = page.ele('css:button.ant-btn-primary', timeout=5) or page.ele("text=登 录", timeout=3)
|
||
if not btn:
|
||
log("没找到登录按钮")
|
||
return None
|
||
btn.click()
|
||
|
||
# 等页面把 user 写进 sessionStorage(登录成功前端会整页跳转,sessionStorage 保留)
|
||
deadline = time.time() + LOGIN_TIMEOUT
|
||
while time.time() < deadline:
|
||
raw = js(page, "return sessionStorage.getItem('user')", times=2)
|
||
if raw:
|
||
try:
|
||
user = json.loads(raw)
|
||
except Exception:
|
||
user = {}
|
||
if user.get("token"):
|
||
return user
|
||
time.sleep(0.5)
|
||
|
||
# 没拿到 token:看页面提示,验证码错就换图重试
|
||
msg = js(page, "return (Array.from(document.querySelectorAll('.ant-message-notice-content'))[0] || {}).innerText || ''")
|
||
log(f"未拿到 token,页面提示:{msg!r}")
|
||
if "验证码" in (msg or ""):
|
||
if img:
|
||
img.click()
|
||
time.sleep(1)
|
||
continue
|
||
return None
|
||
return None
|
||
|
||
|
||
def main():
|
||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||
|
||
if not ACCOUNT or not PASSWORD:
|
||
log("请先配置 ACCOUNT / PASSWORD")
|
||
return False
|
||
|
||
opts = ChromiumOptions().set_argument("--start-maximized")
|
||
if HEADLESS:
|
||
opts.headless(True)
|
||
page = ChromiumPage(opts)
|
||
page.get(LOGIN_URL)
|
||
time.sleep(2)
|
||
js(page, "return sessionStorage.clear()")
|
||
page.refresh()
|
||
time.sleep(2)
|
||
|
||
if not wait_ready(page):
|
||
log("登录页 40 秒未渲染完成")
|
||
return False
|
||
log(f"登录页就绪:{page.url}")
|
||
|
||
user = browser_login(page)
|
||
if not user:
|
||
log("浏览器登录失败")
|
||
return False
|
||
|
||
token = user.get("token") or ""
|
||
log(f"浏览器登录成功:token={token[:24]}...({len(token)} 字符)")
|
||
log(f"账号信息:mobile={user.get('mobile')} mno={user.get('mno')} userName={user.get('userName')!r}")
|
||
|
||
if VERIFY_TOKEN:
|
||
ctx = ssl.create_default_context()
|
||
ctx.set_ciphers("DEFAULT@SECLEVEL=0")
|
||
|
||
class _Low(HTTPAdapter):
|
||
def init_poolmanager(self, *a, **kw):
|
||
kw["ssl_context"] = ctx
|
||
return super().init_poolmanager(*a, **kw)
|
||
|
||
s = requests.Session()
|
||
s.mount("https://", _Low())
|
||
s.headers.update({
|
||
"Content-Type": "application/json",
|
||
"channel": "WELIFE-PC",
|
||
"token": token,
|
||
"Origin": BASE,
|
||
"Referer": BASE + "/bankAccount/",
|
||
})
|
||
try:
|
||
r = s.post(BASE + URL_PROBE, json={"queryType": "D"}, timeout=20).json()
|
||
log(f"requests 带 token 调业务接口:code={r.get('code')} msg={r.get('msg') or r.get('message')}")
|
||
except Exception as exc:
|
||
log(f"requests 调业务接口异常:{exc}")
|
||
|
||
if TOKEN_FILE:
|
||
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 __name__ == "__main__":
|
||
sys.exit(0 if main() else 1)
|