# -*- coding: utf-8 -*- """ @FileName: erp_sso_login.py @Description: 金蝶云星空 ERP 单点登录(OA → ERP),纯接口无浏览器版共享模块。 逆向自 OA「系统入口 → ERP(新)/ERP(旧)」的 SSO 链路(2026-11 实测通过)。 链路(全程 requests,无浏览器,约 1 秒): 1. 读 OA 登录态 %LOCALAPPDATA%\\37duAutomation\\.sessions\\oa_cookies.json, 并校验其有效(sysNotifyTodo.do?method=sumTodoCount 返回 JSON 即有效); 2. GET https://oa.37du.co/portal/sso.do?method=token&appName=&redirect=/index → 302 Location: https://?token=; 3. GET 该 Location(跟随跳转)→ 落到 /K3Cloud/HTML5/lightstartapp.aspx?ud=, 从最终 URL 取出 ud(内含 dbid/username/appid/signeddata/timestamp), 同时会话里拿到 sl-session / ASP.NET_SessionId; 4. POST /k3cloud/Kingdee.BOS.ServiceFacade.ServicesStub.StartAppVerifySerivce.Verify.common.kdsvc Content-Type: text/json,JSON 体(ap0=clientinfo, customArgs=ud, ...), → 返回 ResultType=1,并下发 kdservice-sessionid(关键会话凭据); 5. 落盘 erp_cookies.json(app='old' 时为 erp_cookies_old.json,新旧互不覆盖), 并用一次只读查询校验会话可用。 关键实现要点(踩坑记录,勿随意改动): ⚠ 报文必须是 **JSON 体 + Content-Type: text/json**;用表单 data= 会报 "Unexpected character encountered while parsing value: n",握手失败; ⚠ 路径分两套:SSO 握手走 Kingdee.BOS.ServiceFacade.ServicesStub(k3cloud 小写、 服务名保留官方拼写 StartAppVerifySerivce),业务接口走 Kingdee.BOS.WebApi.ServicesStub; ⚠ ud 有时效,第 3~4 步必须紧接连跑,不能中间插入长耗时操作; ⚠ BuildSessionWithHtml5 在纯接口下返回 false,不需要调,Verify 已给会话; ⚠ 登录身份 = OA 当前登录人,不是独立 ERP 账号,权限随该员工在 ERP 中的角色; ⚠ ud 里的账套(dbid)由 OA 的 ERP 入口决定,本模块不硬编码账套。 对外入口: ensure_login(app='new', force=False) -> dict {success, cookie_path, message, relogin, identity} build_session(app='new', force=False) -> requests.Session 业务脚本用:登录态有效则复用,失效自动重登。 main(app='new', force=True) -> dict 影刀自定义指令调用入口(JSON 安全 dict)。 依赖(影刀「Python包管理」安装): pip install requests 配置: 无新增环境变量;复用 OA 登录态文件,OA 登录由「37duOA登录」指令负责。 """ import base64 import datetime import json import os import time import urllib.parse import uuid import requests # ================== 共享路径(与 oa_login / hr_login 统一) ================== _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') OA_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json') ERP_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'erp_cookies.json') # 新版 ERP_COOKIE_FILE_OLD = os.path.join(_SESSIONS_DIR, 'erp_cookies_old.json') # 旧版 ERP_META_FILE = os.path.join(_SESSIONS_DIR, 'erp_session_meta.json') ERP_META_FILE_OLD = os.path.join(_SESSIONS_DIR, 'erp_session_meta_old.json') # ================== 站点与接口常量 ================== OA_BASE = 'https://oa.37du.co' OA_VALIDATE_URL = OA_BASE + '/sys/notify/sys_notify_todo/sysNotifyTodo.do?method=sumTodoCount' SSO_URL_TPL = OA_BASE + '/portal/sso.do?method=token&appName={app}&redirect=/index' # app 标识 → (ERP 主机, OA 侧 appName) ERP_SITES = { 'new': ('criterion.erp.37du.co', 'erpnew'), 'old': ('erp.37du.co', 'erp'), } # SSO 握手服务(Kingdee.BOS.ServiceFacade,路径小写 k3cloud,服务名保留官方拼写) VERIFY_SVC = ('/k3cloud/Kingdee.BOS.ServiceFacade.ServicesStub' '.StartAppVerifySerivce.Verify.common.kdsvc') # 业务查询服务(Kingdee.BOS.WebApi) QUERY_SVC = ('/K3Cloud/Kingdee.BOS.WebApi.ServicesStub' '.DynamicFormService.ExecuteBillQuery.common.kdsvc') UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36') XHR_HEADERS = { 'User-Agent': UA, 'X-Requested-With': 'XMLHttpRequest', 'Referer': OA_BASE + '/sys/portal/page.jsp', } JSON_HEADERS = { 'User-Agent': UA, 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'text/json', } TIMEOUT = 20 RETRY_MAX = 3 # 项目规范:全局重试 3 次 RETRY_SLEEP = 1.5 # 会话失效判定关键字(业务权限报错不算失效) _SESSION_DEAD = ('会话信息已丢失', '请重新登录', 'Unexpectable request', '401 Forbidden') # ================== 通用 ================== 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 _ensure_dir(path): if path: os.makedirs(path, exist_ok=True) def _utc_ts(): """K3Cloud 客户端时间戳格式:2026-11-13T10:53:00.000Z""" return datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.') + '000Z' def _client_info(entry_url, custom_args): """K3Cloud HTML5 客户端信息(服务端只做基础校验,值可固定)。""" return { 'ipAddress': 'mozila', 'macAddress': 'browser', 'hostName': 'mozila', 'IsDefaultInfo': True, 'IpAddress': 'mozila', 'MacAddress': 'browser', 'HostName': 'mozila', 'OperationSystem': '', 'BrowserType': 'win|chrome|157.0.0.0', 'Version': 'HTML5', 'ClientType': 16, 'vH': 0, 'vW': 764, 'AvailableAreaSize': {'Height': 595, 'Width': 764}, 'ScreenSize': {'Height': 600, 'Width': 800}, 'EntryPageUrl': entry_url, 'customArgs': custom_args, } # ================== Cookies 持久化(结构对齐 oa/hr 登录模块) ================== def _load_cookies(path): """读取 cookies 文件 → requests 可用的 [{name, value, domain, path}]。""" if not path or not os.path.exists(path): return [] try: with open(path, 'r', encoding='utf-8') as f: data = json.load(f) return data if isinstance(data, list) else [] except Exception as e: print(f"读取 cookies 失败({path}):{e}") return [] def _save_cookies(session, path): """requests.Session → [{name, value, domain, path, expires}, ...],与其他登录模块结构兼容。""" cookies = [] for c in session.cookies: cookies.append({ 'name': c.name, 'value': c.value, 'domain': c.domain or '', 'path': c.path or '/', 'expires': c.expires, }) _ensure_dir(os.path.dirname(os.path.abspath(path))) with open(path, 'w', encoding='utf-8') as f: json.dump(cookies, f, ensure_ascii=False, indent=2) print(f"已保存 {len(cookies)} 个 ERP cookies → {path}") return cookies def _session_from_cookies(cookies): """把 cookies 列表灌进 requests.Session。""" s = requests.Session() for c in cookies or []: try: s.cookies.set(c.get('name'), c.get('value'), domain=c.get('domain') or None, path=c.get('path') or '/') except Exception: pass return s # ================== OA 登录态校验 ================== def _oa_cookies_valid(cookies): """OA 会话是否有效:sumTodoCount 返回 JSON 即有效(被重定向回登录页会返回 HTML)。""" if not cookies: print("未找到 OA 登录态(oa_cookies.json 缺失或为空),请先运行「37duOA登录」指令") return False s = _session_from_cookies(cookies) for delay in (0, 0.8, 2.0): # OA 网关偶发 468 风控,退避重试 if delay: time.sleep(delay) try: r = s.get(OA_VALIDATE_URL, headers=XHR_HEADERS, timeout=TIMEOUT) txt = (r.text or '').strip() if r.status_code == 200 and txt.startswith(('{', '[')): print("OA 登录态有效") return True print(f"OA 会话校验未通过(HTTP {r.status_code}),稍后重试...") except Exception as e: print(f"OA 会话校验异常:{e}") print("OA 登录态已失效,请先运行「37duOA登录」指令更新 oa_cookies.json") return False # ================== SSO 握手 ================== def _get_sso_entry(app): """第 2 步:向 OA 要 ERP 入口地址(302 Location 内含 OA 令牌)。""" app_name = ERP_SITES[app][1] url = SSO_URL_TPL.format(app=app_name) oa_cookies = _load_cookies(OA_COOKIE_FILE) if not _oa_cookies_valid(oa_cookies): return None, None s = _session_from_cookies(oa_cookies) r = s.get(url, headers=XHR_HEADERS, timeout=TIMEOUT, allow_redirects=False) loc = r.headers.get('Location') or '' if r.status_code not in (301, 302, 303, 307, 308) or not loc: print(f"SSO 未返回跳转地址(HTTP {r.status_code}),可能 OA 侧 ERP 入口配置有变") return None, None print(f"已取得 ERP SSO 入口(appName={app_name})") return s, loc def _exchange_session(erp_session, entry_url, host): """ 第 3~4 步:跟随到中转页取 ud,再用 Verify 换 kdservice-sessionid。 返回 (ok, message)。 """ resp = erp_session.get(entry_url, headers={'User-Agent': UA}, timeout=TIMEOUT, allow_redirects=True) final_url = str(resp.url) if 'lightstartapp.aspx' not in final_url.lower(): return False, f"中转页异常(未落到 lightstartapp.aspx):{final_url[:150]}", None if host not in final_url: # OA 侧入口指错了站点时会落到别的域,Verify 必然失败,这里先给出明确提示 print(f"⚠ SSO 落点与预期站点不一致:期望 {host},实际 {final_url.split('/')[2]}") ud = urllib.parse.parse_qs(urllib.parse.urlparse(final_url).query).get('ud', [''])[0] if not ud: return False, "中转页 URL 中缺少 ud 参数", None username = None try: pad = ud + '=' * (-len(ud) % 4) payload = json.loads(base64.b64decode(pad).decode('utf-8')) username = payload.get('username') print(f"SSO 身份:{username} 账套:{payload.get('dbid')}") except Exception: print("ud 解析失败(不影响后续握手)") base = f'https://{host}' ci = json.dumps(_client_info(final_url, ud), separators=(',', ':')) body = { 'ap0': ci, 'customArgs': ud, 'clientinfo': ci, 'forminfo': {'scope': 'BODY_'}, 'nonce': '', 'v': '1.0', 'format': '1', 'sign': '', 'timestamp': _utc_ts(), 'compressed': False, 'compressedapx': False, 'useragent': 'KD.HTML5.GZIP', } headers = dict(JSON_HEADERS) headers['Referer'] = final_url r = erp_session.post(base + VERIFY_SVC, json=body, headers=headers, timeout=TIMEOUT) if r.status_code != 200: return False, f"Verify 握手失败:HTTP {r.status_code}", None try: j = r.json() except Exception: return False, f"Verify 返回非 JSON:{r.text[:150]}", None result_type = j.get('ResultType') if result_type != 1: return False, f"Verify 未通过:{j.get('Message') or j.get('MessageCode') or result_type}", None if 'kdservice-sessionid' not in erp_session.cookies.get_dict(): return False, "Verify 通过但未下发 kdservice-sessionid", None print("SSO 握手完成,已取得 kdservice-sessionid") return True, 'SSO 登录成功', username def _erp_session_valid(session, host): """业务查询探活:返回 JSON 且不含会话失效关键字即视为有效(权限报错同样算有效)。""" url = f'https://{host}' + QUERY_SVC body = {'parameters': [{'FormId': 'BD_MATERIAL', 'FieldKeys': 'FNumber', 'FilterString': '', 'OrderString': '', 'TopRowCount': 1, 'StartRow': 0, 'Limit': 0}]} try: r = session.post(url, json=body, timeout=TIMEOUT) except Exception as e: print(f"ERP 会话探活异常:{e}") return False txt = (r.text or '').strip() if r.status_code != 200: print(f"ERP 会话探活 HTTP {r.status_code}") return False if any(k in txt for k in _SESSION_DEAD): return False return txt.startswith(('[', '{')) def _cookie_file(app): """按站点取 cookies 落盘路径(新旧版登录态互不覆盖)。""" return ERP_COOKIE_FILE_OLD if app == 'old' else ERP_COOKIE_FILE def _saved_session(app): """用已落盘的 cookies 建会话(不做校验)。""" host = ERP_SITES[app][0] path = _cookie_file(app) cookies = [c for c in _load_cookies(path) if host in (c.get('domain') or '')] or _load_cookies(path) return _session_from_cookies(cookies) def _meta_file(app): """按站点取会话摘要路径。""" return ERP_META_FILE_OLD if app == 'old' else ERP_META_FILE def _save_meta(app, host, identity): """会话摘要(与其它平台 *_session_meta.json 同风格):记录 SSO 身份,便于日志与排查。""" meta = {'app': app, 'host': host, 'identity': identity, 'saved_at': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} try: with open(_meta_file(app), 'w', encoding='utf-8') as f: json.dump(meta, f, ensure_ascii=False, indent=2) except Exception as e: print(f"写入会话摘要失败(忽略):{e}") def _load_identity(app): """从会话摘要里读上次 SSO 的登录人(读不到返回 None)。""" try: with open(_meta_file(app), 'r', encoding='utf-8') as f: return (json.load(f) or {}).get('identity') except Exception: return None # ================== 主入口 ================== def ensure_login(app='new', force=False): """ 确保存在有效的 ERP 登录态(纯接口 SSO),必要时重新握手并落盘。 参数: app 'new'=新版 criterion.erp.37du.co / 'old'=旧版 erp.37du.co force True 强制重新握手(忽略缓存) 返回: {success, cookie_path, message, relogin, identity} """ _set_login_state(False) if app not in ERP_SITES: return {'success': False, 'cookie_path': ERP_COOKIE_FILE, 'message': f"无效的 app 参数:{app}(可选 'new' / 'old')", 'relogin': False, 'identity': None} host = ERP_SITES[app][0] cookie_path = _cookie_file(app) # 优先复用已保存的 ERP 会话 if not force: sess = _saved_session(app) if _erp_session_valid(sess, host): print("已通过缓存的 Cookies 复用 ERP 登录态") _set_login_state(True) return {'success': True, 'cookie_path': cookie_path, 'message': '复用缓存登录态', 'relogin': False, 'identity': _load_identity(app)} last_msg = '' for attempt in range(1, RETRY_MAX + 1): print(f"--- 第 {attempt}/{RETRY_MAX} 轮 ERP SSO 登录 ---") try: oa_sess, entry = _get_sso_entry(app) if not entry: last_msg = '未取得 SSO 入口(OA 登录态失效或 OA 侧入口变更)' time.sleep(RETRY_SLEEP) continue erp_sess = requests.Session() ok, msg, identity = _exchange_session(erp_sess, entry, host) if not ok: last_msg = msg time.sleep(RETRY_SLEEP) continue if not _erp_session_valid(erp_sess, host): last_msg = 'SSO 完成但业务接口校验未通过' time.sleep(RETRY_SLEEP) continue _save_cookies(erp_sess, cookie_path) _save_meta(app, host, identity) _set_login_state(True) return {'success': True, 'cookie_path': cookie_path, 'message': 'SSO 登录成功', 'relogin': True, 'identity': identity} except Exception as e: last_msg = f'SSO 过程异常:{e}' print(last_msg) time.sleep(RETRY_SLEEP) return {'success': False, 'cookie_path': cookie_path, 'message': last_msg or 'ERP SSO 登录失败(重试耗尽)', 'relogin': False, 'identity': None} def build_session(app='new', force=False): """ 业务脚本入口:返回可直接调用 ERP WebAPI 的 requests.Session。 登录态有效则复用 erp_cookies.json,失效自动重新 SSO 登录。 """ result = ensure_login(app=app, force=force) if not result.get('success'): print(f"ERP 会话不可用:{result.get('message')}") return _saved_session(app) # ================== 影刀自定义指令入口 ================== def main(app='new', force=True): """ 影刀自定义指令调用入口。 app: 'new' / 'old',用于选择新版或旧版 ERP force: bool 是否强制重新握手(默认 True,便于本地独立运行直接刷新登录态) 返回: dict {success, cookie_path, message, relogin, identity} """ try: return ensure_login(app=app, force=force) except Exception as e: return {'success': False, 'cookie_path': ERP_COOKIE_FILE, 'message': f'登录过程异常:{e}', 'relogin': False, 'identity': None} if __name__ == '__main__': print("最终结果:", main(app='new', force=True))