""" 虎牙 HTTP POST RPC 通道(cdnws.api.huya.com) 用于 WSS 业务通道被设备态 Cookie 静默拒收时的兜底: URL: https://cdnws.api.huya.com/?baseinfo= Body: Wup 包 (含4字节长度前缀) Response: Wup 包 (tRsp) """ import base64 import json import random import struct import urllib.parse import urllib.request from typing import Optional, Callable from .taf_protocol import TafOutputStream, TafInputStream, TafType, TafStruct from .wup_protocol import WupRequest, WupResponse CDNWS_HOST = "cdnws.api.huya.com" PC_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/149.0.0.0 Safari/537.36") HTTP_HUYA_UA = "webh5&0.0.1&websocket&&diypc_52775" class WSConnectParaInfo(TafStruct): """WSS/HTTP 连接参数(baseinfo 的内容),从前端 SDK 逆向 tag0 lUid int64 tag1 sGuid string tag2 sUA string "webh5&0.0.1&websocket&&diypc_52775" tag3 sAppSrc string "HUYA&ZH&2052" tag4 sMid string tag5 sExp string tag6 iTokenType int32 tag7 sToken string tag8 sCookie string (lUid>0 时设 document.cookie) tag9 sTraceId string "hex8:hex8:0:0" tag10 mCustomHeaders Map """ def __init__(self): self.lUid: int = 0 self.sGuid: str = "" self.sUA: str = "webh5&0.0.1&websocket&&diypc_52775" self.sAppSrc: str = "HUYA&ZH&2052" self.sMid: str = "" self.sExp: str = "" self.iTokenType: int = 0 self.sToken: str = "" self.sCookie: str = "" self.sTraceId: str = "" self.mCustomHeaders: dict = {} def write_to(self, os: TafOutputStream): # 与浏览器一致: 空字符串也写 (HAR 实证 tag4/5/7/8 都写了空串) if self.lUid: os.write_int64(0, self.lUid) else: os.write_int64(0, 0) # ZERO os.write_string(1, self.sGuid) os.write_string(2, self.sUA) os.write_string(3, self.sAppSrc) os.write_string(4, self.sMid) os.write_string(5, self.sExp) os.write_int32(6, self.iTokenType) os.write_string(7, self.sToken) os.write_string(8, self.sCookie) os.write_string(9, self.sTraceId) os.write_map(10, self.mCustomHeaders) def read_from(self, ins: TafInputStream): pass def _gen_trace_id() -> str: """生成 sTraceId (格式 hex8:hex8:0:0,HAR 实证)""" h = '%016x' % random.getrandbits(64) return f"{h}:{h}:0:0" def generate_http_baseinfo(uid: int, guid: str, cookie: str, trace_id: str = None) -> str: """ 构造 HTTP POST 的 baseinfo URL 参数 HAR 实证: getGoodsInfoV5 的 baseinfo lUid=0, sCookie="" (身份靠 Wup body 的 userId.sCookie) """ info = WSConnectParaInfo() info.lUid = 0 # HAR 实证: baseinfo 里 lUid=0 info.sGuid = guid info.sUA = "webh5&0.0.1&websocket&&diypc_52775" info.sAppSrc = "HUYA&ZH&2052" info.sCookie = "" # HAR 实证: baseinfo 不带 cookie, cookie 在 Wup body info.sTraceId = trace_id or _gen_trace_id() os = TafOutputStream() os.write_struct_begin(0) # WSConnectParaInfo 是顶层 struct? 实际 baseinfo 是裸 struct 字段 # 实际 HAR baseinfo 解码: 顶层直接是字段(tag0 lUid...), 不包 STRUCT_BEGIN # 重置, 不写 STRUCT_BEGIN os = TafOutputStream() info.write_to(os) raw = os.get_bytes() # base64 (与 JS window.btoa 一致) b64 = base64.b64encode(raw).decode('ascii') return urllib.parse.quote(b64, safe='') class HuyaHttpClient: """虎牙 HTTP POST RPC 客户端""" def __init__(self, logger: Callable[[str], None] = None): self.logger = logger or print @staticmethod def _normalize_cookie(cookie: str) -> str: """HTTP 业务 UserId.sCookie 需要带 huya_ua 前缀,避免重复写入。""" import re cookie = (cookie or "").strip() normalized = f"huya_ua={HTTP_HUYA_UA}" if re.search(r"(?:^|;\s*)huya_ua=", cookie): return re.sub(r"(^|;\s*)huya_ua=[^;]*", lambda m: f"{m.group(1)}{normalized}", cookie, count=1) if not cookie: return normalized return f"{normalized}; {cookie}" @staticmethod def _build_user(uid: int, guid: str, cookie: str): """构造 HTTP 业务 UserId。""" from .shop_structs import UserId user = UserId() user.lUid = uid user.sGuid = guid user.sToken = "" user.sHuYaUA = HTTP_HUYA_UA user.sCookie = HuyaHttpClient._normalize_cookie(cookie) user.iTokenType = 0 user.sDeviceInfo = "" user.sQIMEI = "" return user @staticmethod def _build_shop_app(source_id: str = "yellowcarlist", scene: int = 7): """构造 HTTP 业务 ShopAppInfo。""" from .shop_structs import ShopAppInfo info = ShopAppInfo() info.sAppId = "huya" info.sBizType = "" info.scene = scene info.sourceId = source_id return info @staticmethod def _build_order_env(item_count: int = 1): """构造下单/支付环境参数。""" import time click_time = int(time.time() * 1000) return { "user_click_seq": f'[{{"x":258,"y":487,"time":{click_time},"id":""}}]', "input_1": str(item_count), } def call_rpc(self, service: str, method: str, req_struct: TafStruct, rsp_class=None, uid: int = 0, guid: str = "", cookie: str = "", timeout: float = 15.0): """ HTTP POST RPC 调用 Args: service: servant 名 (shopMiddleUI) method: 方法名 (getGoodsInfoV5) req_struct: 请求结构体 (TafStruct) rsp_class: 响应类 uid/guid/cookie: 用于构造 baseinfo (cookie 主要放 Wup body) """ # 1. 构造 Wup 请求体 wup = WupRequest() wup.setServant(service) wup.setFunc(method) wup.setRequestId(1) wup.writeStruct("tReq", req_struct) wup_data = wup.encode() # [4字节长度][wup body] # 2. 构造 baseinfo baseinfo = generate_http_baseinfo(uid, guid, cookie) url = f"https://{CDNWS_HOST}/?baseinfo={baseinfo}" self.logger(f"[HTTP] POST {service}.{method}") self.logger(f"[HTTP] URL: {url[:100]}...") self.logger(f"[HTTP] 发送 body: {len(wup_data)} 字节, hex前60: {wup_data[:60].hex()}") # 3. POST req = urllib.request.Request(url, data=wup_data, method='POST', headers={ 'User-Agent': PC_UA, 'Origin': 'https://zt.huya.com', 'Referer': 'https://zt.huya.com/', 'Content-Type': 'application/octet-stream', 'Accept-Language': 'zh-CN,zh;q=0.9', }) try: with urllib.request.urlopen(req, timeout=timeout) as resp: resp_data = resp.read() # 检测 gzip 压缩 (响应 hex 1f8b 开头) if resp_data[:2] == b'\x1f\x8b': import gzip resp_data = gzip.decompress(resp_data) except Exception as e: self.logger(f"[HTTP] ❌ 请求失败: {type(e).__name__}: {e}") return None self.logger(f"[HTTP] 收到响应: {len(resp_data)} 字节, hex前60: {resp_data[:60].hex()}") # 4. 解析响应 Wup wup_resp = WupResponse() wup_resp.decode(resp_data) if wup_resp.newdata: self.logger(f"[HTTP] 响应 newdata keys: {list(wup_resp.newdata.keys())}") for k, v in wup_resp.newdata.items(): self.logger(f"[HTTP] {k} hex({len(v)}): {v.hex()[:200]}") else: self.logger(f"[HTTP] 响应无 newdata (servant={wup_resp.sServantName})") if rsp_class is None: return wup_resp result = wup_resp.readStruct("tRsp", rsp_class) if result is None: result = wup_resp.readStruct("tResp", rsp_class) return result # ---------- 业务便捷方法 ---------- def get_goods_info(self, uid, guid, cookie, pid, spu_id, sku_id=0, game_id="", source_id="yellowcarlist", scene=7): from .shop_structs import GetGoodsInfoReqV5, GoodsInfoRsp req = GetGoodsInfoReqV5() req.userId = self._build_user(uid, guid, cookie) req.shopAppInfo = self._build_shop_app(source_id, scene) req.pid = pid req.spuId = spu_id req.skuId = sku_id req.gameId = game_id return self.call_rpc("shopMiddleUI", "getGoodsInfoV5", req, GoodsInfoRsp, uid, guid, cookie) def create_order(self, uid, guid, cookie, pid, spu_id, sku_id, item_count=1, source_id="yellowcarlist", game_id="", scene=7, order_type=None): """order_type=None 时自动尝试从 1 到 10 找到有效值""" from .shop_structs import (CreateOrderReqV5, CreateOrderRsp, CreateOrderExtraParam, CreateOrderPromotionParam, CreateOrderAccountParam) # 如果指定了具体值,直接试 types_to_try = [order_type] if order_type is not None else list(range(1, 11)) last_result = None for ot in types_to_try: req = CreateOrderReqV5() req.userId = self._build_user(uid, guid, cookie) req.shopAppInfo = self._build_shop_app(source_id, scene) req.receiveId = 0 req.pid = pid req.spuId = spu_id req.skuId = sku_id req.itemCount = item_count req.gameId = game_id or "0" req.src = scene req.scene = 0 req.sourceId = source_id req.orderType = ot req.extraParam = CreateOrderExtraParam() req.env = self._build_order_env(item_count) req.orderScene = scene req.promotionParam = CreateOrderPromotionParam() req.accountParam = CreateOrderAccountParam() req.bizType = 5 req.gameCategoryId = 507 req.ext = "" result = self.call_rpc("shopMiddleUI", "createOrderV5", req, CreateOrderRsp, uid, guid, cookie) if result is not None: self.logger(f" orderType={ot}: code={result.code} orderId={result.orderId} msg={result.message}") if result.code == 200 and result.orderId: self.logger(f"[✓] 找到有效 orderType={ot}") return result last_result = result else: self.logger(f" orderType={ot}: 无响应") return last_result def pay_order_submit(self, uid, guid, cookie, order_id, pay_type=1, pid=0, source_id="yellowcarlist", scene=7, item_count=1): """发起支付,结构与 WSS HAR 中 payOrderSubmitV5 对齐。""" from .shop_structs import PayOrderRes os = TafOutputStream() os.write_struct_begin(0) os.write_struct(0, self._build_user(uid, guid, cookie)) os.write_struct(1, self._build_shop_app(source_id, scene)) os.write_int64(2, order_id) os.write_string(3, "Zfb" if pay_type == 1 else str(pay_type)) os.write_string(4, "QrCode") callback_url = ( f"https://m-shop.yaoguo.com/index.html#/consumer/paycallback" f"?orderId={order_id}&pid={pid}&sourceId={source_id}" ) os.write_string(5, callback_url) os.write_map(6, self._build_order_env(item_count)) os.write_string(7, "null") os.write_struct_end() # 构造 Wup wup = WupRequest() wup.setServant("shopMiddleUI") wup.setFunc("payOrderSubmitV5") wup.setRequestId(1) wup.newdata["tReq"] = os.get_bytes() wup_data = wup.encode() baseinfo = generate_http_baseinfo(uid, guid, cookie) url = f"https://{CDNWS_HOST}/?baseinfo={baseinfo}" self.logger(f"[HTTP] POST shopMiddleUI.payOrderSubmitV5") self.logger(f"[HTTP] 发送 hex前60: {wup_data[:60].hex()}") req = urllib.request.Request(url, data=wup_data, method='POST', headers={ 'User-Agent': PC_UA, 'Origin': 'https://zt.huya.com', 'Referer': 'https://zt.huya.com/', 'Content-Type': 'application/octet-stream', }) try: with urllib.request.urlopen(req, timeout=15) as resp: resp_data = resp.read() if resp_data[:2] == b'\x1f\x8b': import gzip resp_data = gzip.decompress(resp_data) except Exception as e: self.logger(f"[HTTP] ❌ payOrderSubmitV5 失败: {e}") return None self.logger(f"[HTTP] payOrderSubmitV5 响应 {len(resp_data)} 字节, hex前60: {resp_data[:60].hex()}") wup_resp = WupResponse() wup_resp.decode(resp_data) if wup_resp.newdata: self.logger(f"[HTTP] 响应 keys: {list(wup_resp.newdata.keys())}") for k, v in wup_resp.newdata.items(): self.logger(f"[HTTP] {k} hex({len(v)}): {v.hex()[:200]}") result = wup_resp.readStruct("tRsp", PayOrderRes) if result is None: result = wup_resp.readStruct("tResp", PayOrderRes) return result