import hashlib import hmac import json import os import secrets import time import urllib.error import urllib.parse import urllib.request # Python 3: standard library only. Keep credentials on your server. BASE_URL = os.getenv("DOTUAN_BASE_URL", "https://t.ek2.cn").rstrip("/") APP_ID = os.environ["DOTUAN_APP_ID"] APP_SECRET = os.environ["DOTUAN_APP_SECRET"] def generate(long_url, remark="", group_name=""): payload = { "app_code": APP_ID, "generate_url": long_url, "group_name": group_name, "nonce": secrets.token_hex(16), "remark": remark, "timestamp": str(int(time.time())), } canonical = "&".join( key + "=" + urllib.parse.quote(payload[key], safe="-._~") for key in sorted(payload) ) signature = hmac.new( APP_SECRET.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256 ).hexdigest().upper() request = urllib.request.Request( BASE_URL + "/api/ShortLink/Generate", data=json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers={"Content-Type": "application/json", "X-Signature": signature}, method="POST", ) try: with urllib.request.urlopen(request, timeout=30) as response: result = json.load(response) except urllib.error.HTTPError as error: raise RuntimeError("HTTP %s: %s" % ( error.code, error.read().decode("utf-8", errors="replace") )) from error if result.get("resultCode") != 200 or not result.get("resultData"): raise RuntimeError(result.get("resultMsg", "Invalid API response")) return BASE_URL + "/" + result["resultData"] if __name__ == "__main__": print(generate("https://example.com/?campaign=partner", "合作方活动", "第三方接入")) # For multiple links, call generate() for each item. It signs each request anew.