feat: 新增银行卡检查插件及相关依赖与配置文件
This commit is contained in:
@@ -0,0 +1,564 @@
|
||||
# -*- 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
|
||||
Reference in New Issue
Block a user