feat: 新增微盟数据导出和门店出勤积分更新插件

This commit is contained in:
2026-10-20 18:29:04 +08:00
parent af4055e08b
commit a4709aa79b
54 changed files with 9591 additions and 2 deletions
@@ -190,6 +190,11 @@ def build_kaoqin_bytes(rows):
# ================== 上传 ==================
# 服务端对"重复/无内容可删"的良性响应关键词:目标状态已达成,不算失败
# (例:积分导入遇已存在记录返回"不能重复添加";积分删除遇无记录返回"未生成出勤积分")
_BENIGN_MSGS = ('不能重复添加', '未生成出勤积分', '已存在')
def _upload(session, url, file_bytes, filename):
import requests
resp = session.post(url, files={'file': (filename, file_bytes, _FILE_MIME)},
@@ -201,7 +206,11 @@ def _upload(session, url, file_bytes, filename):
except Exception:
return {'success': False, 'message': '响应非 JSON'}
ok = data.get('status') is True or data.get('code') == 'S0'
return {'success': bool(ok), 'message': data.get('message') or ('' if ok else '导入失败')}
msg = data.get('message') or ''
if not ok and any(k in msg for k in _BENIGN_MSGS):
# 良性:记录已存在/无需删除,目标状态已达成 → 视为成功(保留原始提示便于核对)
return {'success': True, 'message': f'部分已存在/无需处理(目标状态已达成):{msg[:200]}'}
return {'success': bool(ok), 'message': msg or ('' if ok else '导入失败')}
def _push(session, url, file_bytes, label, push):
@@ -0,0 +1,607 @@
# -*- coding: utf-8 -*-
"""
@FileName: wm_export.py
@Description: XQ0047 微盟数据导出 —— 订单数据 API 导出主流程。
策略(避免导出超限 + 风控 + 减少等待):
1) 先用 queryOrderList 探测「上月1日0:00~此刻」的订单总数 totalCount;
2) 按 ceil(total / SEG_TARGET) 向上取整等分时间区间(最小化导出次数),
再用新时段逐段探测条数校验:满足阈值则定稿,超限则按
ceil(cnt / SEG_TARGET) 继续等分,直到每段都不超限;
3) 批量创建 exportOrder 导出任务(异步:不逐段等待);
4) 统一轮询 download/list 一次取回全部任务状态,全部完成后再逐段
下载 mediaUrl(zip) → 解压出 Excel;
5) 各段 Excel 的全部 sheet 数据合并到同一个工作表,输出单个最终 xlsx
(HEADER_ROWS 行表头,其余行追加)。
请求间加入随机限流 sleep,降低风控触发风险。
最终输出:一个 xlsx 文件(桌面/微盟订单导出/微盟订单_YYYYMMDD_HHMMSS.xlsx)。
登录态:由同目录 wm_login.py(或共享 share/weimob_login.py)写入
%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_cookies.json,
本脚本只读不补登;缺失/失效时提示先运行登录脚本。
运行方式:直接运行本文件(参数全部内置,无需命令行传参)。
python wm_export.py
配置说明(改下面配置块即可):
SEG_TARGET 单段目标订单数(接口 Excel 上限 5w,此处留明细行余量)
INTERVAL 请求间限流区间(秒)
OUTPUT_DIR 输出目录,None 时默认桌面/微盟订单导出;可用环境变量 wm_export_dir 覆盖
依赖:requests openpyxl(+ wm_login 用 DrissionPage)
"""
import os
import json
import time
import math
import random
import shutil
import zipfile
import ctypes
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone, timedelta
from pathlib import Path
import requests
from openpyxl import Workbook, load_workbook
# ================== 商家配置(金色印象,其他账号改这里) ==================
BOS_ID = '4022571268153'
MERCHANT_ID = 2000527625153
VID = 6017432629153
PRODUCT_ID = 145
PRODUCT_VERSION_ID = '12010'
PRODUCT_INSTANCE_ID = 22515052153
TCODE = 'weimob'
ORDER_LIST_URL = ("https://master.weimob.com/bos/products/ecOrder/4022571268153/"
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist")
QUERY_LIST_URL = "https://master.weimob.com/api3/mall/mgr/order/queryOrderList"
EXPORT_URL = "https://master.weimob.com/api3/mall/mgr/order/exportOrder"
DOWNLOAD_LIST_URL = "https://master.weimob.com/api3/merchant/backstage/service/download/list"
# ================== 输出与切分配置 ==================
OUTPUT_DIR = None # None → 桌面/微盟订单导出;可用环境变量 wm_export_dir 覆盖
FILE_PREFIX = '微盟订单' # 最终文件名前缀
SEG_TARGET = 45000 # 单段目标订单数(接口 Excel 上限 5w,留约 10% 明细行余量)
MIN_SPLIT_MS = 3600 * 1000 # 最小细分粒度(1 小时):到该粒度仍超限则直接导出尝试
INTERVAL_MIN = 3 # 请求间限流下限(秒)
INTERVAL_MAX = 5 # 请求间限流上限(秒,随机化模拟人工节奏,降低风控触发)
# ================== 运行参数(项目规范:全局重试3次) ==================
RETRY_MAX = 3 # 单段 exportOrder 最大重试次数
POLL_MAX = 180 # 统一轮询 download/list 最大次数(180×10s ≈ 30 分钟,大数据量生成较慢)
POLL_INTERVAL = 10 # 轮询间隔(秒)
DOWNLOAD_WORKERS = 4 # 并发下载线程数(CDN 单连接约 100K/s,多段并行抢带宽)
TIMEOUT = 25 # 接口请求超时(秒)
DOWNLOAD_TIMEOUT = 180 # 文件下载超时(秒,大文件 CDN 限速较慢)
HEADER_ROWS = 1 # 导出 xlsx 表头行数(合并时跳过,后续追加数据)
# ================== 共享路径 ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
COOKIE_FILE = os.path.join(_APP_DATA_DIR, '.sessions', 'weimob_cookies.json')
# ================== 工具函数 ==================
def _get_desktop():
"""获取真实桌面路径,适配 OneDrive 等重定向的不同电脑。"""
try:
from ctypes import wintypes
guid = wintypes.GUID(
data1=0xB4BFCC3A, data2=0xDB2C, data3=0x424C,
data4=(0xB0, 0x29, 0x7F, 0xE9, 0x9A, 0x87, 0xC6, 0x41))
func = ctypes.windll.shell32.SHGetKnownFolderPath
func.argtypes = [wintypes.GUID, wintypes.DWORD, wintypes.HANDLE,
ctypes.POINTER(ctypes.c_wchar_p)]
ptr = ctypes.c_wchar_p()
func(ctypes.byref(guid), 0, None, ctypes.byref(ptr))
return ptr.value
except Exception:
return str(Path.home() / 'Desktop')
def _get_output_dir():
"""输出目录:环境变量 wm_export_dir 优先,否则桌面/微盟订单导出。"""
env = os.getenv('wm_export_dir', '').strip()
if env:
return env
return os.path.join(_get_desktop(), '微盟订单导出')
def _sleep_interval():
"""请求间/段间限流:随机 3~5 秒,模拟人工节奏,降低风控触发概率。"""
time.sleep(random.uniform(INTERVAL_MIN, INTERVAL_MAX))
def _time_range():
"""时间范围:上月1日 00:00:00(北京时间)~ 此刻。返回毫秒时间戳 (start, end)。"""
cn_tz = timezone(timedelta(hours=8))
now = datetime.now(cn_tz)
if now.month == 1:
start_dt = datetime(now.year - 1, 12, 1, 0, 0, 0, tzinfo=cn_tz)
else:
start_dt = datetime(now.year, now.month - 1, 1, 0, 0, 0, tzinfo=cn_tz)
return int(start_dt.timestamp() * 1000), int(now.timestamp() * 1000)
def _load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
def _build_session():
"""读登录态构建 requests.Session,携带微盟鉴权票据。
微盟 api3 接口除 cookie 外,必须带以下请求头(否则 errcode=1041 fail auth):
Authorization: Bearer <saasAuthData cookie 值>
Apiclient: saas-pc
weimob-bosId: <bosId>
"""
cookies = _load_cookies()
if not cookies:
return None
token = next((c["value"] for c in cookies
if c.get("name") == "saasAuthData" and c.get("value")), "")
session = requests.Session()
session.headers.update({
"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",
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*",
"Origin": "https://master.weimob.com",
"Referer": ORDER_LIST_URL,
"Authorization": f"Bearer {token}",
"Apiclient": "saas-pc",
"weimob-bosId": BOS_ID,
"x-page-route": "/bos/products/ecOrder/4022571268153/"
"4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist",
"x-aggs-route": "products/ecOrder/4sidacmmkX1q2pyt1eX4sinvqste/order/order/orderlist",
})
for c in cookies:
domain = c.get("domain") or ""
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
return session
# ================== 请求体模板 ==================
def _build_basic_info():
return {
"tcode": TCODE, "merchantId": MERCHANT_ID, "bosId": int(BOS_ID),
"vid": VID, "vidType": 2, "vidTypeName": "品牌", "vidTypes": [2],
"parentVid": 0, "vidPath": f"-{VID}-", "vidDeleted": False,
"vidStatus": 1, "wxOnlineStatus": 0, "onlineStoreStatus": 0,
"onlineStoreAbilityType": 1, "onlineStoreAbilityRelationVid": None,
"activeStatus": True, "vidRelation": True, "isRootVid": True,
"productId": PRODUCT_ID, "productVersionId": PRODUCT_VERSION_ID,
"productInstanceId": PRODUCT_INSTANCE_ID,
"statusCode": "in_use", "vidName": "金色印象商城", "productName": "商城",
"productVersionName": "商城连锁-PE", "overPrivilegeTime": None,
"rootVid": VID, "rootVidType": 2, "packCode": None,
}
def _query_param(start_ms, end_ms):
"""与 exportOrder 完全一致的查询条件(orderTypes 等保持一致,保证条数探测准确)。"""
return {
"orderStatuses": [], "urgePayTimeType": -1, "needBuyerHeadUrl": True,
"bizSourceTypes": [-1], "searchType": 4, "keyword": "",
"queryTime": {"type": 0, "startTime": start_ms, "endTime": end_ms},
"processVids": [], "vids": [], "orderAssign": 0, "flagRanks": [],
"channelTypes": [], "orderSources": [-1], "deliveryMode": [-1],
"orderTypes": [1, 98, 96, 11, 12], "goodsSellModes": [], "subGoodsTypes": [],
"paymentTypes": [], "deliveryTypes": [], "activities": [], "labelTypes": [],
"warehouseIds": [], "queryAmount": {"type": 1, "minAmount": "", "maxAmount": ""},
"searchScene": 0,
}
def _build_export_body(start_ms, end_ms):
"""exportOrder 请求体(exportFieldCodeList 全 null=默认导出列;仅 queryTime 动态)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"exportFieldCodeList": [None] * 142,
"exportFormat": 1,
"exportType": 1,
"orderMenuCode": 5,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_query_body(start_ms, end_ms):
"""queryOrderList 请求体(分页,用于探测区间条数)。"""
return {
"basicInfo": _build_basic_info(),
"operationSource": 1,
"pageNum": 1,
"pageSize": 1,
"queryParameter": _query_param(start_ms, end_ms),
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_dl_body(page_size=20):
"""download/list 请求体(分页取最近导出记录,page_size 按本轮段数放大)。"""
return {
"bosId": BOS_ID,
"pageSize": page_size,
"basicInfo": {
"merchantId": MERCHANT_ID, "bosId": int(BOS_ID), "vid": VID,
"vidType": 2, "vidTypes": [2], "productId": PRODUCT_ID,
"productVersionId": PRODUCT_VERSION_ID, "productInstanceId": PRODUCT_INSTANCE_ID,
"tcode": TCODE,
},
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
# ================== 区间探测与切分 ==================
def query_count(session, start_ms, end_ms):
"""调用 queryOrderList 返回区间订单总数(失败返回 -1)。"""
try:
resp = session.post(QUERY_LIST_URL, json=_build_query_body(start_ms, end_ms), timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0":
return int((data.get("data") or {}).get("totalCount") or 0)
print(f"queryOrderList 异常:{str(data)[:200]}")
except Exception as e:
print(f"queryOrderList 请求异常:{e}")
return -1
def _split_equal(start_ms, end_ms, n):
"""把 [start_ms, end_ms] 等分为 n 段(毫秒),返回不重叠、连续覆盖的区间列表。"""
n = max(1, n)
span = end_ms - start_ms + 1
step = -(-span // n) # 向上取整,保证 n 段覆盖整区间
segments = []
cur = start_ms
for _ in range(n):
if cur + step - 1 >= end_ms:
segments.append((cur, end_ms))
break
segments.append((cur, cur + step - 1))
cur += step
return segments
def _fmt_range(a, b):
"""区间可读标签(北京时间)。"""
return (f"[{datetime.fromtimestamp(a / 1000):%m-%d %H:%M} ~ "
f"{datetime.fromtimestamp(b / 1000):%m-%d %H:%M}]")
def plan_segments(session, start_ms, end_ms):
"""按条数等分 + 逐段校验细分,最小化导出次数。
1) 探测总条数 total → 段数 n = ceil(total / SEG_TARGET),一次性等分;
2) 再用新时段逐段探测条数:<= SEG_TARGET 即定稿(不再拆);
3) 仍超限则按 ceil(cnt / SEG_TARGET) 继续等分,直到全部满足。
返回 [(seg_start_ms, seg_end_ms), ...](按时间升序)。
"""
total = query_count(session, start_ms, end_ms)
if total < 0:
return []
print(f"总区间订单数:{total}")
if total == 0:
return []
if total <= SEG_TARGET:
return [(start_ms, end_ms)]
n = math.ceil(total / SEG_TARGET)
queue = _split_equal(start_ms, end_ms, n)
print(f"按 {SEG_TARGET} 单/段向上取整,先等分为 {n} 段,逐段探测校验:")
segments = []
probe_limit = 200 # 防御:探测次数上限,避免异常数据导致无限细分
probes = 0
while queue:
probes += 1
if probes > probe_limit:
print(" 警告:细分探测次数超限,中止")
return []
a, b = queue.pop(0)
_sleep_interval()
cnt = query_count(session, a, b)
if cnt < 0:
return []
label = _fmt_range(a, b)
if cnt <= SEG_TARGET:
segments.append((a, b))
print(f" ✓ {label} 订单数={cnt} → 定稿")
continue
if b - a < MIN_SPLIT_MS:
print(f" ! {label} 订单数={cnt} 超限但已到最小粒度,直接导出尝试")
segments.append((a, b))
continue
k = math.ceil(cnt / SEG_TARGET)
print(f" ↻ {label} 订单数={cnt} 超限 → 再等分 {k} 段")
queue[0:0] = _split_equal(a, b, k) # 保持时间顺序继续校验
segments.sort()
return segments
# ================== 导出流程 ==================
def create_export_task(session, start_ms, end_ms):
"""调用 exportOrder 创建导出任务,成功返回触发时间戳(用于匹配任务)。"""
body = _build_export_body(start_ms, end_ms)
trigger_ms = int(time.time() * 1000) # 调用前记录:任务创建时间必然在此之后,匹配更稳
for attempt in range(1, RETRY_MAX + 1):
try:
resp = session.post(EXPORT_URL, json=body, timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") == "0" and (data.get("data") or {}).get("success"):
return trigger_ms
print(f"exportOrder 第{attempt}次失败:{str(data)[:200]}")
except Exception as e:
print(f"exportOrder 第{attempt}次异常:{e}")
if attempt < RETRY_MAX:
_sleep_interval()
return None
def _parse_create_ms(item):
"""解析导出记录的 createTime 为毫秒时间戳;失败返回 None。"""
try:
dt = datetime.fromisoformat((item.get("createTime") or "").replace("Z", "+00:00"))
return dt.timestamp() * 1000
except Exception:
return None
def _task_in_window(item, lo_ms, hi_ms):
"""判断导出记录是否属于某段任务:状态成功 + 订单导出 + createTime 落在时间窗内。"""
if item.get("status") != 1 or "订单导出" not in (item.get("fileName") or ""):
return False
ct = _parse_create_ms(item)
if ct is None:
return False
return ct >= lo_ms and (hi_ms is None or ct < hi_ms)
def _fetch_download_items(session, page_size):
"""取最近导出记录列表;失败返回 None。"""
try:
resp = session.post(DOWNLOAD_LIST_URL, json=_build_dl_body(page_size), timeout=TIMEOUT)
data = resp.json() if resp.status_code == 200 else {}
if data.get("errcode") != "0":
print(f"download/list 返回异常:{str(data)[:200]}")
return None
return (data.get("data") or {}).get("items") or []
except Exception as e:
print(f"download/list 异常:{e}")
return None
def create_export_tasks(session, segments):
"""批量创建导出任务:串行调 exportOrder(随机限流),不逐段等待生成。
返回 [{'start','end','trigger_ms'}];任一段创建失败返回 None。
"""
tasks = []
for i, (a, b) in enumerate(segments, 1):
print(f" 创建任务 {i}/{len(segments)}:{_fmt_range(a, b)}")
trigger_ms = create_export_task(session, a, b)
if trigger_ms is None:
return None
tasks.append({"start": a, "end": b, "trigger_ms": trigger_ms})
if i < len(segments):
_sleep_interval()
return tasks
def wait_all_done(session, tasks):
"""统一轮询 download/list,一次请求取回全部任务状态(异步并行等待)。
任务归属:第 i 段任务 = createTime ∈ [trigger_i, trigger_{i+1}),末段上界为 None;
下界留 1 秒容差,兼容 createTime 秒级截断。
返回与 tasks 顺序一致的完成记录列表;超时返回 None(打印最近记录便于诊断)。
"""
windows = []
for i, t in enumerate(tasks):
lo = t["trigger_ms"] - 1000
hi = tasks[i + 1]["trigger_ms"] - 1000 if i + 1 < len(tasks) else None
windows.append((lo, hi))
page_size = max(20, len(tasks) + 10)
done = {}
used = set()
pending = list(range(len(tasks)))
for round_no in range(1, POLL_MAX + 1):
time.sleep(POLL_INTERVAL if round_no > 1 else 3)
items = _fetch_download_items(session, page_size)
if items is None:
continue
for idx in list(pending):
lo, hi = windows[idx]
cand = [it for it in items
if it.get("id") not in used and _task_in_window(it, lo, hi)]
if not cand:
continue
cand.sort(key=lambda it: it.get("createTime") or "")
done[idx] = cand[0]
used.add(cand[0].get("id"))
pending.remove(idx)
print(f" 任务 {idx + 1}/{len(tasks)} 已生成:{cand[0].get('fileName')}")
if not pending:
return [done[i] for i in range(len(tasks))]
print(f" 轮询 {round_no}/{POLL_MAX}:已完成 {len(done)}/{len(tasks)}")
print(" 等待超时,最近导出记录:")
for it in (_fetch_download_items(session, page_size) or [])[:10]:
print(f" id={it.get('id')} status={it.get('status')} "
f"fileName={it.get('fileName')} createTime={it.get('createTime')}")
return None
def _fix_zip_name(name):
"""修复 zip 内 GBK 编码的中文文件名乱码。"""
try:
return name.encode('cp437').decode('gbk')
except Exception:
return name
def download_and_extract(item, out_dir):
"""(并发线程内执行)用独立会话流式下载 mediaUrl(zip) → 解压出 Excel,返回 xlsx 路径。"""
media_url = item.get("mediaUrl") or ""
if not media_url:
raise RuntimeError("导出记录缺少 mediaUrl")
session = _build_session() # 独立会话:requests.Session 非线程安全,且并发下载需独立连接
if session is None:
raise RuntimeError("未找到微盟登录态")
zip_path = os.path.join(out_dir, f"导出任务_{item.get('id')}.zip")
t0 = time.time()
with session.get(media_url, timeout=DOWNLOAD_TIMEOUT, stream=True) as resp:
if resp.status_code != 200:
raise RuntimeError(f"下载失败(status={resp.status_code})")
total = 0
with open(zip_path, "wb") as f:
for chunk in resp.iter_content(1024 * 1024):
if chunk:
f.write(chunk)
total += len(chunk)
cost = max(time.time() - t0, 0.001)
print(f" 已下载:{total} 字节,耗时 {cost:.1f}s({total / cost / 1024:.0f} KB/s)")
excel_in_zip = None
with zipfile.ZipFile(zip_path) as zf:
for info in zf.infolist():
if info.is_dir():
continue
name = _fix_zip_name(info.filename)
if name.lower().endswith((".xlsx", ".xls")):
excel_in_zip = (info.filename, name)
break
if excel_in_zip is None:
raise RuntimeError("压缩包内未找到 Excel 文件")
src_in_zip, src_name = excel_in_zip
tmp = os.path.join(out_dir, src_name)
with zf.open(src_in_zip) as f_in, open(tmp, "wb") as f_out:
shutil.copyfileobj(f_in, f_out)
os.remove(zip_path)
return tmp
def merge_excels(paths, out_dir):
"""把各段 xlsx 的全部 sheet 数据合并到同一个工作表。
取第一个 sheet 的 HEADER_ROWS 行表头,其余所有 sheet 仅追加数据行;
输出单 sheet 的最终文件(write_only 流式写入,8w+ 行也不占大内存)。
"""
if not paths:
return None
final_name = f"{FILE_PREFIX}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.xlsx"
final_path = os.path.join(out_dir, final_name)
out_wb = Workbook(write_only=True)
out_ws = out_wb.create_sheet("订单数据")
header_written = False
total_rows = 0
for p in paths:
src = load_workbook(p, read_only=True)
for ws in src.worksheets:
# 微盟导出的 xlsx 缺 <dimension>,read_only 模式会误判为 A1:A1,必须重置尺寸
ws.reset_dimensions()
rows = ws.iter_rows(values_only=True)
if not header_written:
for _ in range(HEADER_ROWS):
row = next(rows, None)
if row is not None:
out_ws.append(list(row))
header_written = True
else:
for _ in range(HEADER_ROWS): # 跳过其余 sheet 表头
next(rows, None)
for row in rows:
if all(v is None for v in row): # 跳过空行
continue
out_ws.append(list(row))
total_rows += 1
src.close()
out_wb.save(final_path)
print(f"合并完成:单 sheet 共 {total_rows} 行数据(含表头 {total_rows + HEADER_ROWS} 行)")
# 保留各段源文件:合并异常时可人工打开核对,或供二次使用
print("各段源文件已保留:")
for p in paths:
print(f" {p}")
return final_path
# ================== 主流程 ==================
def main():
"""
微盟订单导出主流程:
探测条数 → 按条数等分并逐段校验 → 批量建导出任务 → 统一轮询 → 下载解压 → 合并一个 Excel。
返回 dict {success, excel_path, message}
"""
start_ms, end_ms = _time_range()
print(f"导出时间范围:上月1日 0:00 ~ 此刻({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})")
session = _build_session()
if session is None:
return {"success": False, "excel_path": "",
"message": "未找到微盟登录态(weimob_cookies.json)。请先运行 wm_login.py 完成登录。"}
out_dir = _get_output_dir()
os.makedirs(out_dir, exist_ok=True)
segments = plan_segments(session, start_ms, end_ms)
if not segments:
return {"success": False, "excel_path": "",
"message": "区间探测失败或无订单(请检查登录态是否有效,或稍后重试)"}
print(f"最终导出段数:{len(segments)}")
# 阶段 1:批量创建导出任务(异步,不逐段等待)
print("\n批量创建导出任务:")
tasks = create_export_tasks(session, segments)
if tasks is None:
return {"success": False, "excel_path": "",
"message": "创建导出任务失败(请检查登录态或风控状态后重试)"}
# 阶段 2:统一轮询全部任务(一次请求拿全部状态,等最慢的一段)
print("\n等待全部导出任务生成:")
items = wait_all_done(session, tasks)
if items is None:
return {"success": False, "excel_path": "",
"message": "等待导出任务完成超时(已创建任务可能仍在生成,稍后可重试)"}
# 阶段 3:并发下载各段 zip(独立连接,避免单连接 CDN 限速串行等待)→ 解压 Excel
excel_paths = [None] * len(segments)
workers = min(DOWNLOAD_WORKERS, len(items))
print(f"\n并发下载 {len(items)} 段({workers} 线程):")
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = {pool.submit(download_and_extract, it, out_dir): i
for i, it in enumerate(items)}
for fut in as_completed(futures):
i = futures[fut]
try:
excel_paths[i] = fut.result()
print(f" [段 {i + 1}/{len(segments)}] 完成:{excel_paths[i]}")
except Exception as e:
return {"success": False, "excel_path": "",
"message": f"第 {i + 1} 段下载/解压失败:{e}"}
if any(p is None for p in excel_paths):
return {"success": False, "excel_path": "", "message": "部分段下载结果缺失"}
final_path = merge_excels(excel_paths, out_dir)
if final_path is None:
return {"success": False, "excel_path": "", "message": "合并结果为空"}
return {"success": True, "excel_path": final_path,
"message": f"导出成功({len(segments)} 段合并),最终文件:{final_path}"}
if __name__ == "__main__":
result = main()
print("\n最终结果:", result)
@@ -0,0 +1,363 @@
# -*- coding: utf-8 -*-
"""
@FileName: wm_login.py
@Description: 微盟(Weimob)登录(XQ0047 微盟数据导出 需求自包含版)。
登录微盟商家后台,保存 Cookies 与 localStorage 票据,
供同目录 wm_export.py 及后续微盟相关脚本复用登录态。
登录说明:
- 微盟登录页默认打开是「验证码登录」(codeLogin.html),脚本会自动切换到「密码登录」tab;
- 账号密码只从共享 .env 读取(wm_login_username / wm_login_password),不内置明文;
- 点击登录后若弹出腾讯验证码(滑块/点选),自动化无法绕过:脚本会暂停并提示人工在浏览器窗口
手动完成,完成后脚本自动继续并保存登录态;若已有有效登录态则直接复用,不重新登录。
配置(.env):
wm_login_url 登录页 URL(默认 https://account.weimob.com)
wm_target_url_keyword 登录成功后 URL 关键字(默认 master.weimob.com)
wm_login_username 微盟登录手机号
wm_login_password 微盟登录密码
wm_bos_id 商家后台 bosId(会话校验接口用;默认内置金色印象账号值,其他账号请覆盖)
wm_validate_url (可选)会话校验接口 URL;默认 download/list
登录态文件(与共享版 weimob_login.py 同一路径,可互相复用):
%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_cookies.json(Cookies)
%LOCALAPPDATA%\\37duAutomation\\.sessions\\weimob_tokens.json(localStorage 票据)
依赖:pip install DrissionPage requests python-dotenv
入口:
python wm_login.py 独立运行(等价于 main({"force": true}))
"""
import os
import json
import time
from DrissionPage import ChromiumPage, ChromiumOptions
from dotenv import load_dotenv
import requests
# ================== 共享路径(与项目 app 版统一) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'weimob_cookies.json')
TOKEN_FILE = os.path.join(_SESSIONS_DIR, 'weimob_tokens.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
def _load_shared_env():
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
load_dotenv()
# ================== 配置 ==================
_load_shared_env()
LOGIN_URL = os.getenv('wm_login_url', 'https://account.weimob.com').strip()
SUCCESS_KEYWORD = os.getenv('wm_target_url_keyword', 'master.weimob.com/bos/products/home').strip()
USERNAME = os.getenv('wm_login_username', '').strip()
PASSWORD = os.getenv('wm_login_password', '').strip()
# 会话校验接口:download/list,登录态有效时返回 {"errcode":"0"},失效时返回错误码/登录页
DOWNLOAD_LIST_URL = "https://master.weimob.com/api3/merchant/backstage/service/download/list"
TIMEOUT = 10
LOGIN_WAIT = 180 # 登录等待总时长(秒):含人工处理腾讯验证码的时间
HEADLESS = False # 微盟登录需人工兜底验证码,必须可见浏览器
# ================== Cookies / 票据持久化 ==================
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
def save_session(page):
"""登录成功后保存 Cookies 与 localStorage 票据。"""
cookies = page.cookies(all_domains=True)
ensure_dir(_SESSIONS_DIR)
if cookies:
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
# localStorage 票据(如 wm token 等),仅保留非超长 key,备用
try:
raw = page.run_js('''
const data = {};
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
const v = localStorage.getItem(k);
if (v && v.length < 100000) data[k] = v;
}
return JSON.stringify(data);
''')
ls = json.loads(raw) if raw else {}
if ls:
with open(TOKEN_FILE, 'w', encoding='utf-8') as f:
json.dump({"localStorage": ls, "saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
f, ensure_ascii=False, indent=2)
print(f"已保存 localStorage 票据 {len(ls)} 项到 {TOKEN_FILE}")
except Exception as e:
print(f"保存 localStorage 票据失败(不影响 Cookies):{e}")
def load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== 会话校验(无需打开浏览器) ==================
def _build_validate_body():
"""构造 download/list 校验请求体(模板化,仅 bosId 等商家标识可变)。"""
bos_id = os.getenv('wm_bos_id', '4022571268153').strip()
merchant_id = int(os.getenv('wm_merchant_id', '2000527625153'))
vid = int(os.getenv('wm_vid', '6017432629153'))
product_id = int(os.getenv('wm_product_id', '145'))
product_version_id = os.getenv('wm_product_version_id', '12010')
product_instance_id = int(os.getenv('wm_product_instance_id', '22515052153'))
return {
"bosId": bos_id,
"pageSize": 1,
"basicInfo": {
"merchantId": merchant_id,
"bosId": int(bos_id),
"vid": vid,
"vidType": 2,
"vidTypes": [2],
"productId": product_id,
"productVersionId": product_version_id,
"productInstanceId": product_instance_id,
"tcode": "weimob",
},
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_weimob_session():
"""用保存的 cookies 构建 requests.Session(仅注入微盟相关域)。
微盟 api3 接口除 cookie 外,还必须携带如下请求头才能通过鉴权(否则 errcode=1041 fail auth):
Authorization: Bearer <saasAuthData cookie 值>
Apiclient: saas-pc
weimob-bosId: <bosId>
"""
cookies = load_cookies()
if not cookies:
return None
token = next((c["value"] for c in cookies
if c.get("name") == "saasAuthData" and c.get("value")), "")
bos_id = os.getenv('wm_bos_id', '4022571268153').strip()
session = requests.Session()
session.headers.update({
"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",
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*",
"Origin": "https://master.weimob.com",
"Referer": "https://master.weimob.com/",
"Authorization": f"Bearer {token}",
"Apiclient": "saas-pc",
"weimob-bosId": bos_id,
})
for c in cookies:
domain = c.get("domain") or ""
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
return session
def _is_weimob_session_valid():
"""API 轻量校验微盟登录态:download/list 返回 {"errcode":"0"} 视为有效。"""
validate_url = os.getenv('wm_validate_url', '').strip() or DOWNLOAD_LIST_URL
session = _build_weimob_session()
if session is None:
return False
try:
resp = session.post(validate_url, json=_build_validate_body(), timeout=15)
except Exception as e:
print(f"API 校验微盟登录态异常:{e}")
return False
if resp.status_code != 200:
print(f"API 校验微盟登录态状态码异常:{resp.status_code}")
return False
try:
data = resp.json()
if data.get("errcode") == "0":
return True
print(f"API 校验返回非成功码:{str(data)[:200]}(若为账号配置问题请检查 wm_bos_id)")
return False
except Exception:
return False
# ================== 登录主流程 ==================
def _wait_login(page):
"""登录等待:处理协议弹窗 + 提示人工完成腾讯验证码,直到登录成功或超时。"""
deadline = time.time() + LOGIN_WAIT
captcha_hinted = False
while time.time() < deadline:
if SUCCESS_KEYWORD in page.url:
return True
# 协议确认弹窗(首次登录出现「同意」按钮),自动点同意
try:
agree = page.ele('xpath://button[contains(.,"意")]', timeout=1)
if agree:
print("检测到协议确认弹窗,点击「同意」")
agree.click()
time.sleep(1)
continue
except Exception:
pass
# 腾讯验证码提示(跨域 iframe,脚本无法自动操作,交给人工)
if not captcha_hinted:
try:
cap = page.ele('css:iframe[src*="captcha"],iframe[src*="gtimg"]', timeout=1)
if cap:
print("检测到腾讯验证码,请在浏览器窗口手动完成验证……完成前脚本会持续等待。")
captcha_hinted = True
except Exception:
pass
time.sleep(2)
return False
def _do_login():
"""打开浏览器完成微盟登录(人工兜底验证码),成功保存登录态。"""
co = ChromiumOptions()
if HEADLESS:
co.headless()
page = ChromiumPage(co)
try:
page.get(LOGIN_URL)
time.sleep(2)
if SUCCESS_KEYWORD in page.url:
print("已登录")
save_session(page)
return True
# 默认打开是「验证码登录」,切换到「密码登录」tab
if not page.ele('css:input[placeholder="请输入密码"]', timeout=5):
tab = page.ele('xpath://span[contains(@class,"tabItem") and text()="密码登录"]', timeout=5)
if tab:
tab.click()
time.sleep(1)
else:
print("找不到「密码登录」切换入口")
return False
account = page.ele('css:input[placeholder="请输入手机号码"]', timeout=TIMEOUT)
if not account:
print("找不到手机号输入框")
return False
account.clear()
account.input(USERNAME)
time.sleep(0.5)
pwd = page.ele('css:input[placeholder="请输入密码"]', timeout=TIMEOUT)
if not pwd:
print("找不到密码输入框")
return False
pwd.clear()
pwd.input(PASSWORD)
time.sleep(0.5)
# 勾选「登录即表示同意」协议复选框(未勾选时点击一次)
try:
checkbox = page.ele('css:input[type="checkbox"].ant-checkbox-input', timeout=3)
if checkbox:
if getattr(checkbox, 'checked', False):
print("协议复选框已勾选")
else:
checkbox.click()
time.sleep(0.5)
print("已勾选「登录即表示同意」协议复选框")
except Exception as e:
print(f"勾选协议复选框异常(继续尝试登录):{e}")
# 登录按钮文本在子 span 内,需用 contains(.,...) 才能匹配
login_btn = page.ele('xpath://button[contains(.,"登")]', timeout=5)
if not login_btn:
print("找不到登录按钮")
return False
login_btn.click()
if _wait_login(page):
print("登录成功")
save_session(page)
return True
print("登录失败(超时未进入后台)")
return False
finally:
try:
page.quit()
except Exception:
pass
def ensure_login(force=False):
"""
确保存在有效的微盟登录态并缓存 Cookies/票据。
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
"""
_load_shared_env()
_set_login_state(False)
if not (LOGIN_URL and SUCCESS_KEYWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(wm_login_url / wm_target_url_keyword 未配置且无内置默认值)", "relogin": False}
if not (USERNAME and PASSWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(wm_login_username / wm_login_password 未配置)", "relogin": False}
# 优先复用已保存的登录态(通过 API 校验有效性,无需打开浏览器)
if not force and _is_weimob_session_valid():
print("已通过缓存的 Cookies 复用微盟登录态")
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE,
"message": "复用缓存登录态", "relogin": False}
ok = _do_login()
if ok:
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录失败(可能验证码未完成或账号密码有误)", "relogin": False}
# ================== 影刀自定义指令入口 ==================
def main(args):
"""
影刀自定义指令「37du微盟登录」调用入口。
args: dict,可选字段 force(bool) 是否强制重新登录
返回: dict {success, cookie_path, message, relogin}
"""
if not args:
args = {}
force = bool(args.get("force", False))
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "cookie_path": COOKIE_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main({"force": True})
print("最终结果:", result)
+378
View File
@@ -0,0 +1,378 @@
# -*- coding: utf-8 -*-
"""
@FileName: weimob_login.py
@Description: 微盟(Weimob)登录自定义指令(影刀编码版 Python 模块源码)。
作为「37du微盟登录」影刀自定义指令的模块源码(单一真源),
供 XQ0047 微盟数据导出等微盟相关流程复用登录态。
如何在影刀中创建指令:
1. 影刀客户端 → 新建「PC自动化指令」→ 指令编码如 weimob_login,添加 Python 模块;
2. 把本文件内容粘贴进指令的 Python 模块(或直接以本文件作为模块源码);
3. 增加流程参数 force(可选,布尔,是否强制重新登录);
4. 保存并「发版」;在需要登录的应用中「获取指令」并安装;
5. 在每个应用的流程开头拖入该指令,即可保证后续业务脚本能读到有效登录态。
登录说明:
- 微盟登录页默认打开是「验证码登录」(codeLogin.html),脚本会自动切换到「密码登录」tab;
- 账号密码只从共享 .env 读取(wm_login_username / wm_login_password),不内置明文;
- 点击登录后若弹出腾讯验证码(滑块/点选),自动化无法绕过:脚本会暂停并提示人工在浏览器窗口
手动完成,完成后脚本自动继续并保存登录态;若已有有效登录态则直接复用,不重新登录。
约定(与项目 app 版一致):
- 配置:统一读取固定路径共享 .env:%LOCALAPPDATA%\\37duAutomation\\.env
(本地开发时也兼容当前工作目录下的 .env);
- 登录态:统一写入 %LOCALAPPDATA%\\37duAutomation\\.sessions\\
weimob_cookies.json(Cookies)+ weimob_tokens.json(localStorage 票据),
各微盟业务脚本自行用这些 cookies 构建 requests.Session。
配置(.env):
wm_login_url 登录页 URL(默认 https://account.weimob.com)
wm_target_url_keyword 登录成功后 URL 关键字(默认 master.weimob.com)
wm_login_username 微盟登录手机号
wm_login_password 微盟登录密码
wm_bos_id 商家后台 bosId(会话校验接口用;默认内置金色印象账号值,其他账号请覆盖)
wm_validate_url (可选)会话校验接口 URL;默认 download/list
全局变量(在影刀流程中创建,此指令负责写入):
login_state 登录成功或缓存的登录态有效时写入 True,否则为 False
依赖(影刀「Python包管理」安装):
pip install DrissionPage requests python-dotenv
入口:
main(args) 影刀自定义指令调用入口,args 传 {"force": true|false},返回 JSON 安全 dict
python weimob_login.py 独立运行(等价于 main({"force": true}))
"""
import os
import json
import time
from DrissionPage import ChromiumPage, ChromiumOptions
from dotenv import load_dotenv
import requests
# ================== 共享路径(与项目 app 版统一) ==================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'weimob_cookies.json')
TOKEN_FILE = os.path.join(_SESSIONS_DIR, 'weimob_tokens.json')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
def _load_shared_env():
"""统一加载配置:优先固定路径共享 .env,再兼容当前工作目录 .env 与系统变量。"""
if os.path.exists(SHARED_ENV_FILE):
load_dotenv(SHARED_ENV_FILE)
load_dotenv()
# ================== 配置 ==================
_load_shared_env()
LOGIN_URL = os.getenv('wm_login_url', 'https://account.weimob.com').strip()
SUCCESS_KEYWORD = os.getenv('wm_target_url_keyword', 'master.weimob.com/bos/products/home').strip()
USERNAME = os.getenv('wm_login_username', '').strip()
PASSWORD = os.getenv('wm_login_password', '').strip()
# 会话校验接口:download/list,登录态有效时返回 {"errcode":"0"},失效时返回错误码/登录页
DOWNLOAD_LIST_URL = "https://master.weimob.com/api3/merchant/backstage/service/download/list"
TIMEOUT = 10
LOGIN_WAIT = 180 # 登录等待总时长(秒):含人工处理腾讯验证码的时间
HEADLESS = False # 微盟登录需人工兜底验证码,必须可见浏览器
# ================== Cookies / 票据持久化 ==================
def ensure_dir(path):
if path:
os.makedirs(path, exist_ok=True)
def save_session(page):
"""登录成功后保存 Cookies 与 localStorage 票据。"""
cookies = page.cookies(all_domains=True)
ensure_dir(_SESSIONS_DIR)
if cookies:
with open(COOKIE_FILE, 'w', encoding='utf-8') as f:
json.dump(cookies, f, ensure_ascii=False, indent=2)
print(f"已保存 {len(cookies)} 个 Cookies 到 {COOKIE_FILE}")
# localStorage 票据(如 wm token 等),仅保留非超长 key,备用
try:
raw = page.run_js('''
const data = {};
for (let i = 0; i < localStorage.length; i++) {
const k = localStorage.key(i);
const v = localStorage.getItem(k);
if (v && v.length < 100000) data[k] = v;
}
return JSON.stringify(data);
''')
ls = json.loads(raw) if raw else {}
if ls:
with open(TOKEN_FILE, 'w', encoding='utf-8') as f:
json.dump({"localStorage": ls, "saved_at": time.strftime("%Y-%m-%d %H:%M:%S")},
f, ensure_ascii=False, indent=2)
print(f"已保存 localStorage 票据 {len(ls)} 项到 {TOKEN_FILE}")
except Exception as e:
print(f"保存 localStorage 票据失败(不影响 Cookies):{e}")
def load_cookies():
if not os.path.exists(COOKIE_FILE):
return None
with open(COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
# ================== 影刀全局变量 ==================
def _set_login_state(value):
"""写入影刀全局变量 login_state(影刀指令环境可用;独立运行/非影刀环境时静默跳过)。"""
try:
glv['login_state'] = value
print(f"已写入影刀全局变量 login_state={value}")
except Exception as e:
print(f"写入影刀全局变量 login_state 失败(非影刀环境?):{e}")
# ================== 会话校验(无需打开浏览器) ==================
def _build_validate_body():
"""构造 download/list 校验请求体(模板化,仅 bosId 等商家标识可变)。"""
bos_id = os.getenv('wm_bos_id', '4022571268153').strip()
merchant_id = int(os.getenv('wm_merchant_id', '2000527625153'))
vid = int(os.getenv('wm_vid', '6017432629153'))
product_id = int(os.getenv('wm_product_id', '145'))
product_version_id = os.getenv('wm_product_version_id', '12010')
product_instance_id = int(os.getenv('wm_product_instance_id', '22515052153'))
return {
"bosId": bos_id,
"pageSize": 1,
"basicInfo": {
"merchantId": merchant_id,
"bosId": int(bos_id),
"vid": vid,
"vidType": 2,
"vidTypes": [2],
"productId": product_id,
"productVersionId": product_version_id,
"productInstanceId": product_instance_id,
"tcode": "weimob",
},
"i18n": {"language": "zh-CN", "timezone": 8},
"extendInfo": {"refer": "/bos/products/ecOrder/{bosId}/{key}/order/order/orderlist", "source": 80},
}
def _build_weimob_session():
"""用保存的 cookies 构建 requests.Session(仅注入微盟相关域)。
微盟 api3 接口除 cookie 外,还必须携带如下请求头才能通过鉴权(否则 errcode=1041 fail auth):
Authorization: Bearer <saasAuthData cookie 值>
Apiclient: saas-pc
weimob-bosId: <bosId>
"""
cookies = load_cookies()
if not cookies:
return None
token = next((c["value"] for c in cookies
if c.get("name") == "saasAuthData" and c.get("value")), "")
bos_id = os.getenv('wm_bos_id', '4022571268153').strip()
session = requests.Session()
session.headers.update({
"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",
"Content-Type": "application/json",
"Accept": "application/json, text/plain, */*",
"Origin": "https://master.weimob.com",
"Referer": "https://master.weimob.com/",
"Authorization": f"Bearer {token}",
"Apiclient": "saas-pc",
"weimob-bosId": bos_id,
})
for c in cookies:
domain = c.get("domain") or ""
if any(k in domain for k in ("weimob.com", "weimobwmc.com")):
session.cookies.set(c["name"], c["value"], domain=domain, path=c.get("path", "/"))
return session
def _is_weimob_session_valid():
"""API 轻量校验微盟登录态:download/list 返回 {"errcode":"0"} 视为有效。"""
validate_url = os.getenv('wm_validate_url', '').strip() or DOWNLOAD_LIST_URL
session = _build_weimob_session()
if session is None:
return False
try:
resp = session.post(validate_url, json=_build_validate_body(), timeout=15)
except Exception as e:
print(f"API 校验微盟登录态异常:{e}")
return False
if resp.status_code != 200:
print(f"API 校验微盟登录态状态码异常:{resp.status_code}")
return False
try:
data = resp.json()
if data.get("errcode") == "0":
return True
print(f"API 校验返回非成功码:{str(data)[:200]}(若为账号配置问题请检查 wm_bos_id)")
return False
except Exception:
return False
# ================== 登录主流程 ==================
def _wait_login(page):
"""登录等待:处理协议弹窗 + 提示人工完成腾讯验证码,直到登录成功或超时。"""
deadline = time.time() + LOGIN_WAIT
captcha_hinted = False
while time.time() < deadline:
if SUCCESS_KEYWORD in page.url:
return True
# 协议确认弹窗(首次登录出现「同意」按钮),自动点同意
try:
agree = page.ele('xpath://button[contains(.,"意")]', timeout=1)
if agree:
print("检测到协议确认弹窗,点击「同意」")
agree.click()
time.sleep(1)
continue
except Exception:
pass
# 腾讯验证码提示(跨域 iframe,脚本无法自动操作,交给人工)
if not captcha_hinted:
try:
cap = page.ele('css:iframe[src*="captcha"],iframe[src*="gtimg"]', timeout=1)
if cap:
print("检测到腾讯验证码,请在浏览器窗口手动完成验证……完成前脚本会持续等待。")
captcha_hinted = True
except Exception:
pass
time.sleep(2)
return False
def _do_login():
"""打开浏览器完成微盟登录(人工兜底验证码),成功保存登录态。"""
co = ChromiumOptions()
if HEADLESS:
co.headless()
page = ChromiumPage(co)
try:
page.get(LOGIN_URL)
time.sleep(2)
if SUCCESS_KEYWORD in page.url:
print("已登录")
save_session(page)
return True
# 默认打开是「验证码登录」,切换到「密码登录」tab
if not page.ele('css:input[placeholder="请输入密码"]', timeout=5):
tab = page.ele('xpath://span[contains(@class,"tabItem") and text()="密码登录"]', timeout=5)
if tab:
tab.click()
time.sleep(1)
else:
print("找不到「密码登录」切换入口")
return False
account = page.ele('css:input[placeholder="请输入手机号码"]', timeout=TIMEOUT)
if not account:
print("找不到手机号输入框")
return False
account.clear()
account.input(USERNAME)
time.sleep(0.5)
pwd = page.ele('css:input[placeholder="请输入密码"]', timeout=TIMEOUT)
if not pwd:
print("找不到密码输入框")
return False
pwd.clear()
pwd.input(PASSWORD)
time.sleep(0.5)
# 勾选「登录即表示同意」协议复选框(未勾选时点击一次)
try:
checkbox = page.ele('css:input[type="checkbox"].ant-checkbox-input', timeout=3)
if checkbox:
if getattr(checkbox, 'checked', False):
print("协议复选框已勾选")
else:
checkbox.click()
time.sleep(0.5)
print("已勾选「登录即表示同意」协议复选框")
except Exception as e:
print(f"勾选协议复选框异常(继续尝试登录):{e}")
# 登录按钮文本在子 span 内,需用 contains(.,...) 才能匹配
login_btn = page.ele('xpath://button[contains(.,"登")]', timeout=5)
if not login_btn:
print("找不到登录按钮")
return False
login_btn.click()
if _wait_login(page):
print("登录成功")
save_session(page)
return True
print("登录失败(超时未进入后台)")
return False
finally:
try:
page.quit()
except Exception:
pass
def ensure_login(force=False):
"""
确保存在有效的微盟登录态并缓存 Cookies/票据。
返回 JSON 安全 dict:{success, cookie_path, message, relogin}
"""
_load_shared_env()
_set_login_state(False)
if not (LOGIN_URL and SUCCESS_KEYWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(wm_login_url / wm_success_keyword 未配置且无内置默认值)", "relogin": False}
if not (USERNAME and PASSWORD):
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录配置缺失(wm_login_username / wm_login_password 未配置)", "relogin": False}
# 优先复用已保存的登录态(通过 API 校验有效性,无需打开浏览器)
if not force and _is_weimob_session_valid():
print("已通过缓存的 Cookies 复用微盟登录态")
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE,
"message": "复用缓存登录态", "relogin": False}
ok = _do_login()
if ok:
_set_login_state(True)
return {"success": True, "cookie_path": COOKIE_FILE, "message": "登录成功", "relogin": True}
return {"success": False, "cookie_path": COOKIE_FILE,
"message": "登录失败(可能验证码未完成或账号密码有误)", "relogin": False}
# ================== 影刀自定义指令入口 ==================
def main(args):
"""
影刀自定义指令「37du微盟登录」调用入口。
args: dict,可选字段 force(bool) 是否强制重新登录
返回: dict {success, cookie_path, message, relogin}
"""
if not args:
args = {}
force = bool(args.get("force", False))
try:
return ensure_login(force=force)
except Exception as e:
return {"success": False, "cookie_path": COOKIE_FILE,
"message": f"登录过程异常:{e}", "relogin": False}
if __name__ == "__main__":
result = main({"force": True})
print("最终结果:", result)