"""复现门户脚本里的请求签名。""" from __future__ import annotations import hashlib import time import uuid from urllib.parse import quote from app.nqi.constants import APP_KEY, APP_SECRET, SIGN_VERSION _SKIP = {"sign", "SIG", "UPPER_SIG"} def encode_uri_component(value: str) -> str: return quote(value, safe="-_.!~*'()") def build_sign( params: dict | None = None, *, encode: bool = True, timestamp: str | None = None, nonce: str | None = None, ) -> dict[str, str]: stamp = timestamp if timestamp is not None else str(int(time.time())) nonce_str = nonce if nonce is not None else uuid.uuid4().hex payload: dict[str, str] = {} for key, value in (params or {}).items(): text = "" if value is None else str(value) payload[str(key)] = text if text == "" or not encode else encode_uri_component(text) payload["timestamp"] = stamp payload["nonceStr"] = nonce_str payload["version"] = SIGN_VERSION raw = "".join(f"{key}{payload[key]}" for key in sorted(payload) if key not in _SKIP) sign = hashlib.md5((raw + APP_SECRET).encode("utf-8")).hexdigest().upper() return { "sign": sign, "timestamp": stamp, "nonceStr": nonce_str, "version": SIGN_VERSION, "appKey": APP_KEY, }