diff --git a/.tmp_check_wf0033.py b/.tmp_check_wf0033.py deleted file mode 100644 index 97ed220..0000000 --- a/.tmp_check_wf0033.py +++ /dev/null @@ -1,80 +0,0 @@ -# -*- coding: utf-8 -*- -"""临时校验脚本(用后即删):影刀版 attendance_points_update.py 新增快照逻辑。""" -import importlib.util -import os -import shutil -from datetime import date - -import openpyxl - -ROOT = os.path.dirname(os.path.abspath(__file__)) -WF = os.path.join(ROOT, "workflows", "XQ0001-0100", "XQ0033 门店管理及服务岗出勤积分更新", - "attendance_points_update.py") - -spec = importlib.util.spec_from_file_location("wf_xq0033", WF) -m = importlib.util.module_from_spec(spec) -spec.loader.exec_module(m) - -SRC = r"D:\资料\人资\门店管理及服务岗出勤积分更新" -TMP = os.path.join(ROOT, ".tmp_wf0033") -os.makedirs(TMP, exist_ok=True) -shutil.copy2(os.path.join(SRC, "员工出勤及遵章积分导入1026.xlsx"), - os.path.join(TMP, "员工出勤及遵章积分导入1026.xlsx")) -shutil.copy2(os.path.join(SRC, "员工出勤及遵章积分导入1018.xlsx"), - os.path.join(TMP, "员工出勤及遵章积分导入1018.xlsx")) - -m.TARGET_DIR = TMP -m.STATE_FILE = os.path.join(TMP, "_xq0033_state.json") - -try: - # 1) 按积分日期找上轮文件 - got = m.pick_prev_file(date(2026, 10, 18)) - print("pick_prev_file(10-18) ->", os.path.basename(got or "")) - assert got and os.path.basename(got).endswith("1018.xlsx") - assert m.pick_prev_file(date(2026, 10, 25)) is None - - # 2) 新建批次:源文件按积分日期最大 - path, is_new, covered = m.pick_target_file(date(2026, 10, 25)) - print("pick_target_file(10-25) ->", os.path.basename(path), is_new, covered) - assert os.path.basename(path).endswith("1023.xlsx") and is_new and covered == date(2026, 10, 26) - - # 3) 上轮文件今日导出 → 本批前一日导出 - wb = openpyxl.load_workbook(os.path.join(TMP, "员工出勤及遵章积分导入1026.xlsx")) - try: - assert m.read_report_month(wb) == (2026, 10) - t2 = date(2026, 11, 3) - assert m._is_new_month((2026, 10), date(2026, 10, 26), t2) is True - assert m._is_new_month((2026, 11), date(2026, 10, 26), t2) is False - assert m._is_new_month(None, date(2026, 10, 26), t2) is True - assert m._is_new_month(None, date(2026, 10, 28), date(2026, 10, 30)) is False - assert m._is_new_month(None, None, t2) is False - - src = openpyxl.load_workbook(os.path.join(TMP, "员工出勤及遵章积分导入1018.xlsx"), - data_only=True, read_only=True) - try: - expect = [list(r) for r in src[m.SHEET_TODAY].iter_rows( - min_row=m.EXP_DATA_START, min_col=1, max_col=41, values_only=True)] - finally: - src.close() - while expect and all(v in (None, "") for v in expect[-1]): - expect.pop() - - n = m.copy_file_today_to_prev(wb, os.path.join(TMP, "员工出勤及遵章积分导入1018.xlsx")) - assert n == len(expect), (n, len(expect)) - ws = wb[m.SHEET_PREV] - for i in range(0, min(len(expect), 50)): - row = [ws.cell(row=m.EXP_DATA_START + i, column=c).value for c in (1, 9, 10)] - assert row == [expect[i][0], expect[i][8], expect[i][9]], (i, row, expect[i][:10]) - print(f"copy_file_today_to_prev OK:{n} 行,前 50 行一致") - - m.reset_snapshots(wb) - for name in (m.SHEET_TODAY, m.SHEET_PREV): - last = m._scan_last_data_row(wb[name], 1, m.EXP_DATA_START) - assert last == m.EXP_DATA_START - 1, (name, last) - assert wb[m.SHEET_PREV].cell(row=4, column=1).value == "工号" - print("reset_snapshots OK") - finally: - wb.close() -finally: - shutil.rmtree(TMP, ignore_errors=True) -print("ALL OK") diff --git a/tests/tianque_probe/tianque_browser_capture.py b/tests/tianque_probe/tianque_browser_capture.py new file mode 100644 index 0000000..8bdfe26 --- /dev/null +++ b/tests/tianque_probe/tianque_browser_capture.py @@ -0,0 +1,307 @@ +"""用 DrissionPage 打开真实浏览器登录天阙会生活商户平台,捕获浏览器实际提交的登录请求, +把 loginAcc / loginPwd 密文 / 解密明文 / 请求头 与接口脚本的配置逐字对照。 + +用法: + d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_browser_capture.py + + MODE = "auto" 脚本自动清登录态 → 重开登录页 → 填账号密码 → OCR 验证码 → 点登录 + MODE = "manual" 脚本只注入钩子,你自己在浏览器里登录 + +抓取原理: + 登录成功后前端会整页跳转,CDP 监听容易丢包。这里在页面里 hook XMLHttpRequest, + 把 bankLogin 请求的 body 与响应写进 sessionStorage(同标签页跨导航保留), + 跳转后再读出来,稳拿真实请求。 +""" + +import base64 +import json +import os +import sys +import time +from datetime import datetime + +from Crypto.Cipher import AES +from Crypto.Util.Padding import unpad + +if hasattr(sys.stdout, "reconfigure"): + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + +# ==================== 配置区 ==================== +MODE = "manual" # manual=只注入钩子、你手动登录一次(默认,避免反复自动登录触发风控) +MAX_SUBMIT = 3 # auto 模式下最多提交几次(只有验证码识别错才重试) +WAIT_SECONDS = 300 # manual 模式等待你手动登录的秒数 +PAGE_TIMEOUT = 40 # 等待登录页表单渲染的最长秒数 +# =============================================== + +LOGIN_URL = "https://mch-web.tianquetech.com/login" +AES_KEY = b"abcdefgabcdefg12" +KEY_REQ = "__cap_req" +KEY_RES = "__cap_res" + +_HERE = os.path.dirname(os.path.abspath(__file__)) +LOG_FILE = os.path.join(_HERE, "capture.log") + +try: + from tianque_login_test import ACCOUNT as _ACC, PASSWORD as _PWD +except Exception: + _ACC, _PWD = "", "" + +_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 + +# 页面内 hook:把 bankLogin 请求体/响应落到 sessionStorage(跳转后仍可读) +HOOK_JS = """ +(function(){ + if (window.__capHooked) { return 'already'; } + window.__capHooked = true; + function save(k, v) { try { sessionStorage.setItem(k, JSON.stringify(v)); } catch(e) {} } + var XO = XMLHttpRequest.prototype.open, XS = XMLHttpRequest.prototype.send; + XMLHttpRequest.prototype.open = function(m, u) { this.__capUrl = u; return XO.apply(this, arguments); }; + XMLHttpRequest.prototype.send = function(b) { + var self = this; + if (String(self.__capUrl || '').indexOf('bankLogin') >= 0) { + save('__cap_req', {url: self.__capUrl, body: b}); + self.addEventListener('load', function() { + save('__cap_res', {url: self.__capUrl, status: self.status, text: self.responseText}); + }); + } + return XS.apply(this, arguments); + }; + var of = window.fetch; + if (of) { + window.fetch = function(input, init) { + var url = (typeof input === 'string') ? input : (input && input.url) || ''; + if (url.indexOf('bankLogin') >= 0) { + save('__cap_req', {url: url, body: (init && init.body) || ''}); + } + return of.apply(this, arguments).then(function(r) { + if (url.indexOf('bankLogin') >= 0) { + r.clone().text().then(function(t){ save('__cap_res', {url: url, status: r.status, text: t}); }); + } + return r; + }); + }; + } + return 'ok'; +})() +""" + + +def log(msg): + line = f"[{datetime.now():%H:%M:%S}] {msg}" + print(line, flush=True) + try: + with open(LOG_FILE, "a", encoding="utf-8") as f: + f.write(line + "\n") + except Exception: + pass + + +def dec_password(b64_text): + cipher = AES.new(AES_KEY, AES.MODE_ECB) + return unpad(cipher.decrypt(base64.b64decode(b64_text)), 16).decode("utf-8") + + +def parse_body(raw): + if isinstance(raw, dict): + return raw + if not raw: + return {} + try: + return json.loads(raw) + except Exception: + return {"_raw": str(raw)[:300]} + + +def ocr_data_url(src): + if not src or "base64," not in src: + return "" + try: + import ddddocr + except ImportError: + return "" + return ddddocr.DdddOcr(show_ad=False).classification(base64.b64decode(src.split("base64,", 1)[1])).strip() + + +def wait_ready(page, timeout=PAGE_TIMEOUT): + for _ in range(timeout): + n = page.run_js("return document.querySelectorAll('input').length") or 0 + if n >= 3: + return True + time.sleep(1) + return False + + +def reset_login_state(page): + page.get(LOGIN_URL) + time.sleep(1) + try: + page.run_js("return sessionStorage.clear()") + except Exception: + pass + page.refresh() + time.sleep(1) + + +def read_capture(page, timeout=20): + """等页面把登录请求写进 sessionStorage,返回 (req_dict, res_dict)。""" + deadline = time.time() + timeout + req_raw = None + while time.time() < deadline: + req_raw = page.run_js(f"return sessionStorage.getItem('{KEY_REQ}')") + if req_raw: + break + time.sleep(0.5) + if not req_raw: + return None, None + req = parse_body(req_raw) + res_raw = page.run_js(f"return sessionStorage.getItem('{KEY_RES}')") + res = parse_body(res_raw) if res_raw else {} + return req, res + + +def report(req, res): + body = parse_body(req.get("body")) + log("=" * 60) + log(f"抓到请求:{req.get('url')}") + log(f"loginAcc = {body.get('loginAcc')!r}") + log(f"imageCode = {body.get('imageCode')!r}") + log(f"imageKey = {body.get('imageKey')!r}") + cipher_text = body.get("loginPwd") or "" + log(f"loginPwd = {cipher_text}") + + plain = None + if cipher_text: + try: + plain = dec_password(cipher_text) + log(f"解密明文 = {plain!r}(长度 {len(plain)})") + except Exception as exc: + log(f"loginPwd 解密失败:{exc}") + + log("-" * 60) + log(f"脚本 ACCOUNT = {ACCOUNT!r}") + log(f"脚本 PASSWORD = {PASSWORD!r}(长度 {len(PASSWORD)})") + if plain is not None: + if plain == PASSWORD: + log("密码对比:浏览器提交 == 脚本配置 → 加密和密码都没问题") + else: + log("密码对比:浏览器提交 != 脚本配置 → 脚本里密码填错了,以浏览器这份为准") + log(f" 浏览器={plain!r} 脚本={PASSWORD!r}") + if body.get("loginAcc") and ACCOUNT and str(body.get("loginAcc")) != ACCOUNT: + log(f"账号对比:浏览器={body.get('loginAcc')!r} 脚本={ACCOUNT!r}(不一致)") + + text = res.get("text") or "" + log(f"响应:HTTP {res.get('status')} {text[:300]}") + data = parse_body(text) if text else {} + if data.get("errorType"): + log(f"网页登录结果:失败 errorType={data.get('errorType')} message={data.get('message')}") + return False + users = (data.get("data") or {}).get("users") or [] + if users: + token = users[0].get("token") or "" + log(f"网页登录结果:成功 token={token[:24]}...(共 {len(token)} 字符)") + return True + log("网页登录结果:响应结构未识别") + return False + + +def auto_login(page): + acc_ele = page.ele('css:input[placeholder*="商户"]', timeout=10) or page.ele('css:input[type="text"]', timeout=3) + pwd_ele = page.ele('css:input[type="password"]', timeout=5) + code_ele = page.ele('css:input[placeholder*="验证码"]', timeout=5) + if not (acc_ele and pwd_ele and code_ele): + log("表单元素没找齐,转手动模式") + return None + + acc_ele.clear() + acc_ele.input(ACCOUNT) + pwd_ele.clear() + pwd_ele.input(PASSWORD) + log(f"已填入账号 {ACCOUNT!r}、密码(长度 {len(PASSWORD)}),并注入请求钩子") + page.run_js(HOOK_JS) + + for attempt in range(1, MAX_SUBMIT + 1): + img_ele = page.ele('css:img[src^="data:image/jpeg"]', timeout=5) + code = ocr_data_url(img_ele.attr("src") if img_ele else "") + log(f"第 {attempt} 次提交:验证码 OCR = {code or '识别为空'}") + if not code: + if img_ele: + img_ele.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() + + req, res = read_capture(page, timeout=20) + if not req: + log("没捕获到登录请求(前端校验未通过或页面已跳走)") + return None + + ok = report(req, res) + if ok: + return True + body = parse_body(req.get("body")) + data = parse_body(res.get("text")) + if data.get("errorType") != "IMG_WRONG": + return False + log("网页提示验证码错误,换图重试") + page.run_js(f"return sessionStorage.removeItem('{KEY_REQ}')") + img2 = page.ele('css:img[src^="data:image/jpeg"]', timeout=5) + if img2: + img2.click() + time.sleep(1) + return False + + +def main(): + from DrissionPage import ChromiumPage, ChromiumOptions + + if not ACCOUNT or not PASSWORD: + log("请先配置 ACCOUNT / PASSWORD(tianque_login_test.py 顶部或同目录 account.json)") + return False + + log(f"启动浏览器,模式 {MODE}") + page = ChromiumPage(ChromiumOptions().set_argument("--start-maximized")) + reset_login_state(page) + log(f"登录页已打开:{page.url}") + + if MODE == "auto": + if not wait_ready(page): + log(f"等了 {PAGE_TIMEOUT} 秒表单仍未渲染,转手动模式") + else: + result = auto_login(page) + if result is not None: + log("抓包结束(浏览器保持打开)") + return result + + page.run_js(HOOK_JS) + log(f"手动模式:请在浏览器里登录,监听 {WAIT_SECONDS} 秒") + req, res = read_capture(page, timeout=WAIT_SECONDS) + if not req: + log("超时未捕获到登录请求") + return False + report(req, res) + log("抓包结束(浏览器保持打开)") + return True + + +if __name__ == "__main__": + sys.exit(0 if main() else 1) diff --git a/tests/tianque_probe/tianque_export.py b/tests/tianque_probe/tianque_export.py new file mode 100644 index 0000000..7074a6f --- /dev/null +++ b/tests/tianque_probe/tianque_export.py @@ -0,0 +1,224 @@ +"""天阙会生活商户平台:纯接口导出交易记录(不启浏览器,不依赖 DrissionPage)。 + +用法: + d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_export.py + +流程(与网页完全一致,报文来自真实抓包): + 1. 验证码 + AES 加密密码 → user/transForm/login 拿 token + 2. POST tranInfoPc/exportNew 提交导出任务(返回空 body,任务异步生成) + 3. POST download/downLoadList 轮询下载中心,等新增那条 fileSource=交易记录 且 exportStatus=1 + 4. 取记录里的 downloadUrl(OSS 预签名地址,直接 GET 即可,无需 token)落盘到 export/ + 5. POST download/read/ 标记已读,避免下载中心越堆越多 + +已知坑位: + - exportNew 参数照抄网页即可,timeType=01 表示自定义时间;响应是空 body(0 字节), + 不能按 JSON 解析,成功与否靠下载中心列表判断。 + - downloadUrl 带 expires/accessKey/signature,有时效,拿到要立刻下。 + - 下载中心是「按任务」的:先记下提交前的 id 集合,之后只认新增记录,避免下到历史文件。 + - 登录接口 body 需要 {header:{sysType:pc},data:{...}} 信封,业务接口是扁平 body。 +""" + +import json +import os +import sys +import time +from datetime import datetime, timedelta + +if hasattr(sys.stdout, "reconfigure"): + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + +import tianque_login_test as m # 复用登录原语:验证码、OCR、AES 加密、低安全 SSL 会话 + +# ==================== 配置区 ==================== +EXPORT_KIND = "trade" # trade=交易记录;后续扩展:settle=结算记录 +START_DAYS_AGO = 3 # 起始时间:N 天前的 00:00:00 +END_TODAY = True # True=结束时间取今天 23:59:59 +CUSTOM_START = "" # 也可直接写死 "2026-11-01 00:00:00",非空则优先 +CUSTOM_END = "" + +POLL_TIMEOUT = 180 # 等文件生成的最长秒数 +POLL_INTERVAL = 5 # 轮询间隔 +LIST_PAGE_SIZE = 10 +OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "export") +DO_MARK_READ = True # 下载后标记已读(与网页点击下载行为一致) +KEEP_RAW = False # True 时把 downLoadList 原始响应也落盘,便于排查 +# =============================================== + +BASE = "https://mch-web.tianquetech.com" +URL_EXPORT = "/management/easypay/api/tranInfoPc/exportNew" +URL_DOWNLOAD_LIST = "/management/easypay/api/download/downLoadList" +URL_MARK_READ = "/management/easypay/api/download/read/" +URL_POLLING = "/management/easypay/api/download/polling" + +# 下载中心里 fileSource 的取值,用来认自己刚触发的那条记录 +SOURCE_OF_KIND = { + "trade": "交易记录", + "settle": "结算记录", +} + +# 交易记录导出参数:照抄网页抓包(payTypePc/tranStsPc/payWayPcList 的 0 均表示「全部」) +TRADE_EXPORT_TEMPLATE = { + "payTypePc": "0", + "storeId": "", + "userId": "", + "tranStsPc": "0", + "payWayPcList": ["0"], + "trmNo": "", + "tradeSources": "", + "timeType": "01", +} + + +def log(msg): + print(f"[{datetime.now():%H:%M:%S}] {msg}", flush=True) + + +def api_post(session, path, payload=None): + """业务接口 POST。注意 exportNew 会返回空 body,不能无脑 r.json()。""" + r = session.post(BASE + path, json=payload if payload is not None else {}, timeout=30) + text = (r.text or "").strip() + if not text: + return {"_empty": True, "_status": r.status_code} + try: + return r.json() + except ValueError: + return {"_raw": text[:500], "_status": r.status_code} + + +def login(): + """验证码 + 密码登录,返回 (session, user)。复用 tianque_login_test 的原语。""" + if not (m.ACCOUNT and m.PASSWORD): + raise RuntimeError("请先在 tianque_login_test.py 顶部配置 ACCOUNT / PASSWORD") + + session = m.new_session() + for attempt in range(1, m.MAX_ATTEMPTS + 1): + log(f"登录第 {attempt}/{m.MAX_ATTEMPTS} 轮") + image_key, png = m.fetch_captcha(session) + code = m.ocr_image(png) + if not m.ocr_code_ok(code): + log(f"验证码识别结果不可用({code or '空'}),换图") + continue + + resp = m.do_login(session, m.ACCOUNT, m.PASSWORD, image_key, code) + if str(resp.get("code", "")) in m.CODE_OK: + users = (resp.get("data") or {}).get("users") or [] + if not users: + raise RuntimeError(f"登录成功但无用户信息:{json.dumps(resp, ensure_ascii=False)[:200]}") + user = users[0] + session.headers["token"] = user["token"] + log(f"登录成功:{user.get('merchantName') or user.get('userName')} mno={user.get('mno')}") + return session, user + + log(f"登录未通过:code={resp.get('code')} {resp.get('msg') or resp.get('message')}") + raise RuntimeError("登录失败(多为验证码识别率问题,重跑即可)") + + +def time_range(): + """导出时间范围。""" + if CUSTOM_START and CUSTOM_END: + return CUSTOM_START, CUSTOM_END + now = datetime.now() + start = (now - timedelta(days=START_DAYS_AGO)).strftime("%Y-%m-%d 00:00:00") + end = now.strftime("%Y-%m-%d 23:59:59") if END_TODAY else now.strftime("%Y-%m-%d %H:%M:%S") + return start, end + + +def download_list(session): + """下载中心列表(新→旧)。""" + resp = api_post(session, URL_DOWNLOAD_LIST, {"pageNum": 1, "pageSize": LIST_PAGE_SIZE}) + data = resp.get("data") or {} + return data.get("content") or [] + + +def submit_export(session, start, end): + """提交导出任务。""" + payload = dict(TRADE_EXPORT_TEMPLATE) + payload["startTime"] = start + payload["endTime"] = end + resp = api_post(session, URL_EXPORT, payload) + if resp.get("_empty"): + log(f"导出任务已提交(HTTP {resp.get('_status')},空响应属正常)") + else: + log(f"导出任务已提交:{json.dumps(resp, ensure_ascii=False)[:200]}") + return payload + + +def wait_new_record(session, before_ids, source_kw, timeout=POLL_TIMEOUT, interval=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 source_kw and source_kw not in (rec.get("fileSource") or ""): + continue + status = str(rec.get("exportStatus") or "") + desc = rec.get("exportStatusDesc") or status + if status == "1" 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}s 仍未等到导出完成,可调大 POLL_TIMEOUT 或去下载中心手动确认") + + +def download_file(session, rec): + """GET 预签名 OSS 地址直接下载,按平台给的文件名落盘。""" + os.makedirs(OUT_DIR, exist_ok=True) + name = rec.get("fileName") or f"tianque_{rec.get('id')}.xlsx" + path = os.path.join(OUT_DIR, name) + url = rec["downloadUrl"] + log("开始下载:" + url.split("?")[0]) + r = session.get(url, timeout=180) + r.raise_for_status() + with open(path, "wb") as f: + f.write(r.content) + log(f"已落盘:{path}({len(r.content)} 字节)") + return path + + +def mark_read(session, rec_id): + if not DO_MARK_READ: + return + resp = api_post(session, URL_MARK_READ + rec_id, {}) + log(f"已标记已读:{rec_id} -> {resp.get('data') or resp.get('message')}") + + +def main(): + start, end = time_range() + log(f"导出类型={EXPORT_KIND} 时间范围 {start} ~ {end}") + + session, _ = login() + + before_ids = {rec.get("id") for rec in download_list(session)} + log(f"提交前下载中心已有 {len(before_ids)} 条记录") + + submit_export(session, start, end) + + rec = wait_new_record(session, before_ids, SOURCE_OF_KIND.get(EXPORT_KIND, "")) + log(f"导出完成:{rec.get('fileName')} 创建时间={rec.get('createDate')}") + + path = download_file(session, rec) + mark_read(session, rec.get("id")) + + if KEEP_RAW: + raw_path = os.path.join(OUT_DIR, "downLoadList_raw.json") + with open(raw_path, "w", encoding="utf-8") as f: + json.dump(download_list(session), f, ensure_ascii=False, indent=2) + log(f"原始列表已存:{raw_path}") + + log(f"完成,文件:{path}") + return True + + +if __name__ == "__main__": + try: + sys.exit(0 if main() else 1) + except KeyboardInterrupt: + log("手动中断") + sys.exit(1) diff --git a/tests/tianque_probe/tianque_login_drission.py b/tests/tianque_probe/tianque_login_drission.py new file mode 100644 index 0000000..ff28e75 --- /dev/null +++ b/tests/tianque_probe/tianque_login_drission.py @@ -0,0 +1,213 @@ +"""天阙会生活商户平台:用 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") + +try: + from tianque_login_test import ACCOUNT as _ACC, PASSWORD as _PWD +except Exception: + _ACC, _PWD = "", "" + +_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) diff --git a/tests/tianque_probe/tianque_login_test.py b/tests/tianque_probe/tianque_login_test.py new file mode 100644 index 0000000..8ff6e94 --- /dev/null +++ b/tests/tianque_probe/tianque_login_test.py @@ -0,0 +1,293 @@ +"""天阙会生活商户平台(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 = "13629779871" # 663 账号或手机号 +PASSWORD = "Qq201201" # 登录密码(明文,脚本内部加密) +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) diff --git a/tests/tianque_probe/tianque_report_capture.py b/tests/tianque_probe/tianque_report_capture.py new file mode 100644 index 0000000..3eab9d0 --- /dev/null +++ b/tests/tianque_probe/tianque_report_capture.py @@ -0,0 +1,393 @@ +"""天阙会生活商户平台:用 DrissionPage 真浏览器登录后监听报表类接口,产出可复现的抓包样本。 + +用法: + d:\\work\\code\\37duAutomation\\.venv\\Scripts\\python.exe tests/tianque_probe/tianque_report_capture.py + + MODE = "auto" 登录后按 REPORT_ROUTES 逐页打开,自动触发报表/账单页的接口 + MODE = "manual" 登录后只开监听,你自己在页面里点报表菜单(最省事,推荐第一次用) + +产出(CAPTURE_DIR/<时间戳>/): + packets.jsonl 每一条接口调用一行:method / url / 参数 / 响应 code / 响应体(截断) + apis.json 按接口去重的清单:调用次数、示例参数、响应结构、成功码,用于后续写采集器 + files/ 二进制响应(导出 Excel/CSV/ZIP)原样落盘 + capture.log 控制台同步日志 + +抓包原理:page.listen.start() 全量监听(CDP Network),不依赖页面 JS hook, + RPA 常用的「查询列表 + 轮询 download/polling + download/downLoad/」两段式导出也能抓到。 + +已知坑位: + - 前端 POST body 可能是 {"header":{"sysType":"pc"},"data":{...}} 信封,也可能是扁平结构, + 抓到的 postData 是原始报文,写采集器时照抄即可。 + - 导出类接口多为两段:先提交任务拿 id,再 GET download/downLoad/ 取文件; + 第二段可能不返回可读 body,只记 URL。 + - 登录后前端用 sessionStorage.user 存 token,业务接口靠请求头 token + channel。 +""" + +import json +import os +import re +import sys +import time +from datetime import datetime + +if hasattr(sys.stdout, "reconfigure"): + try: + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + except Exception: + pass + +# ==================== 配置区 ==================== +MODE = "manual" # auto=自动逐页开;manual=只监听,你手点 +DO_LOGIN = True # False 时不自动登录(浏览器里已登录过就直接监听) +HEADLESS = False # 报表页多为图表,无头也可以,但 OCR 识别率略低 +IDLE_SECONDS = 90 # 多久没有「有新意的」接口调用就结束监听 +MAX_SECONDS = 1800 # 整轮监听总时长上限(秒) +PAGE_WAIT = 10 # auto 模式每页打开后等待渲染的秒数 +PAGE_LISTEN = 25 # auto 模式单页最多听多少秒 +MAX_BODY_CHARS = 20000 # 单条响应体落盘截断长度 +CAPTURE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "capture") + +# 只收这些接口(None=全收):默认只留业务接口,滤掉埋点/日志/静态资源 +KEEP_KEYWORDS = ("/management/easypay/api/", "/api/") +SKIP_KEYWORDS = ("/log", "/monitor", "/heartbeat", "/reportData", ".js", ".css", ".png", + ".jpg", ".svg", ".woff", ".ttf", "sentry", "collect") + +# 高频背景轮询:照常落盘,但不刷屏、也不重置空闲计时(否则永远等不到空闲) +NOISE_KEYWORDS = ("/download/polling", "/messageManage/queryUnReadMsgCount", "/creditSwitch/", + "/user/activityInfo", "/agentAd/getAdInfo") + +# auto 模式要走的报表页(来自前端 bundle 的 umi 路由表,可按需增删) +REPORT_ROUTES = [ + ("交易趋势", "/report/trend"), + ("交易排行", "/report/ranking"), + ("分店报表", "/report/branch"), + ("即时门店", "/report/jiShiStore"), + ("即时台账", "/report/jiShiLedgerAccount"), + ("明细账单", "/reconciliation/itemizedBill"), + ("汇总账单", "/reconciliation/totalBill"), + ("结算管理", "/financialData/settlementManage"), + ("账单管理", "/financialData/billManage"), + ("凭证管理", "/financialData/voucherManage"), +] + +# 从 bundle 里扒出来的报表相关接口,manual 模式打印出来给你当「点哪里」的对照表 +EXPECTED_APIS = [ + "/tranInfoPc/tradeReport", # 交易报表主查询 + "/tranInfoPc/tradeReportAmtSum", # 交易报表金额汇总 + "/tranInfoPc/queryTradeMark", # 交易报表打点/标签 + "/tranInfoPc/queryMnoTradeRank", # 商户交易排行 + "/tranInfoPc/tranListByParamNew", # 交易明细列表 + "/tranInfoPc/transactionTrad", # 交易笔数 + "/tranInfoPc/downloadTradeReport", # 交易报表导出 + "/tranInfoPc/downloadStatement", # 对账单下载 + "/tranInfoPc/downloadTradList", # 交易明细下载 + "/tranInfoPc/exportNew", # 通用导出 + "/tranInfo/queryTranSumByDate", # 按日交易汇总 + "/tranInfo/queryTradeSumByMonth", # 按月交易汇总 + "/tranInfo/exportBillList", # 交易列表导出 + "/sumbill/querySumBillInfoList", # 汇总账单列表 + "/sumbill/queryAccDetail", # 账单明细 + "/sumbill/exportSumBillInfoList", # 账单导出 + "/settleInfo/querySettleRecord", # 结算记录 + "/settleInfo/exportSettleRecord", # 结算记录导出 + "/dwQuery/business/businessTradeSum", # 业务交易汇总 + "/billDownload/summaryBill", # 账单打包下载 + "/download/downLoadList", # 下载中心列表(两段式导出的第二段) +] +# =============================================== + +BASE = "https://mch-web.tianquetech.com" +LOGIN_URL = BASE + "/login" + + +def log(msg): + line = f"[{datetime.now():%H:%M:%S}] {msg}" + print(line, flush=True) + return line + + +def keep_packet(url): + low = (url or "").lower() + if KEEP_KEYWORDS and not any(k.lower() in low for k in KEEP_KEYWORDS): + return False + return not any(k.lower() in low for k in SKIP_KEYWORDS) + + +def short_path(url): + """去掉域名与查询串,方便聚合统计。""" + path = url.split("://", 1)[-1] + path = path[path.find("/"):] if "/" in path else path + return path.split("?", 1)[0] + + +def to_payload(data): + """DrissionPage 的 postData 是 JSON 时会直接给 dict,这里统一回字符串。""" + if not data: + return "" + if isinstance(data, (dict, list)): + return json.dumps(data, ensure_ascii=False) + return str(data) + + +def resp_code(obj): + """业务返回码:新接口用 code,老接口用 errorType/message。""" + if not isinstance(obj, dict): + return "", "" + code = obj.get("code") + msg = obj.get("msg") or obj.get("message") or "" + if code is None and obj.get("errorType"): + code, msg = obj.get("errorType"), obj.get("message") or "" + return ("" if code is None else str(code)), str(msg or "") + + +def data_keys(obj): + """粗略描述响应结构,用于判断该接口能不能直接复用。""" + if not isinstance(obj, dict): + return "" + data = obj.get("data") + if isinstance(data, dict): + keys = list(data.keys())[:12] + for k, v in data.items(): + if isinstance(v, list) and v and isinstance(v[0], dict): + return f"data{{{','.join(keys)}}} list[{k}]={list(v[0].keys())[:12]}" + return f"data{{{','.join(keys)}}}" + if isinstance(data, list): + return f"data[]={list(data[0].keys())[:12] if data and isinstance(data[0], dict) else type(data).__name__}" + return f"data={type(data).__name__}" + + +def guess_ext(content_type, url): + ct = (content_type or "").lower() + low = (url or "").lower() + if "spreadsheet" in ct or "excel" in ct or low.endswith((".xls", ".xlsx")): + return ".xlsx" + if "csv" in ct: + return ".csv" + if "zip" in ct: + return ".zip" + if "pdf" in ct: + return ".pdf" + if "octet-stream" in ct: + return ".bin" + return ".bin" + + +class Capture(object): + def __init__(self, root): + self.root = root + os.makedirs(root, exist_ok=True) + self.file_dir = os.path.join(root, "files") + os.makedirs(self.file_dir, exist_ok=True) + self.jsonl = open(os.path.join(root, "packets.jsonl"), "w", encoding="utf-8") + self.logf = open(os.path.join(root, "capture.log"), "w", encoding="utf-8") + self.apis = {} + self.seq = 0 + + def write_log(self, msg): + line = log(msg) + self.logf.write(line + "\n") + self.logf.flush() + + def save_binary(self, path, data): + self.seq += 1 + name = re.sub(r"[^0-9A-Za-z._-]", "_", path.strip("/").replace("/", "_"))[:80] + ext = guess_ext("", path) + fn = f"{self.seq:03d}_{name}{ext}" + with open(os.path.join(self.file_dir, fn), "wb") as f: + f.write(data) + return fn + + def handle(self, pkt, route_label=""): + url = pkt.url or "" + if not keep_packet(url): + return + method = (pkt.method or "GET").upper() + path = short_path(url) + try: + body = pkt.response.body + except Exception as exc: # 下载/重定向类响应可能取不到 body + body = b"" + err = str(exc)[:120] + else: + err = "" + + content_type = "" + try: + content_type = (pkt.response.headers or {}).get("content-type", "") + except Exception: + pass + try: + status = pkt.response.status + except Exception: + status = "" + + # DrissionPage 的 response.body 已经自动解析过:JSON 给 dict/list,二进制给 bytes,其它给 str + parsed, text, binary = None, "", "" + if isinstance(body, (dict, list)): + parsed = body + text = json.dumps(body, ensure_ascii=False) + elif isinstance(body, bytes): + binary = self.save_binary(path, body) if body else "" + elif body: + text = str(body) + if text.lstrip()[:1] in ("{", "["): + try: + parsed = json.loads(text) + except ValueError: + parsed = None + + code, msg = resp_code(parsed) + size = len(body) if isinstance(body, bytes) else len(text.encode("utf-8")) + + rec = { + "ts": datetime.now().isoformat(timespec="seconds"), + "route": route_label, + "method": method, + "url": url, + "path": path, + "query": dict(pkt.request.params or {}) if hasattr(pkt.request, "params") else {}, + "postData": to_payload(pkt.request.postData)[:MAX_BODY_CHARS], + "status": status, + "contentType": content_type, + "code": code, + "msg": msg, + "size": size, + "dataKeys": data_keys(parsed), + "binaryFile": binary, + "body": "" if binary else text[:MAX_BODY_CHARS], + } + if err: + rec["bodyError"] = err + self.jsonl.write(json.dumps(rec, ensure_ascii=False) + "\n") + self.jsonl.flush() + + item = self.apis.setdefault(path, { + "path": path, + "methods": [], + "count": 0, + "samplePostData": "", + "lastCode": "", + "lastMsg": "", + "dataKeys": "", + "contentType": "", + }) + item["count"] += 1 + if method not in item["methods"]: + item["methods"].append(method) + if rec["postData"] and not item["samplePostData"]: + item["samplePostData"] = rec["postData"] + item["lastCode"], item["lastMsg"] = code, msg + item["dataKeys"] = rec["dataKeys"] or item["dataKeys"] + item["contentType"] = content_type or item["contentType"] + + noise = any(k.lower() in url.lower() for k in NOISE_KEYWORDS) + if not noise: + self.write_log(f"{method} {path} code={code or ('ok' if parsed is not None else '-')}" + f" {msg[:40]} {rec['size']}B" + (f" -> {binary}" if binary else "")) + return not noise + + def summary(self): + out = os.path.join(self.root, "apis.json") + with open(out, "w", encoding="utf-8") as f: + json.dump({"capturedAt": datetime.now().isoformat(timespec="seconds"), + "apis": sorted(self.apis.values(), key=lambda x: (-x["count"], x["path"]))}, + f, ensure_ascii=False, indent=2) + return out + + def close(self): + self.jsonl.close() + self.logf.close() + + +def listen(page, cap, route_label, idle=IDLE_SECONDS, total=MAX_SECONDS): + """监听直到接口空闲 idle 秒、或本轮总时长超 total;每来一个包就落盘。 + 注意:页面有 download/polling 之类的背景轮询会一直喂包,空闲判定实际靠 total 兜底。""" + start = time.time() + for pkt in page.listen.steps(timeout=idle): + if isinstance(pkt, list): + for p in pkt: + cap.handle(p, route_label) + else: + cap.handle(pkt, route_label) + if time.time() - start > total: + cap.write_log(f"达到本轮时长上限 {total}s,结束本轮监听") + return True + return False + + +def main(): + from DrissionPage import ChromiumOptions, ChromiumPage + + import tianque_login_drission as dl # 复用同目录的浏览器登录实现(含验证码 OCR) + + if DO_LOGIN and not (dl.ACCOUNT and dl.PASSWORD): + log("请先在 tianque_login_test.py 顶部配置 ACCOUNT / PASSWORD") + return False + + stamp = f"{datetime.now():%Y%m%d-%H%M%S}" + cap = Capture(os.path.join(CAPTURE_DIR, stamp)) + cap.write_log(f"抓包目录:{cap.root} 模式:{MODE}") + + opts = ChromiumOptions().set_argument("--start-maximized") + if HEADLESS: + opts.headless(True) + page = ChromiumPage(opts) + + if DO_LOGIN: + page.get(LOGIN_URL) + time.sleep(2) + dl.js(page, "return sessionStorage.clear()") + page.refresh() + time.sleep(2) + if not dl.wait_ready(page): + cap.write_log("登录页 40 秒未渲染完成,退出") + return False + user = dl.browser_login(page) + if not user: + cap.write_log("浏览器登录失败,退出") + return False + cap.write_log(f"登录成功:mno={user.get('mno')} 商户={user.get('merchantName') or user.get('userName')}") + else: + page.get(LOGIN_URL) + time.sleep(2) + + page.listen.start() # 全量监听,必须在触发页面前启动 + cap.write_log("监听已启动") + + try: + if MODE == "auto": + for label, route in REPORT_ROUTES: + cap.write_log(f"打开报表页:{label} {route}") + page.get(BASE + route) + time.sleep(PAGE_WAIT) + listen(page, cap, label, idle=8, total=PAGE_LISTEN) # 单页只收一轮,避免长页面互相拖住 + cap.write_log("auto 模式走完,继续监听最后停留页的懒加载请求") + listen(page, cap, "tail", idle=IDLE_SECONDS, total=300) + else: + cap.write_log("manual 模式:请在浏览器里点开报表/账单菜单,脚本会实时记录接口") + cap.write_log("可对照这些接口找对应页面:") + for api in EXPECTED_APIS: + cap.write_log(f" {api}") + listen(page, cap, "manual") + except KeyboardInterrupt: + cap.write_log("手动中断(Ctrl+C),开始汇总已抓到的接口") + + page.listen.stop() + out = cap.summary() + cap.write_log(f"接口清单已写:{out}") + + if cap.apis: + cap.write_log(f"本次共捕获 {len(cap.apis)} 个接口:") + for item in sorted(cap.apis.values(), key=lambda x: (-x["count"], x["path"])): + cap.write_log(f" {item['count']:>3}x {item['path']} code={item['lastCode'] or '-'}" + f" {item['dataKeys'][:80]}") + else: + cap.write_log("没捕获到接口:确认页面真的发了请求,或放宽 KEEP_KEYWORDS") + + cap.close() + log("浏览器保持打开,可直接对照页面核对") + return True + + +if __name__ == "__main__": + sys.exit(0 if main() else 1)