From f540dcfc29c57a31b0308d3326099287b716c762 Mon Sep 17 00:00:00 2001 From: yml2213 Date: Thu, 15 Oct 2026 14:56:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(huya):=20=E5=AF=B9=E9=BD=90=E7=A7=AF?= =?UTF-8?q?=E5=88=86=E4=B8=AD=E5=BF=83=E5=BC=80=E9=80=9A=E9=93=BE=E8=B7=AF?= =?UTF-8?q?=EF=BC=882026-10-13=20=E6=8A=93=E5=8C=85=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按 10.13「开通精英宝典/购买幸运币」抓包(m-shop.huya.com/points.html)对齐商城链路: - WSS host 改为 launch.queryHttpDns 动态解析(失败回退抓包实测 host);握手 baseinfo 只带 uid/guid/页面 UA/exp,Origin 与页面同源 - wsLaunch 改为带真实 lUid/sGuid;初始化补上 AUTH(0x0A) → getConfig → UpdateUserExps(0x17),并把 getConfig 下发的版本 map 原样回传(不回传则业务 RPC 无响应) - 补齐新 RPC:getSupplierInfoV5 / acceptHyProtocolV5 / calcOrderPromotion / PlayMallUI.getMyPromotion|queryAllocation / wupui.* / huyauserui.getUserProfile - 下单参数对齐:shopAppInfo.scene=7 与订单 src/orderScene=4 分离、orderType=6、 bizType=5、gameCategoryId=507、extraParam.bizParams 标记 jifencenter、env 仅空点击 序列、支付回调指向 m-shop.huya.com/points.html - 开通链路抽到 services/huya_shop_flow.py,充值任务改为调用它 验证:新增 tests/test_huya_points_shop_protocol.py 与抓包逐字节比对(心跳、版本回传、 wsLaunch/getConfig/下单/支付帧与新 RPC 参数,共 10 条);按 AGENTS.md 做了反向验证 (把 jifencenter 改成 0 后该用例变红,还原后恢复)。ruff format --check 与全量 pytest 通过。 --- core/huya/elite_session.py | 56 ++- core/huya/http_client.py | 156 +++++- core/huya/shop_structs.py | 292 ++++++++++++ core/huya/wss_client.py | 476 ++++++++++++++----- tests/test_huya_points_shop_protocol.py | 391 +++++++++++++++ web/backend/services/huya_runner_recharge.py | 172 ++----- web/backend/services/huya_shop_flow.py | 245 ++++++++++ 7 files changed, 1535 insertions(+), 253 deletions(-) create mode 100644 tests/test_huya_points_shop_protocol.py create mode 100644 web/backend/services/huya_shop_flow.py diff --git a/core/huya/elite_session.py b/core/huya/elite_session.py index 3926db4..1a7ebfe 100644 --- a/core/huya/elite_session.py +++ b/core/huya/elite_session.py @@ -11,9 +11,19 @@ import urllib.parse from collections.abc import Callable from typing import Literal -from .http_client import HuyaHttpClient, generate_http_baseinfo +from .http_client import ( + HuyaHttpClient, + generate_http_baseinfo, + generate_ws_baseinfo, + resolve_wss_host, +) from .web_cookie_fields import missing_web_cookie_fields -from .wss_client import ACTIVITY_WS_HOST, SHOP_BASEINFO, SHOP_WS_HOST, HuyaWssClient +from .wss_client import ( + ACTIVITY_WS_HOST, + POINTS_ORIGIN, + POINTS_PAGE_UA, + HuyaWssClient, +) class HuyaEliteWssSession: @@ -35,7 +45,8 @@ class HuyaEliteWssSession: self.logger = logger or (lambda _message: None) self.http = HuyaHttpClient(logger=self.logger) self.loop = asyncio.new_event_loop() - self.client: HuyaWssClient | None = None + # 构造期必定赋值;提前声明为具体类型,避免每个透传方法都被判定为可选成员。 + self.client: HuyaWssClient self._closed = False if kind == "activity": @@ -45,9 +56,15 @@ class HuyaEliteWssSession: connect_host = host or ACTIVITY_WS_HOST origin = "https://zt.huya.com" else: - baseinfo = SHOP_BASEINFO - connect_host = host or SHOP_WS_HOST - origin = "https://m-shop.yaoguo.com" + # 积分中心通道(2026-10-13 抓包对齐): + # - host 由 launch.queryHttpDns 动态解析(失败回退抓包实测 host) + # - 握手 baseinfo 带真实 uid/guid + h5_/points.html UA,cookie/trace 为空 + # - Origin 与页面同源(m-shop.huya.com) + baseinfo = generate_ws_baseinfo(self.uid, self.guid, POINTS_PAGE_UA) + connect_host = host or resolve_wss_host( + self.uid, self.cookie, self.guid, self.logger + ) + origin = POINTS_ORIGIN self.client = HuyaWssClient(baseinfo=baseinfo, logger=self.logger) try: @@ -92,11 +109,11 @@ class HuyaEliteWssSession: initialized = self.loop.run_until_complete( self.client.initialize_activity(self.uid, self.guid, self.cookie) if kind == "activity" - else self.client.initialize(self.uid, "", self.cookie) + else self.client.initialize(self.uid, self.guid, self.cookie) ) if not initialized: raise RuntimeError(f"虎牙 {kind} WSS 初始化失败") - if kind == "activity" and self.client._launch_guid: + if self.client._launch_guid: # wsLaunch 的 sGuid 是当前连接的真实会话值,供后续业务 Cookie # 与 HTTP baseinfo 继续复用,避免沿用登录时的旧 guid。 self.cookie = self.client._cookie_with_guid( @@ -233,5 +250,28 @@ class HuyaEliteWssSession: def query_user_order_list(self, **kwargs): return self._run(self.client.query_user_order_list(**kwargs)) + # ---- 积分中心链路新增 RPC(2026-10-13 抓包) ---- + + def get_supplier_info(self, **kwargs): + return self._run(self.client.get_supplier_info(**kwargs)) + + def accept_hy_protocol(self, **kwargs): + return self._run(self.client.accept_hy_protocol(**kwargs)) + + def calc_order_promotion(self, **kwargs): + return self._run(self.client.calc_order_promotion(**kwargs)) + + def play_mall_query_allocation(self, **kwargs): + return self._run(self.client.play_mall_query_allocation(**kwargs)) + + def play_mall_get_my_promotion(self, **kwargs): + return self._run(self.client.play_mall_get_my_promotion(**kwargs)) + + def get_user_profile(self, **kwargs): + return self._run(self.client.get_user_profile(**kwargs)) + + def get_follow_wechat_status(self, **kwargs): + return self._run(self.client.get_follow_wechat_status(**kwargs)) + __all__ = ["HuyaEliteWssSession"] diff --git a/core/huya/http_client.py b/core/huya/http_client.py index b827b0a..1915937 100644 --- a/core/huya/http_client.py +++ b/core/huya/http_client.py @@ -11,6 +11,8 @@ import base64 import hashlib import json import random +import re +import time import urllib.parse import urllib.request from collections.abc import Callable @@ -121,6 +123,32 @@ def generate_http_baseinfo( return urllib.parse.quote(b64, safe="") +def generate_ws_baseinfo( + uid: int, + guid: str, + ua: str, + exp: str = "", +) -> str: + """构造 WSS 连接 URL 的 baseinfo(返回未转义的 base64)。 + + 2026-10-13 积分中心抓包实证:握手 baseinfo 只有 + lUid/sGuid/sUA/sAppSrc/sExp 有值,cookie 与 traceId 都是空的; + ``sExp`` 是 getConfig 下发的版本串(实测 ``58664.107263``)。 + """ + info = WSConnectParaInfo() + info.lUid = int(uid or 0) + info.sGuid = guid or "" + info.sUA = ua + info.sAppSrc = "HUYA&ZH&2052" + info.sExp = exp or "" + info.sCookie = "" + info.sTraceId = "" + + os = TafOutputStream() + info.write_to(os) + return base64.b64encode(os.get_bytes()).decode("ascii") + + class HuyaHttpClient: """虎牙 HTTP POST RPC 客户端""" @@ -261,6 +289,9 @@ class HuyaHttpClient: guid: str = "", cookie: str = "", timeout: float = 15.0, + request_id: int = 1, + origin: str = "https://zt.huya.com", + referer: str = "https://zt.huya.com/", ): """ HTTP POST RPC 调用 @@ -271,12 +302,14 @@ class HuyaHttpClient: req_struct: 请求结构体 (TafStruct) rsp_class: 响应类 uid/guid/cookie: 用于构造 baseinfo,业务请求体也会按各接口需要携带 + request_id: WUP iRequestId(launch.queryHttpDns 固定 -1) + origin/referer: 部分接口(积分中心页面)要求与页面同源 """ # 1. 构造 Wup 请求体 wup = WupRequest() wup.setServant(service) wup.setFunc(method) - wup.setRequestId(1) + wup.setRequestId(request_id) wup.writeStruct("tReq", req_struct) wup_data = wup.encode() # [4字节长度][wup body] @@ -297,8 +330,8 @@ class HuyaHttpClient: method="POST", headers={ "User-Agent": PC_UA, - "Origin": "https://zt.huya.com", - "Referer": "https://zt.huya.com/", + "Origin": origin, + "Referer": referer, "Content-Type": "application/octet-stream", "Accept-Language": "zh-CN,zh;q=0.9", }, @@ -348,6 +381,39 @@ class HuyaHttpClient: # ---------- 业务便捷方法 ---------- + def query_http_dns( + self, + uid: int, + cookie: str, + guid: str = "", + ua: str = HTTP_HUYA_UA, + domains: list[str] | None = None, + timeout: float = 10.0, + ) -> list[str]: + """launch.queryHttpDns — 换取 WSS host 列表(失败返回空列表)。""" + req = QueryHttpDnsReq() + req.uid = int(uid or 0) + req.ua = ua + req.domains = list(domains or [HTTP_DNS_DOMAIN]) + resp = self.call_rpc( + "launch", + "queryHttpDns", + req, + None, + uid=uid, + guid=guid, + cookie=cookie, + timeout=timeout, + request_id=-1, + origin="https://m-shop.huya.com", + referer="https://m-shop.huya.com/points.html", + ) + if resp is None: + return [] + newdata = getattr(resp, "newdata", None) or {} + payload = newdata.get("tRsp") or newdata.get("tResp") or b"" + return _extract_ws_hosts(payload) + def get_act_info( self, act_id: int, @@ -1189,5 +1255,89 @@ def _self_check(): assert empty_user.sCookie == "" +# ============================================================ +# launch.queryHttpDns:动态解析 WSS host +# +# 2026-10-13「精英宝典」抓包确认:m-shop.huya.com 页面先用 HTTP cdnws 调 +# launch.queryHttpDns(iRequestId 固定 -1)换取 host 列表,再连 WSS。 +# 因此 host 不应长期写死;解析失败时回退到抓包实测 host。 +# ============================================================ + +HTTP_DNS_DOMAIN = "cdnws.api.huya.com" +_WSS_HOST_RE = re.compile(rb"[a-z0-9]{6,}-ws\.va\.huya\.com") +#: 解析成功后的缓存时长(响应实测 ttl 1296000s,这里保守缓存)。 +DNS_CACHE_TTL = 600.0 +#: 解析失败后的冷却时间,避免每个任务都打一次无用的 DNS 请求。 +DNS_FAILURE_COOLDOWN = 30.0 +_dns_cache: dict[str, tuple[float, list[str]]] = {} + + +class QueryHttpDnsReq(TafStruct): + """launch.queryHttpDns 请求(2026-10-13 抓包逐字段)。 + + tag0 uid, tag1 UA, tag2 域名列表, tag3 appSrc, tag4 "", tag5 0, tag6 1 + """ + + def __init__(self): + self.uid: int = 0 # tag 0 + self.ua: str = "" # tag 1 + self.domains: list[str] = [] # tag 2 + self.appSrc: str = "HUYA&ZH&2052" # tag 3 + self.blank4: str = "" # tag 4 + self.flag5: int = 0 # tag 5 + self.flag6: int = 1 # tag 6 + + def write_to(self, os: TafOutputStream): + os.write_int64(0, self.uid) + os.write_string(1, self.ua) + os.write_list(2, self.domains) + os.write_string(3, self.appSrc) + os.write_string(4, self.blank4) + os.write_int32(5, self.flag5) + os.write_int32(6, self.flag6) + + def read_from(self, ins: TafInputStream): + pass + + +def _extract_ws_hosts(payload: bytes) -> list[str]: + """从 queryHttpDns 响应里按出现顺序取出 WSS host(去重)。""" + hosts: list[str] = [] + for match in _WSS_HOST_RE.findall(bytes(payload or b"")): + host = match.decode("ascii", errors="ignore") + if host and host not in hosts: + hosts.append(host) + return hosts + + +def resolve_wss_host( + uid: int, + cookie: str, + guid: str = "", + logger: Callable[[str], None] | None = None, +) -> str: + """解析积分中心通道的 WSS host:queryHttpDns + TTL 缓存 + 抓包 host 兜底。""" + from .wss_client import SHOP_POINTS_WS_HOST + + log = logger or (lambda _message: None) + now = time.monotonic() + cached = _dns_cache.get(HTTP_DNS_DOMAIN) + if cached and now < cached[0]: + hosts = cached[1] + else: + hosts = [] + try: + hosts = HuyaHttpClient(logger=log).query_http_dns(uid, cookie, guid=guid) + except Exception: # noqa: BLE001 外部接口失败一律回退默认 host + hosts = [] + ttl = DNS_CACHE_TTL if hosts else DNS_FAILURE_COOLDOWN + _dns_cache[HTTP_DNS_DOMAIN] = (now + ttl, hosts) + if not hosts: + log("[WSS] queryHttpDns 无结果,使用抓包实测 host") + return SHOP_POINTS_WS_HOST + log(f"[WSS] queryHttpDns 解析 host={hosts[0]}(候选 {len(hosts)} 个)") + return hosts[0] + + if __name__ == "__main__": _self_check() diff --git a/core/huya/shop_structs.py b/core/huya/shop_structs.py index 4d47c51..fc3247f 100644 --- a/core/huya/shop_structs.py +++ b/core/huya/shop_structs.py @@ -5,6 +5,8 @@ 来源:m-shop.yaoguo.com 的 jce/ShopFacade.js、api/orderui.ts、api/mall/PlayMallNewHome.ts """ +from typing import Any + from .taf_protocol import TafInputStream, TafOutputStream, TafStruct, TafType @@ -1094,3 +1096,293 @@ class PayOrderRes(TafStruct): "pay_url": self.payUrl, "amount": self.amount, } + + +# ============================================================ +# 积分中心(m-shop.huya.com/points.html)新增 RPC +# +# 来源:2026-10-13「开通精英宝典 / 购买幸运币」WSS 抓包逐字段解出。 +# 浏览器实际链路顺序: +# getGoodsInfoV5 → getSupplierInfoV5 → listPayChannelV5 → checkHyProtocolV5 +# → acceptHyProtocolV5 → calcOrderPromotion → checkUserBuyAuth +# → createOrderV5 → payOrderSubmitV5 → orderDetailV5(轮询) +# 这些接口的响应层次较深且随商品变化,统一用 ShopRawRsp 暴露通用解码结果, +# 不凭空猜测未确认的字段名。 +# ============================================================ + + +class ShopRawRsp: + """未逐字段建模的商城响应:暴露 code/message 与通用解码后的原始结构。""" + + def __init__(self, code: int = 0, message: str = "", payload: dict | None = None): + self.code = code + self.message = message + self.payload = payload or {} + + def value(self, *path): + """按通用解码的 tag 路径取值,例如 value("tag2", "tag0", "tag1")。""" + node: Any = self.payload + for key in path: + if not isinstance(node, dict): + return None + node = node.get(key) + return node + + def to_dict(self) -> dict: + return {"code": self.code, "message": self.message, "payload": self.payload} + + +class PlayMallAppInfo(TafStruct): + """PlayMallUI 系接口的应用信息。 + + 与 ShopAppInfo 字段不同(抓包实证): + tag0 sAppId, tag1 渠道号(1001), tag2 0, tag3 "", tag5 scene(7), + tag6 sourceId, tag7 "" + """ + + def __init__(self): + self.sAppId: str = "huya" # tag 0 + self.channelId: int = 1001 # tag 1 抓包固定 1001 + self.flag2: int = 0 # tag 2 抓包固定 0 + self.blank3: str = "" # tag 3 抓包为空串 + self.scene: int = 7 # tag 5 抓包固定 7 + self.sourceId: str = "yellowcarlist" # tag 6 + self.blank7: str = "" # tag 7 抓包为空串 + + def write_to(self, os: TafOutputStream): + os.write_string(0, self.sAppId) + os.write_int32(1, self.channelId) + os.write_int32(2, self.flag2) + os.write_string(3, self.blank3) + os.write_int32(5, self.scene) + os.write_string(6, self.sourceId) + os.write_string(7, self.blank7) + + def read_from(self, ins: TafInputStream): + pass + + +class GetSupplierInfoReqV5(ShopAppRequest): + """shopMiddleUI.getSupplierInfoV5 请求。""" + + def __init__(self): + super().__init__() + self.supplierId: int = 0 # tag 2 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_struct(1, self.shopAppInfo) + os.write_int64(2, self.supplierId) + + +class AcceptHyProtocolReq(ShopAppRequest): + """shopMiddleUI.acceptHyProtocolV5 请求(同意虎牙商城协议)。""" + + def __init__(self): + super().__init__() + self.protocolVersion: int = 1 # tag 2 抓包固定 1 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_struct(1, self.shopAppInfo) + os.write_int32(2, self.protocolVersion) + + +class CalcOrderPromotionExtra(TafStruct): + """calcOrderPromotion tag12 子结构(抓包全零/空)。""" + + def __init__(self): + self.flag0: int = 0 # tag 0 + self.flag1: int = 0 # tag 1 + self.flag2: int = 0 # tag 2 + self.ids: list = [] # tag 3 + + def write_to(self, os: TafOutputStream): + os.write_int32(0, self.flag0) + os.write_int32(1, self.flag1) + os.write_int32(2, self.flag2) + os.write_list(3, self.ids) + + def read_from(self, ins: TafInputStream): + pass + + +class CalcOrderPromotionReqV5(ShopAppRequest): + """shopMiddleUI.calcOrderPromotion 请求。 + + tag7/tag8/tag9/tag10 在抓包中恒为 1/1/1/0,语义未确认,按抓包原值写出。 + tag2 与 tag14 都是 spuId 去掉 ``hy-`` 前缀后的数字。 + """ + + def __init__(self): + super().__init__() + self.spuNum: int = 0 # tag 2 + self.skuId: int = 0 # tag 3 + self.itemCount: int = 1 # tag 4 + self.pid: int = 0 # tag 5 + self.couponUserIds: list = [] # tag 6 + self.flag7: int = 1 # tag 7 抓包固定 1 + self.flag8: int = 1 # tag 8 抓包固定 1 + self.flag9: int = 1 # tag 9 抓包固定 1 + self.flag10: int = 0 # tag 10 抓包固定 0 + self.extra: CalcOrderPromotionExtra | None = None # tag 12 + self.flag13: int = 0 # tag 13 + self.spuNum2: int = 0 # tag 14 与 tag2 同值 + self.gameId: int = 0 # tag 15 游戏 ID(和平精英 9815) + self.list16: list = [] # tag 16 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_struct(1, self.shopAppInfo) + os.write_int64(2, self.spuNum) + os.write_int64(3, self.skuId) + os.write_int32(4, self.itemCount) + os.write_int64(5, self.pid) + os.write_list(6, self.couponUserIds) + os.write_int32(7, self.flag7) + os.write_int32(8, self.flag8) + os.write_int32(9, self.flag9) + os.write_int32(10, self.flag10) + os.write_struct(12, self.extra or CalcOrderPromotionExtra()) + os.write_int32(13, self.flag13) + os.write_int64(14, self.spuNum2) + os.write_int64(15, self.gameId) + os.write_list(16, self.list16) + + def read_from(self, ins: TafInputStream): + pass + + +class PlayMallQueryAllocationReq(TafStruct): + """PlayMallUI.queryAllocation 请求(积分中心页面配额查询)。""" + + def __init__(self): + self.userId = UserId() # tag 0 + self.appInfo = PlayMallAppInfo() # tag 1 + self.pageCode: str = "" # tag 2 + self.blank3: str = "" # tag 3 + self.flag4: int = 0 # tag 4 + self.flag5: int = 1 # tag 5 抓包固定 1 + self.flag6: int = 24 # tag 6 抓包固定 24 + self.blank7: str = "" # tag 7 + self.data8: bytes = b"" # tag 8 空字节数组 + self.flag9: int = 0 # tag 9 + self.flag10: int = 0 # tag 10 + self.flags11: list[int] = [6, 19] # tag 11 抓包固定 [6, 19] + self.flag12: int = 0 # tag 12 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_struct(1, self.appInfo) + os.write_string(2, self.pageCode) + os.write_string(3, self.blank3) + os.write_int32(4, self.flag4) + os.write_int32(5, self.flag5) + os.write_int32(6, self.flag6) + os.write_string(7, self.blank7) + os.write_bytes(8, self.data8) + os.write_int32(9, self.flag9) + os.write_int32(10, self.flag10) + os.write_list(11, self.flags11) + os.write_int32(12, self.flag12) + + def read_from(self, ins: TafInputStream): + pass + + +class PromotionGoodsKey(TafStruct): + """getMyPromotion tag6 子结构(供应商 + 商品 + 价格)。""" + + def __init__(self): + self.supplierId: int = 0 # tag 0 + self.spuNum: int = 0 # tag 1 + self.skuId: int = 0 # tag 2 + self.price: int = 0 # tag 3 + self.flag4: int = 1 # tag 4 抓包固定 1 + self.list5: list = [] # tag 5 + self.gameId: int = 0 # tag 6 + self.spuNum2: int = 0 # tag 7 与 tag1 同值 + + def write_to(self, os: TafOutputStream): + os.write_int64(0, self.supplierId) + os.write_int64(1, self.spuNum) + os.write_int64(2, self.skuId) + os.write_int64(3, self.price) + os.write_int32(4, self.flag4) + os.write_list(5, self.list5) + os.write_int64(6, self.gameId) + os.write_int64(7, self.spuNum2) + + def read_from(self, ins: TafInputStream): + pass + + +class PlayMallGetMyPromotionReq(TafStruct): + """PlayMallUI.getMyPromotion 请求(查询用户可用返利/促销)。""" + + def __init__(self): + self.userId = UserId() # tag 0 + self.appInfo = PlayMallAppInfo() # tag 1 + self.flag2: int = 1 # tag 2 抓包固定 1 + self.flag3: int = 1 # tag 3 抓包固定 1 + self.flag4: int = 10 # tag 4 抓包固定 10 + self.flag5: int = 0 # tag 5 + self.goods: PromotionGoodsKey | None = None # tag 6 + self.list7: list = [] # tag 7 + self.scene: str = "shop" # tag 8 抓包固定 "shop" + self.blank9: str = "" # tag 9 + self.list10: list = [] # tag 10 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_struct(1, self.appInfo) + os.write_int32(2, self.flag2) + os.write_int32(3, self.flag3) + os.write_int32(4, self.flag4) + os.write_int32(5, self.flag5) + os.write_struct(6, self.goods or PromotionGoodsKey()) + os.write_list(7, self.list7) + os.write_string(8, self.scene) + os.write_string(9, self.blank9) + os.write_list(10, self.list10) + + def read_from(self, ins: TafInputStream): + pass + + +class GetUserProfileReq(TafStruct): + """huyauserui.getUserProfile 请求(tag1 为要查询的 uid)。""" + + def __init__(self): + self.userId = UserId() # tag 0 + self.targetUid: int = 0 # tag 1 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_int64(1, self.targetUid) + + def read_from(self, ins: TafInputStream): + pass + + +class FollowWeChatStatusReq(TafStruct): + """wupui.getUserFollowWeChatOfficialStatus 请求(tag1 抓包固定 1)。""" + + def __init__(self): + self.userId = UserId() # tag 0 + self.flag1: int = 1 # tag 1 抓包固定 1 + + def write_to(self, os: TafOutputStream): + os.write_struct(0, self.userId) + os.write_int32(1, self.flag1) + + def read_from(self, ins: TafInputStream): + pass + + +def shop_spu_number(spu_id: str) -> int: + """把商品 ID(``hy-8328015``)转成接口需要的数字形式(``8328015``)。""" + text = str(spu_id or "").strip() + if "-" in text: + text = text.rsplit("-", 1)[-1] + return int(text) if text.isdigit() else 0 diff --git a/core/huya/wss_client.py b/core/huya/wss_client.py index 511c385..920d691 100644 --- a/core/huya/wss_client.py +++ b/core/huya/wss_client.py @@ -19,7 +19,6 @@ import asyncio import random import re import struct -import time from collections import deque from collections.abc import Callable from typing import Any, cast @@ -43,6 +42,35 @@ WSS_BIZ_UA = "web&1.0.0&huya" WSS_COOKIE_UA = "webh5&0.0.1&websocket&&diypc_52775" WSS_SHOP_SCENE = 4 +# ============================================================ +# 积分中心页面上下文(m-shop.huya.com/points.html) +# +# 2026-10-13「开通精英宝典 / 购买幸运币」抓包实证:servant 仍是 shopMiddleUI, +# 但页面 UA / Origin / Referer / 下单参数与 7.4 的 m-shop.yaoguo.com 通道不同: +# - wsLaunch 带真实 lUid + sGuid,UA 为 h5_/points.html +# - 先 VerifyCookie(0x0A) 再 getConfig,最后用 getConfig 的版本 map 回传(0x17) +# - shopAppInfo.scene = 7,而 createOrderV5 的 src/orderScene = 4 +# - 下单 extraParam.bizParams 标记积分中心来源,env 只有空 user_click_seq +# ============================================================ +POINTS_PAGE_UA = "webh5&0.0.1&websocket&&h5_/points.html" +POINTS_ORIGIN = "https://m-shop.huya.com" +POINTS_REFERER = ( + "https://m-shop.huya.com/points.html" + "?pagecode=heping_baodian_credit_center_page&sourceId=yellowcarlist" +) +POINTS_PAGE_CODE = "heping_baodian_credit_center_page" +POINTS_PAY_CALLBACK = "https://m-shop.huya.com/points.html#/consumer/paycallback" +# wsLaunch 响应里的 host 是动态的(launch.queryHttpDns);此为抓包实测值兼兜底。 +SHOP_POINTS_WS_HOST = "d35bf373-ws.va.huya.com" +SUPPLIER_ID_YELLOW_CAR = 87401 +GAME_CATEGORY_ID_HUYA = 507 +ORDER_BIZ_TYPE = 5 +SHOP_APP_SCENE = 7 +ORDER_SCENE = 4 +PEACE_ELITE_GAME_ID = 9815 +# createOrderV5 的 extraParam.bizParams:标记「积分中心」来源,缺了会走成普通商城单。 +JIFENCENTER_BIZ_PARAMS = '{ "jifencenter": 1 }' + class _ActivityConfigReq(TafStruct): def __init__(self, user): @@ -67,6 +95,12 @@ SEQ_CONFIRM = 0x1D000002 SEQ_BUSINESS = 0x1D000106 # 业务 RPC (HAR 7.4 实证:业务帧固定使用该 seq) SEQ_ACTIVITY_WSLAUNCH = 0x1D000100 SEQ_ACTIVITY_BIZ = 0x1D000109 +# 积分中心通道业务帧(2026-10-13 抓包:AUTH/getConfig/业务统一 0x1d000107, +# 仅 createOrderV5 / payOrderSubmitV5 为 0x1d000108)。 +SEQ_POINTS_BIZ = 0x1D000107 +SEQ_POINTS_ORDER = 0x1D000108 +# 积分中心通道里用 0x1d000108 的两帧 +POINTS_ORDER_METHODS = frozenset({"createOrderV5", "payOrderSubmitV5"}) class WssCommand: @@ -118,13 +152,20 @@ class HuyaWssClient: self._launch_guid = "" self._launch_ip = "" self._activity_mode = False + # 积分中心通道:0x10 组播 + wsLaunch(带 uid) + AUTH + getConfig + 版本回传 + self._points_mode = False + # getConfig 下发的版本 map,UpdateUserExps(0x17) 必须原样回传 + self._config_versions: dict[str, str] = {} - def _next_biz_seq(self) -> int: + def _next_biz_seq(self, order_frame: bool = False) -> int: """业务 RPC 的 frame seq。 - 浏览器在商城 WSS 上连续发送多个业务 RPC 时,frame seq 都保持 - 0x1d000106;真正区分请求依赖 WUP requestId。 + 浏览器在商城 WSS 上连续发送多个业务 RPC 时,frame seq 基本保持固定值; + 真正区分请求依赖 WUP requestId。积分中心通道里 createOrderV5 / + payOrderSubmitV5 两帧用 0x1d000108,其余用 0x1d000107(抓包实证)。 """ + if self._points_mode: + return SEQ_POINTS_ORDER if order_frame else SEQ_POINTS_BIZ return SEQ_ACTIVITY_BIZ if self._activity_mode else SEQ_BUSINESS def _next_wup_req_id(self) -> int: @@ -231,8 +272,8 @@ class HuyaWssClient: return user @staticmethod - def _build_shop_app(source_id: str = "yellowcarlist", scene: int = WSS_SHOP_SCENE): - """构造 WSS 业务 ShopAppInfo""" + def _build_shop_app(source_id: str = "yellowcarlist", scene: int = SHOP_APP_SCENE): + """构造 WSS 业务 ShopAppInfo(积分中心抓包 scene 为 7)""" from .shop_structs import ShopAppInfo info = ShopAppInfo() @@ -243,13 +284,37 @@ class HuyaWssClient: return info @staticmethod - def _build_order_env(item_count: int = 1): - """构造下单/支付环境参数""" - 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 _build_play_mall_app(source_id: str = "yellowcarlist"): + """构造 PlayMallUI 系接口的应用信息(字段序与 ShopAppInfo 不同)""" + from .shop_structs import PlayMallAppInfo + + info = PlayMallAppInfo() + info.sourceId = source_id + return info + + @staticmethod + def _build_order_env(): + """下单/支付环境参数。 + + 2026-10-13 积分中心抓包:仅一个空点击序列,没有 7.4 那版坐标数组与 input_1。 + """ + return {"user_click_seq": "[]"} + + @staticmethod + def _build_config_user(uid: int, guid: str, cookie: str): + """getConfig 的 UserId:带真实 uid/guid/cookie,UA 用页面 UA。""" + from .shop_structs import UserId + + user = UserId() + user.lUid = int(uid or 0) + user.sGuid = guid or "" + user.sToken = "" + user.sHuYaUA = POINTS_PAGE_UA + user.sCookie = HuyaWssClient._normalize_biz_cookie(cookie) + user.iTokenType = 0 + user.sDeviceInfo = "" + user.sQIMEI = "" + return user async def connect( self, @@ -371,17 +436,22 @@ class HuyaWssClient: await self.ws.send(msg.encode()) async def initialize(self, uid: int, guid: str, cookie: str): - """商城端点初始化: heartbeat → wsLaunch → getConfig → confirm + """商城(积分中心)端点初始化,对齐 2026-10-13 抓包帧序。 - 商城 wsLaunch 无 lUid/sGuid (匿名), tReq: - tag0 lUid=0, tag1 sGuid="", tag2 sUA="webh5&0.0.1&websocket&&h5_/index.html", - tag3 sAppSrc="HUYA&ZH&2052", tag4 tDeviceInfo={5空串} + RegisterGroup(0x10, live:0) + → launch.wsLaunch(带真实 lUid + sGuid,UA=h5_/points.html) + → VerifyCookie(0x0A,页面 UA) + → mobileui.getConfig(带真实 uid/guid/cookie) + → UpdateUserExps(0x17),回传 getConfig 下发的版本 map + + getConfig 之后浏览器还会补发一次 RegisterGroup;业务 RPC 期间用 0x14 心跳维持。 """ - self.logger("[初始化] 开始 WSS 初始化流程 (商城端点)...") + self.logger("[初始化] 开始 WSS 初始化流程 (积分中心端点)...") + self._points_mode = True await self.send_heartbeat() - launch_rsp = await self.call_ws_launch_shop() + launch_rsp = await self.call_ws_launch_shop(uid, guid) if launch_rsp is None: self.logger("[✗] wsLaunch 无响应,初始化失败") return False @@ -389,17 +459,20 @@ class HuyaWssClient: f"[初始化] wsLaunch OK guid={self._launch_guid} ip={self._launch_ip}" ) - config_rsp = await self.call_get_config_shop() - self.logger( - f"[初始化] getConfig {'OK' if config_rsp is not None else '无响应(可继续)'}" + # wsLaunch 为当前连接签发新的 sGuid:AUTH、getConfig 与后续业务必须复用它。 + if self._launch_guid: + guid = self._launch_guid + cookie = self._cookie_with_guid(cookie, guid) + + await self.send_auth( + uid, cookie, sequence=SEQ_BUSINESS, guid=guid, ua=POINTS_PAGE_UA ) - if self._launch_guid: - await self.send_register(self._launch_guid) + await self.call_get_config_shop(uid=uid, guid=guid, cookie=cookie) - await self.send_confirm() + await self.send_confirm(self._config_versions) - await asyncio.sleep(0.3) + await asyncio.sleep(0.2) self.logger("[初始化] 完成 ✓") return True @@ -488,15 +561,21 @@ class HuyaWssClient: user.sCookie = HuyaWssClient._normalize_biz_cookie(cookie) return user - async def call_ws_launch_shop(self, timeout: float = 10.0): - """商城版 wsLaunch (匿名, 无 lUid/sGuid, 与 conn4 格式一致)""" - ua = "webh5&0.0.1&websocket&&h5_/index.html" + async def call_ws_launch_shop( + self, uid: int = 0, guid: str = "", timeout: float = 10.0 + ): + """商城 wsLaunch。 + + 2026-10-13 积分中心抓包:带真实 lUid 与 sGuid(不再是匿名), + UA 为页面 UA(h5_/points.html),与活动通道的字段布局一致。 + """ + ua = POINTS_PAGE_UA app_src = "HUYA&ZH&2052" os = TafOutputStream() os.write_struct_begin(0) - os.write_int64(0, 0) # lUid = 0 - os.write_string(1, "") # sGuid = "" + os.write_int64(0, int(uid or 0)) # lUid = 真实 uid + os.write_string(1, guid or "") # sGuid = 真实 guid os.write_string(2, ua) # sUA os.write_string(3, app_src) # sAppSrc os.write_struct_begin(4) # tDeviceInfo @@ -514,7 +593,7 @@ class HuyaWssClient: wup_data = wup.encode() body = self._encode_rpc_body(wup_data) - seq = SEQ_WSLAUNCH + seq = SEQ_ACTIVITY_WSLAUNCH msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=seq, body=body) future = asyncio.Future() self.rpc_queue.append(future) @@ -611,6 +690,7 @@ class HuyaWssClient: cookie: str, sequence: int = SEQ_WSLAUNCH, guid: str = "", + ua: str = "", ): """cmd 0x0a AUTH — 对齐 9.1 抓包(828 活动帧)。 @@ -624,12 +704,14 @@ class HuyaWssClient: tag5 STRING1 = "HUYA&ZH&2052" tag6 STRING1 = "" += TAIL_BYTES(tag2 ZERO/tag3 ""/tag4 ZERO/tag5 ZERO/tag6 "") + + ``ua`` 可覆盖:积分中心页面为 ``h5_/points.html``(2026-10-13 抓包)。 """ os = TafOutputStream() - if self._activity_mode: + if self._activity_mode or self._points_mode: os.write_head(3, TafType.ZERO) os.write_int64(0, int(uid or 0)) - os.write_string(1, WSS_COOKIE_UA) + os.write_string(1, ua or WSS_COOKIE_UA) os.write_string(2, HuyaWssClient._normalize_biz_cookie(cookie)) guid_match = re.search(r"(?:^|;\s*)guid=([^;]+)", cookie or "") auth_guid = ( @@ -657,61 +739,34 @@ class HuyaWssClient: ) ) - async def call_get_config_shop(self, timeout: float = 10.0): - """商城版 mobileui.getConfig + async def call_get_config_shop( + self, uid: int = 0, guid: str = "", cookie: str = "", timeout: float = 10.0 + ): + """商城/积分中心 mobileui.getConfig。 - tReq 结构 (HAR 实证): - tag0: UserId {lUid=0, sGuid="", sUA="", sHuYaUA="webh5&0.0.1&websocket&&h5_/index.html", - sToken="", iTokenType=0, sDeviceInfo="", sCookie=""} + tReq 结构 (2026-10-13 抓包实证): + tag0: UserId {lUid=真实uid, sGuid=真实guid, sHuYaUA=h5_/points.html, + sCookie=完整 Cookie} tag1: 空Map tag2: "huya" (sAppId) tag3: 空List + + 响应 tag1 是版本 map(实测 ``{"58664":"107263"}``),必须缓存下来, + 因为 UpdateUserExps(0x17) 要把它原样回传。 """ - ua = "webh5&0.0.1&websocket&&h5_/index.html" - - os = TafOutputStream() - os.write_struct_begin(0) - # tag0: UserId (匿名) - os.write_struct_begin(0) - os.write_int64(0, 0) # lUid = 0 - os.write_string(1, "") # sGuid - os.write_string(2, "") # sUA - os.write_string(3, ua) # sHuYaUA - os.write_string(4, "") # sToken - os.write_int32(5, 0) # iTokenType - os.write_string(6, "") # sDeviceInfo - os.write_string(7, "") # sCookie - os.write_struct_end() - os.write_map(1, {}) # tag1: 空Map - os.write_string(2, "huya") # tag2: sAppId - os.write_head(3, TafType.LIST) # tag3: 空List - os.write_int32(0, 0) - os.write_struct_end() - - wup = WupRequest() - wup.setServant("mobileui") - wup.setFunc("getConfig") - wup.setRequestId(7) - wup.iTimeout = 0 - wup.newdata["tReq"] = os.get_bytes() - wup_data = wup.encode() - body = self._encode_rpc_body(wup_data) - - seq = SEQ_GETCONFIG - msg = WssMessage(command=WssCommand.RPC_REQUEST, sequence=seq, body=body) - future = asyncio.Future() - self.rpc_queue.append(future) - self.logger(format_wss_log(body, WssCommand.RPC_REQUEST, seq, "发")) - await self.ws.send(msg.encode()) - - try: - body = await asyncio.wait_for(future, timeout) - except TimeoutError: - if future in self.rpc_queue: - self.rpc_queue.remove(future) + user = self._build_config_user(uid, guid, cookie) + req = _ActivityConfigReq(user) + body = await self.call_rpc("mobileui", "getConfig", req, None, timeout=timeout) + if body is None: self.logger("[✗] getConfig 超时") return None - + payload = self._decode_rsp_dict(body) + versions = payload.get("tag1") + if isinstance(versions, dict): + self._config_versions = { + str(key): str(value) for key, value in versions.items() + } + self.logger(f"[初始化] getConfig 下发版本 {self._config_versions or '{}'}") return body async def send_register(self, guid_from_launch: str): @@ -738,10 +793,14 @@ class HuyaWssClient: self.logger(format_wss_log(body, WssCommand.REGISTER, SEQ_REGISTER, "发")) await self.ws.send(msg.encode()) - async def send_confirm(self): - """cmd 0x17 CONFIRM_SEND — body = 空Map(tag0) + TAIL""" + async def send_confirm(self, version_map: dict[str, str] | None = None): + """cmd 0x17 UpdateUserExps — body = 版本 map(tag0) + TAIL + + 2026-10-13 抓包实证:body 是 getConfig 下发的版本 map + (``{"58664":"107263"}``),不是空 map;不回传会导致业务 RPC 无响应。 + """ os = TafOutputStream() - os.write_map(0, {}) + os.write_map(0, version_map or {}) body = os.get_bytes() + TAIL_BYTES msg = WssMessage( command=WssCommand.CONFIRM_SEND, sequence=SEQ_CONFIRM, body=body @@ -749,6 +808,62 @@ class HuyaWssClient: self.logger(format_wss_log(body, WssCommand.CONFIRM_SEND, SEQ_CONFIRM, "发")) await self.ws.send(msg.encode()) + @staticmethod + def _decode_rsp_dict(body: bytes) -> dict: + """把 RPC 响应的 tRsp 解成通用 dict(未建模的接口用它取字段)。""" + try: + wup_resp = WupResponse() + wup_resp.decode(HuyaWssClient._extract_wup(body)) + except Exception: # noqa: BLE001 响应解析失败按空结构处理 + return {} + data = wup_resp.newdata.get("tRsp") or wup_resp.newdata.get("tResp") + if not isinstance(data, bytes) or not data: + return {} + ins = TafInputStream(data) + try: + _tag, dtype = ins.peek_head() + if dtype != TafType.STRUCT_BEGIN: + return {} + ins.read_head() + return _decode_taf_struct(ins) + except Exception: # noqa: BLE001 外部接口与任务边界需要保留宽泛异常兜底 + return {} + + @classmethod + def _raw_rsp_from_body(cls, body: bytes): + """响应 → ShopRawRsp(code/message + 通用解码结构)。""" + from .shop_structs import ShopRawRsp + + payload = cls._decode_rsp_dict(body) + code = 0 + message = "" + head = payload.get("tag0") + if isinstance(head, int): + # 扁平响应(acceptHyProtocolV5 / createOrderV5 等) + code = int(head) + if isinstance(payload.get("tag1"), str): + message = payload["tag1"] + elif isinstance(head, dict): + # 嵌套响应(PlayMallUI.getMyPromotion 的 tag0.tag0/tag0.tag1) + if isinstance(head.get("tag0"), int): + code = int(head["tag0"]) + if isinstance(head.get("tag1"), str): + message = head["tag1"] + return ShopRawRsp(code=code, message=message, payload=payload) + + async def call_rpc_raw( + self, + service: str, + method: str, + req_struct: TafStruct, + timeout: float = 15.0, + ): + """未逐字段建模的 RPC:返回 ShopRawRsp,取不到响应时返回 None。""" + body = await self.call_rpc(service, method, req_struct, None, timeout=timeout) + if body is None: + return None + return self._raw_rsp_from_body(body) + async def call_rpc( self, service: str, @@ -757,7 +872,7 @@ class HuyaWssClient: rsp_class=None, timeout: float = 10.0, ): - seq = self._next_biz_seq() + seq = self._next_biz_seq(method in POINTS_ORDER_METHODS) wup = WupRequest() wup.setServant(service) @@ -820,13 +935,13 @@ class HuyaWssClient: sku_id: int = 0, game_id: str = "", source_id: str = "yellowcarlist", - scene: int = WSS_SHOP_SCENE, + app_scene: int = SHOP_APP_SCENE, ): from .shop_structs import GetGoodsInfoReqV5, GoodsInfoRsp req = GetGoodsInfoReqV5() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app(source_id, scene) + req.shopAppInfo = self._build_shop_app(source_id, app_scene) req.pid = pid req.spuId = spu_id req.skuId = sku_id @@ -998,14 +1113,16 @@ class HuyaWssClient: cookie: str, spu_id: str, sku_id: int = 0, - supplier_id: int = 87401, + supplier_id: int = SUPPLIER_ID_YELLOW_CAR, ): from .shop_structs import ListPayChannelReq, ListPayChannelRsp req = ListPayChannelReq() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app("yellowcarlist", WSS_SHOP_SCENE) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) req.supplierId = int(supplier_id or 0) + req.bizType = ORDER_BIZ_TYPE + req.gameCategoryId = GAME_CATEGORY_ID_HUYA req.spuId = spu_id req.skuId = int(sku_id or 0) return await self.call_rpc( @@ -1017,7 +1134,7 @@ class HuyaWssClient: req = CheckHyProtocolReq() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app("yellowcarlist", WSS_SHOP_SCENE) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) return await self.call_rpc( "shopMiddleUI", "checkHyProtocolV5", req, ShopCodeRsp, timeout=15.0 ) @@ -1034,7 +1151,7 @@ class HuyaWssClient: req = CheckUserBuyAuthReq() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app("yellowcarlist", WSS_SHOP_SCENE) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) req.spuId = spu_id req.skuId = int(sku_id or 0) return await self.call_rpc( @@ -1075,14 +1192,14 @@ class HuyaWssClient: cookie: str, order_id: int, source_id: str = "yellowcarlist", - scene: int = WSS_SHOP_SCENE, + app_scene: int = SHOP_APP_SCENE, ): """按订单号查询商城订单详情,匹配 9.1 支付后轮询。""" from .shop_structs import OrderDetailReq, OrderDetailRsp req = OrderDetailReq() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app(source_id, scene) + req.shopAppInfo = self._build_shop_app(source_id, app_scene) req.orderId = int(order_id or 0) return await self.call_rpc( "shopMiddleUI", "orderDetailV5", req, OrderDetailRsp, timeout=15.0 @@ -1099,8 +1216,10 @@ class HuyaWssClient: item_count: int = 1, source_id: str = "yellowcarlist", game_id: str = "", - scene: int = WSS_SHOP_SCENE, + app_scene: int = SHOP_APP_SCENE, + order_scene: int = ORDER_SCENE, order_type: int = 6, + biz_params: str = JIFENCENTER_BIZ_PARAMS, ): from .shop_structs import ( CreateOrderAccountParam, @@ -1112,24 +1231,28 @@ class HuyaWssClient: req = CreateOrderReqV5() req.userId = self._build_biz_user(uid, cookie) - req.shopAppInfo = self._build_shop_app(source_id, scene) + req.shopAppInfo = self._build_shop_app(source_id, app_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 + # 订单侧的 scene 与 shopAppInfo.scene 是两个值(抓包:src/orderScene=4、appInfo=7) + req.src = order_scene req.scene = 0 req.sourceId = source_id req.orderType = order_type - req.extraParam = CreateOrderExtraParam() - req.env = self._build_order_env(item_count) - req.orderScene = scene + extra = CreateOrderExtraParam() + # 标记积分中心来源;缺了会走成普通商城单(抓包实证的固定值)。 + extra.bizParams = biz_params + req.extraParam = extra + req.env = self._build_order_env() + req.orderScene = order_scene req.promotionParam = CreateOrderPromotionParam() req.accountParam = CreateOrderAccountParam() - req.bizType = 5 - req.gameCategoryId = 507 + req.bizType = ORDER_BIZ_TYPE + req.gameCategoryId = GAME_CATEGORY_ID_HUYA req.ext = "" self.logger(f"[下单] orderType={order_type} (HUYA_VIRTUAL)") @@ -1146,8 +1269,9 @@ class HuyaWssClient: pay_type: int = 1, pid: int = 0, source_id: str = "yellowcarlist", - scene: int = WSS_SHOP_SCENE, + app_scene: int = SHOP_APP_SCENE, item_count: int = 1, + callback_url: str = "", ): from .shop_structs import PayOrderRes @@ -1155,21 +1279,22 @@ class HuyaWssClient: os.write_struct_begin(0) os.write_struct(0, self._build_biz_user(uid, cookie)) - os.write_struct(1, self._build_shop_app(source_id, scene)) + os.write_struct(1, self._build_shop_app(source_id, app_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}" + # 积分中心抓包的回调指向 m-shop.huya.com/points.html,不是 yaoguo 域名。 + call_back = callback_url or ( + f"{POINTS_PAY_CALLBACK}?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(5, call_back) + os.write_map(6, self._build_order_env()) os.write_string(7, "null") + os.write_string(8, "") os.write_struct_end() - seq = self._next_biz_seq() + seq = self._next_biz_seq(True) wup = WupRequest() wup.setServant("shopMiddleUI") @@ -1212,3 +1337,134 @@ class HuyaWssClient: if result is None: result = wup_resp.readStruct("tResp", PayOrderRes) return result + + # ============================================================ + # 积分中心链路新增 RPC(2026-10-13「开通精英宝典 / 购买幸运币」抓包) + # ============================================================ + + async def get_supplier_info( + self, + uid: int, + guid: str, + cookie: str, + supplier_id: int = SUPPLIER_ID_YELLOW_CAR, + ): + """shopMiddleUI.getSupplierInfoV5 — 供应商(小店)信息。""" + from .shop_structs import GetSupplierInfoReqV5 + + req = GetSupplierInfoReqV5() + req.userId = self._build_biz_user(uid, cookie) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) + req.supplierId = int(supplier_id or 0) + return await self.call_rpc_raw("shopMiddleUI", "getSupplierInfoV5", req) + + async def accept_hy_protocol(self, uid: int, guid: str, cookie: str): + """shopMiddleUI.acceptHyProtocolV5 — 同意虎牙商城协议(下单前的必做步骤)。""" + from .shop_structs import AcceptHyProtocolReq, ShopCodeRsp + + req = AcceptHyProtocolReq() + req.userId = self._build_biz_user(uid, cookie) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) + return await self.call_rpc( + "shopMiddleUI", "acceptHyProtocolV5", req, ShopCodeRsp, timeout=15.0 + ) + + async def calc_order_promotion( + self, + uid: int, + guid: str, + cookie: str, + pid: int, + spu_id: str, + sku_id: int = 0, + item_count: int = 1, + game_id: int = PEACE_ELITE_GAME_ID, + ): + """shopMiddleUI.calcOrderPromotion — 下单前试算价格/返利。""" + from .shop_structs import CalcOrderPromotionReqV5, shop_spu_number + + spu_num = shop_spu_number(spu_id) + req = CalcOrderPromotionReqV5() + req.userId = self._build_biz_user(uid, cookie) + req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE) + req.spuNum = spu_num + req.skuId = int(sku_id or 0) + req.itemCount = int(item_count or 1) + req.pid = int(pid or 0) + req.spuNum2 = spu_num + req.gameId = int(game_id or 0) + return await self.call_rpc_raw("shopMiddleUI", "calcOrderPromotion", req) + + async def play_mall_query_allocation( + self, + uid: int, + guid: str, + cookie: str, + source_id: str = "yellowcarlist", + page_code: str = POINTS_PAGE_CODE, + ): + """PlayMallUI.queryAllocation — 积分中心页面配额查询。""" + from .shop_structs import PlayMallQueryAllocationReq + + req = PlayMallQueryAllocationReq() + req.userId = self._build_biz_user(uid, cookie) + req.appInfo = self._build_play_mall_app(source_id) + req.pageCode = page_code + return await self.call_rpc_raw("PlayMallUI", "queryAllocation", req) + + async def play_mall_get_my_promotion( + self, + uid: int, + guid: str, + cookie: str, + spu_id: str, + sku_id: int = 0, + price: int = 0, + supplier_id: int = SUPPLIER_ID_YELLOW_CAR, + game_id: int = PEACE_ELITE_GAME_ID, + source_id: str = "yellowcarlist", + ): + """PlayMallUI.getMyPromotion — 查询用户可用返利/促销。""" + from .shop_structs import ( + PlayMallGetMyPromotionReq, + PromotionGoodsKey, + shop_spu_number, + ) + + spu_num = shop_spu_number(spu_id) + req = PlayMallGetMyPromotionReq() + req.userId = self._build_biz_user(uid, cookie) + req.appInfo = self._build_play_mall_app(source_id) + goods = PromotionGoodsKey() + goods.supplierId = int(supplier_id or 0) + goods.spuNum = spu_num + goods.skuId = int(sku_id or 0) + goods.price = int(price or 0) + goods.gameId = int(game_id or 0) + goods.spuNum2 = spu_num + req.goods = goods + return await self.call_rpc_raw("PlayMallUI", "getMyPromotion", req) + + async def get_user_profile( + self, uid: int, guid: str, cookie: str, target_uid: int = 0 + ): + """huyauserui.getUserProfile — 单个用户资料(昵称/头像)。 + + ``target_uid`` 省略时查询自己;响应里资料在 ``tag0.tag0``。 + """ + from .shop_structs import GetUserProfileReq + + req = GetUserProfileReq() + req.userId = self._build_biz_user(uid, cookie) + req.targetUid = int(target_uid or uid or 0) + return await self.call_rpc_raw("huyauserui", "getUserProfile", req) + + async def get_follow_wechat_status(self, uid: int, guid: str, cookie: str): + """wupui.getUserFollowWeChatOfficialStatus — 是否已关注微信公众号。""" + from .shop_structs import FollowWeChatStatusReq + + req = FollowWeChatStatusReq() + req.userId = self._build_biz_user(uid, cookie) + return await self.call_rpc_raw( + "wupui", "getUserFollowWeChatOfficialStatus", req + ) diff --git a/tests/test_huya_points_shop_protocol.py b/tests/test_huya_points_shop_protocol.py new file mode 100644 index 0000000..00e3eeb --- /dev/null +++ b/tests/test_huya_points_shop_protocol.py @@ -0,0 +1,391 @@ +"""积分中心商城链路回归测试(2026-10-13「开通精英宝典 / 购买幸运币」抓包)。 + +抓包文件不入库,这里把关键帧的字节与字段直接固化在测试里;每条断言的来源 +都写在注释里,改动协议时先核对抓包再改测试。 +""" + +import asyncio +import base64 +import struct + +from core.huya.frame_decoder import _decode_wup_body, _extract_wup +from core.huya.http_client import ( + WSConnectParaInfo, + _extract_ws_hosts, + generate_ws_baseinfo, +) +from core.huya.shop_structs import shop_spu_number +from core.huya.taf_protocol import TafInputStream, TafOutputStream, TafType +from core.huya.wss_client import ( + HuyaWssClient, + WssCommand, + WssMessage, +) +from core.huya.wup_protocol import WupResponse + +UID = 1199668595232 +GUID = "0a8995af9218ce6a340261946294a9e7" +COOKIE = f"udb_uid={UID}; yyuid={UID}; guid={GUID}" +PID = 1199650619883 +# 抓包字面值(不要引用实现常量,否则断言会与实现一起漂移) +POINTS_UA_LITERAL = "webh5&0.0.1&websocket&&h5_/points.html" +TAIL_LITERAL = bytes.fromhex("2c36004c5c6600") +BIZ_PARAMS_LITERAL = '{ "jifencenter": 1 }' + +# 抓包实测:RegisterGroup(live:0) 与 UpdateUserExps(版本 map) 的 body 逐字节一致 +HEARTBEAT_BODY = bytes.fromhex("09000106066c6976653a3016002c36004c5c6600") +UPDATE_EXPS_BODY = bytes.fromhex("0800010605353836363416063130373236332c36004c5c6600") +CONFIG_VERSIONS = {"58664": "107263"} + + +class _FakeWs: + """记录发出的帧,并立刻用预设 body 兑现 RPC future(离线跑完整链路)。""" + + def __init__(self, client: HuyaWssClient, response: bytes = b""): + self.client = client + self.response = response + self.sent: list[bytes] = [] + + async def send(self, data: bytes): + self.sent.append(data) + while self.client.rpc_queue: + future = self.client.rpc_queue.popleft() + if not future.done(): + future.set_result(self.response) + + def last_body(self) -> bytes: + return WssMessage.decode(self.sent[-1]).body + + def last_request(self) -> dict: + return _decode_wup_body(self.last_body()) + + +def _points_client(response: bytes = b"") -> HuyaWssClient: + client = HuyaWssClient(logger=lambda _message: None) + client._points_mode = True + client.ws = _FakeWs(client, response) + return client + + +def _wup_response(t_rsp: bytes) -> bytes: + """构造一个 tRsp 为给定结构的 WUP 响应(含 4 字节长度前缀)。""" + buffer = TafOutputStream() + buffer.write_head(0, TafType.MAP) + buffer.write_int32(0, 1) + buffer.write_string(0, "tRsp") + buffer.write_bytes(1, t_rsp) + + output = TafOutputStream() + output.write_int16(1, 3) + output.write_int8(2, 0) + output.write_int32(3, 0) + output.write_int32(4, 1) + output.write_string(5, "mobileui") + output.write_string(6, "getConfig") + output.write_bytes(7, buffer.get_bytes()) + output.write_int32(8, 0) + output.write_map(9, {}) + output.write_map(10, {}) + body = output.get_bytes() + return struct.pack(">I", 4 + len(body)) + body + + +def _config_rsp(versions: dict[str, str]) -> bytes: + """mobileui.getConfig 响应:tag0 开关 map、tag1 版本 map(抓包实测)。""" + output = TafOutputStream() + output.write_struct_begin(0) + output.write_map(0, {}) + output.write_map(1, versions) + output.write_struct_end() + return _wup_response(output.get_bytes()) + + +def test_register_group_frame_matches_capture(): + async def run(): + client = _points_client() + await client.send_heartbeat() + message = WssMessage.decode(client.ws.sent[-1]) + assert message.command == WssCommand.HEARTBEAT_SEND + assert message.sequence == 0x1D00000D + assert message.body == HEARTBEAT_BODY + + asyncio.run(run()) + + +def test_shop_ws_launch_carries_real_identity_and_points_ua(): + async def run(): + client = _points_client(_wup_response(b"")) + await client.call_ws_launch_shop(UID, GUID) + + message = WssMessage.decode(client.ws.sent[-1]) + assert message.command == WssCommand.RPC_REQUEST + # 抓包:wsLaunch 帧 seq=0x1d000100,iRequestId=-1 + assert message.sequence == 0x1D000100 + wup = WupResponse() + wup.decode(_extract_wup(message.body)) + assert wup.iRequestId == -1 + + decoded = _decode_wup_body(message.body) + assert (decoded["servant"], decoded["func"]) == ("launch", "wsLaunch") + t_req = decoded["tReq"] + # 抓包:lUid=真实 uid、sGuid=真实 guid、UA=h5_/points.html(不再是匿名) + assert t_req["tag0"] == UID + assert t_req["tag1"] == GUID + assert t_req["tag2"] == POINTS_UA_LITERAL + assert t_req["tag3"] == "HUYA&ZH&2052" + assert t_req["tag4"] == { + "tag0": "", + "tag1": "", + "tag2": "", + "tag3": "", + "tag4": "", + } + + asyncio.run(run()) + + +def test_get_config_uses_real_user_and_confirms_version_map(): + async def run(): + client = _points_client(_config_rsp(CONFIG_VERSIONS)) + body = await client.call_get_config_shop(uid=UID, guid=GUID, cookie=COOKIE) + assert body is not None + assert client._config_versions == CONFIG_VERSIONS + + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ("mobileui", "getConfig") + t_req = decoded["tReq"] + # 抓包:getConfig 的 UserId 带真实 uid/guid/页面 UA/完整 Cookie + assert t_req["tag0"]["tag0"] == UID + assert t_req["tag0"]["tag1"] == GUID + assert t_req["tag0"]["tag3"] == POINTS_UA_LITERAL + assert GUID in t_req["tag0"]["tag4"] + assert t_req["tag2"] == "huya" + + # UpdateUserExps 必须原样回传版本 map(抓包逐字节一致) + await client.send_confirm(client._config_versions) + assert client.ws.last_body() == UPDATE_EXPS_BODY + + asyncio.run(run()) + + +def test_create_order_v5_matches_points_capture(): + async def run(): + client = _points_client() + await client.create_order( + uid=UID, + guid=GUID, + cookie=COOKIE, + pid=PID, + spu_id="hy-8328015", + sku_id=7756811, + item_count=1, + ) + + message = WssMessage.decode(client.ws.sent[-1]) + # 抓包:下单帧用 0x1d000108(其余业务帧 0x1d000107) + assert message.sequence == 0x1D000108 + + decoded = _decode_wup_body(message.body) + assert (decoded["servant"], decoded["func"]) == ( + "shopMiddleUI", + "createOrderV5", + ) + t_req = decoded["tReq"] + assert t_req["tag1"]["tag4"] == 7 # shopAppInfo.scene=7(appInfo 用 7) + assert t_req["tag3"] == PID + assert t_req["tag4"] == 7756811 + assert t_req["tag5"] == 1 + assert t_req["tag7"] == "hy-8328015" + assert t_req["tag8"] == "0" + assert t_req["tag10"] == 4 # src + assert t_req["tag12"] == 6 # orderType + assert t_req["tag13"]["tag4"] == BIZ_PARAMS_LITERAL + assert t_req["tag16"] == "yellowcarlist" + assert t_req["tag17"] == {"user_click_seq": "[]"} + assert t_req["tag18"] == 4 # orderScene + assert t_req["tag21"]["tag2"] == 1 + assert t_req["tag30"] == 5 + assert t_req["tag31"] == 507 + + asyncio.run(run()) + + +def test_pay_order_submit_v5_callback_points_page(): + async def run(): + client = _points_client() + await client.pay_order_submit( + uid=UID, + guid=GUID, + cookie=COOKIE, + order_id=11339649, + pay_type=1, + pid=PID, + ) + + message = WssMessage.decode(client.ws.sent[-1]) + assert message.sequence == 0x1D000108 + + decoded = _decode_wup_body(message.body) + assert (decoded["servant"], decoded["func"]) == ( + "shopMiddleUI", + "payOrderSubmitV5", + ) + t_req = decoded["tReq"] + assert t_req["tag2"] == 11339649 + assert t_req["tag3"] == "Zfb" + assert t_req["tag4"] == "QrCode" + # 抓包:回调指向 m-shop.huya.com/points.html,不是 yaoguo 域名 + assert t_req["tag5"].startswith( + "https://m-shop.huya.com/points.html#/consumer/paycallback?orderId=11339649" + ) + assert t_req["tag6"] == {"user_click_seq": "[]"} + assert t_req["tag7"] == "null" + assert t_req["tag8"] == "" + + asyncio.run(run()) + + +def test_new_points_rpcs_match_capture(): + async def run(): + client = _points_client() + + await client.get_supplier_info(uid=UID, guid=GUID, cookie=COOKIE) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "shopMiddleUI", + "getSupplierInfoV5", + ) + assert decoded["tReq"]["tag2"] == 87401 + + await client.accept_hy_protocol(uid=UID, guid=GUID, cookie=COOKIE) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "shopMiddleUI", + "acceptHyProtocolV5", + ) + assert decoded["tReq"]["tag2"] == 1 + + await client.calc_order_promotion( + uid=UID, + guid=GUID, + cookie=COOKIE, + pid=PID, + spu_id="hy-8328015", + sku_id=7756811, + ) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "shopMiddleUI", + "calcOrderPromotion", + ) + t_req = decoded["tReq"] + assert t_req["tag2"] == 8328015 # spuId 去前缀后的数字 + assert t_req["tag3"] == 7756811 + assert t_req["tag4"] == 1 + assert t_req["tag5"] == PID + assert (t_req["tag7"], t_req["tag8"], t_req["tag9"]) == (1, 1, 1) + assert t_req["tag14"] == 8328015 + assert t_req["tag15"] == 9815 + + await client.play_mall_query_allocation(uid=UID, guid=GUID, cookie=COOKIE) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "PlayMallUI", + "queryAllocation", + ) + t_req = decoded["tReq"] + assert t_req["tag1"]["tag1"] == 1001 + assert t_req["tag1"]["tag5"] == 7 + assert t_req["tag1"]["tag6"] == "yellowcarlist" + assert t_req["tag2"] == "heping_baodian_credit_center_page" + + await client.play_mall_get_my_promotion( + uid=UID, + guid=GUID, + cookie=COOKIE, + spu_id="hy-8328015", + sku_id=7756811, + price=3000, + ) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "PlayMallUI", + "getMyPromotion", + ) + goods = decoded["tReq"]["tag6"] + assert goods["tag0"] == 87401 + assert goods["tag1"] == 8328015 + assert goods["tag2"] == 7756811 + assert goods["tag3"] == 3000 + assert goods["tag6"] == 9815 + + await client.get_user_profile(uid=UID, guid=GUID, cookie=COOKIE) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "huyauserui", + "getUserProfile", + ) + assert decoded["tReq"]["tag1"] == UID + + await client.get_follow_wechat_status(uid=UID, guid=GUID, cookie=COOKIE) + decoded = client.ws.last_request() + assert (decoded["servant"], decoded["func"]) == ( + "wupui", + "getUserFollowWeChatOfficialStatus", + ) + assert decoded["tReq"]["tag1"] == 1 + + asyncio.run(run()) + + +def test_confirm_frame_ends_with_capture_tail(): + async def run(): + client = _points_client() + await client.send_confirm({}) + assert client.ws.last_body().endswith(TAIL_LITERAL) + + asyncio.run(run()) + + +def test_ws_baseinfo_matches_capture_shape(): + raw = base64.b64decode(generate_ws_baseinfo(UID, GUID, POINTS_UA_LITERAL)) + info = WSConnectParaInfo() + info.read_from(TafInputStream(raw)) + # 抓包:握手 baseinfo 只有 uid/guid/UA/appSrc/exp 有值,cookie 与 traceId 为空 + assert info.lUid == UID + assert info.sGuid == GUID + assert info.sUA == POINTS_UA_LITERAL + assert info.sAppSrc == "HUYA&ZH&2052" + assert info.sCookie == "" + assert info.sTraceId == "" + assert info.sExp == "" + + with_exp = base64.b64decode( + generate_ws_baseinfo(UID, GUID, POINTS_UA_LITERAL, exp="58664.107263") + ) + parsed = WSConnectParaInfo() + parsed.read_from(TafInputStream(with_exp)) + assert parsed.sExp == "58664.107263" + + +def test_query_http_dns_hosts_extraction(): + payload = ( + b"\x1a\x09\x00\x04" + b"\x06\x17d35bf201-ws.va.huya.com" + b"\x06\x17d35bf373-ws.va.huya.com" + b"\x06\x17d35bf35c-ws.va.huya.com" + b"\x06\x17dcca159d-ws.va.huya.com" + ) + assert _extract_ws_hosts(payload) == [ + "d35bf201-ws.va.huya.com", + "d35bf373-ws.va.huya.com", + "d35bf35c-ws.va.huya.com", + "dcca159d-ws.va.huya.com", + ] + assert _extract_ws_hosts(b"") == [] + + +def test_shop_spu_number_strips_prefix(): + assert shop_spu_number("hy-8328015") == 8328015 + assert shop_spu_number("8327356") == 8327356 + assert shop_spu_number("") == 0 diff --git a/web/backend/services/huya_runner_recharge.py b/web/backend/services/huya_runner_recharge.py index 3bb156e..004bf72 100644 --- a/web/backend/services/huya_runner_recharge.py +++ b/web/backend/services/huya_runner_recharge.py @@ -8,10 +8,15 @@ from typing import TYPE_CHECKING, Any from sqlalchemy.orm import Session +from core.huya.wss_client import SHOP_APP_SCENE + from ..models import HuyaAccount, HuyaRechargeGoodsSnapshot, HuyaTask +from .huya_shop_flow import run_open_flow HUYA_RECHARGE_ACT_ID = 25135 -HUYA_RECHARGE_SCENE = 4 +# shopAppInfo.scene(2026-10-13 积分中心抓包实测 7;订单侧 scene 由 +# core.huya.wss_client.ORDER_SCENE 决定,两者不是同一个值) +HUYA_RECHARGE_APP_SCENE = SHOP_APP_SCENE HUYA_PAYMENT_POLL_SECONDS = 180 HUYA_PAYMENT_POLL_INTERVAL = 3 HUYA_RECHARGE_EXTRA_PRODUCTS = [ @@ -290,7 +295,7 @@ class RechargeMixin: sku_id=0, game_id="", source_id=HUYA_RECHARGE_SOURCE_ID, - scene=HUYA_RECHARGE_SCENE, + app_scene=HUYA_RECHARGE_APP_SCENE, ) if detail_resp is None: failed.append({"spu_id": spu_id, "message": "商品详情接口无响应"}) @@ -419,143 +424,42 @@ class RechargeMixin: unit_price = int(snapshot.price or 0) if snapshot else 0 client: Any = self._shop_client(uid, cookie) - detail_resp = client.get_goods_info( + outcome = run_open_flow( + client, uid=uid, - guid="", - cookie=cookie, - pid=pid, - spu_id=spu_id, - sku_id=sku_id or 0, - game_id="", - source_id=HUYA_RECHARGE_SOURCE_ID, - scene=HUYA_RECHARGE_SCENE, - ) - if detail_resp is None: - self._mark_task(worker_db, task, "error", "虎牙充值商品详情接口无响应") - return - detail = detail_resp.to_dict() - if detail_resp.code != 200: - self._mark_task( - worker_db, - task, - "failed", - detail_resp.message or f"虎牙充值商品详情获取失败: {detail_resp.code}", - detail, - ) - return - - sku_id = int(detail.get("sku_id") or sku_id or 0) - product_name = detail.get("name") or product_name - unit_price = int(detail.get("price") or unit_price or 0) - if not sku_id: - self._mark_task( - worker_db, - task, - "failed", - "充值商品缺少 SKU,请先刷新充值商品列表", - detail, - ) - return - - protocol = client.check_hy_protocol(uid=uid, guid="", cookie=cookie) - if protocol is None or protocol.code != 200: - self._mark_task( - worker_db, - task, - "failed", - getattr(protocol, "message", "商城协议校验失败") or "商城协议校验失败", - {"goods": detail, "protocol": protocol.to_dict() if protocol else None}, - ) - return - channels = client.list_pay_channels( - uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=0 - ) - available_channels = set(getattr(channels, "channels", []) or []) - if ( - channels is None - or channels.code != 200 - or pay_channel not in available_channels - ): - self._mark_task( - worker_db, - task, - "failed", - "当前支付渠道不可用", - {"goods": detail, "channels": channels.to_dict() if channels else None}, - ) - return - auth = client.check_user_buy_auth( - uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=sku_id - ) - if auth is None or auth.code != 200: - self._mark_task( - worker_db, - task, - "failed", - getattr(auth, "message", "购买权限校验失败") or "购买权限校验失败", - {"goods": detail, "auth": auth.to_dict() if auth else None}, - ) - return - - order_resp = client.create_order( - uid=uid, - guid="", cookie=cookie, pid=pid, spu_id=spu_id, sku_id=sku_id, - item_count=count, - source_id=HUYA_RECHARGE_SOURCE_ID, - game_id="0", - scene=HUYA_RECHARGE_SCENE, - order_type=6, + count=count, + pay_channel=pay_channel, + snapshot_price=unit_price, + log=lambda message: self._push_log("info", message), + stopped=self._stop.is_set, ) - if order_resp is None: - self._mark_task(worker_db, task, "error", "虎牙下单接口无响应") - return - order_result = order_resp.to_dict() - if order_resp.code != 200 or not order_resp.orderId: + detail = outcome.detail + if not outcome.ok: self._mark_task( worker_db, task, - "failed", - order_resp.message or f"虎牙下单失败: {order_resp.code}", - {"goods": detail, "order": order_result}, + "error" if "无响应" in outcome.message else "failed", + outcome.message, + { + "goods": detail, + "supplier_name": outcome.supplier_name, + "promotion": outcome.promotion, + "promotion_info": outcome.promotion_info, + }, ) return - pay_resp = client.pay_order_submit( - uid=uid, - guid="", - cookie=cookie, - order_id=order_resp.orderId, - pay_type=pay_channel, - pid=pid, - source_id=HUYA_RECHARGE_SOURCE_ID, - scene=HUYA_RECHARGE_SCENE, - item_count=count, - ) - if pay_resp is None: - self._mark_task( - worker_db, - task, - "error", - "虎牙支付接口无响应", - {"goods": detail, "order": order_result}, - ) - return - pay_result = pay_resp.to_dict() - if pay_resp.code != 200 or not pay_resp.payUrl: - self._mark_task( - worker_db, - task, - "failed", - pay_resp.message or f"虎牙支付二维码生成失败: {pay_resp.code}", - {"goods": detail, "order": order_result, "pay": pay_result}, - ) - return + sku_id = outcome.sku_id or sku_id + product_name = outcome.product_name or product_name + unit_price = outcome.unit_price or unit_price - amount = int(pay_resp.amount or unit_price * count or 0) + order_result = outcome.order_raw + pay_result = outcome.pay_raw + amount = outcome.amount result = { "spu_id": spu_id, "sku_id": sku_id, @@ -566,15 +470,19 @@ class RechargeMixin: "amount_text": self._recharge_price_text(amount), "pay_channel": pay_channel, "pay_channel_label": self._pay_channel_label(pay_channel), - "order_id": order_resp.orderId, - "app_order_id": pay_resp.appOrderId, - "pay_order_id": pay_resp.payOrderId, - "pay_url": pay_resp.payUrl, + "order_id": outcome.order_id, + "app_order_id": outcome.app_order_id, + "pay_order_id": outcome.pay_order_id, + "pay_url": outcome.pay_url, "payment_status": "pending", "payment_status_label": "等待支付", "payment_paid": False, "goods": detail, "order": order_result, + "pay": pay_result, + "supplier_name": outcome.supplier_name, + "promotion": outcome.promotion, + "promotion_info": outcome.promotion_info, } account.status = "recharge_order_created" account.updated_at = datetime.now(UTC) @@ -583,7 +491,7 @@ class RechargeMixin: worker_db, task, "running", f"{message},等待扫码支付", result ) self._push_log( - "info", f"[{uid}] 已生成虎牙支付二维码,开始监听订单 {order_resp.orderId}" + "info", f"[{uid}] 已生成虎牙支付二维码,开始监听订单 {outcome.order_id}" ) payment_status, payment_order = self._wait_recharge_payment( @@ -591,7 +499,7 @@ class RechargeMixin: uid=uid, guid="", cookie=cookie, - order_id=order_resp.orderId, + order_id=outcome.order_id, sid=self._to_int(config_info.get("sid")) or 2203, result=result, ) diff --git a/web/backend/services/huya_shop_flow.py b/web/backend/services/huya_shop_flow.py new file mode 100644 index 0000000..701f1df --- /dev/null +++ b/web/backend/services/huya_shop_flow.py @@ -0,0 +1,245 @@ +"""虎牙积分中心(m-shop.huya.com/points.html)开通 / 买币下单链路。 + +2026-10-13「开通精英宝典 / 购买幸运币」抓包实证的帧顺序: + + getGoodsInfoV5 → getSupplierInfoV5 → listPayChannelV5 → checkHyProtocolV5 + → PlayMallUI.getMyPromotion → calcOrderPromotion → acceptHyProtocolV5 + → checkUserBuyAuth → createOrderV5 → payOrderSubmitV5 → orderDetailV5(轮询) + +本模块只负责「准备 → 下单 → 起支付」;支付到账轮询由调用方决定(任务侧会轮询, +外部 CK 批量开通只出支付码)。任务执行器与外部 CK 批量开通共用这里,避免链路 +在两处各写一遍。 +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field +from typing import Any + +#: 小黄车供应商(和平精英官方小店),抓包实测。 +SUPPLIER_ID_YELLOW_CAR = 87401 + + +@dataclass +class ShopOrderOutcome: + """开通链路的结果(ok=False 时 message 是失败原因)。""" + + ok: bool + message: str + detail: dict = field(default_factory=dict) + supplier_name: str = "" + promotion: dict | None = None + promotion_info: dict | None = None + order_raw: dict = field(default_factory=dict) + pay_raw: dict = field(default_factory=dict) + order_id: int = 0 + app_order_id: str = "" + pay_order_id: str = "" + pay_url: str = "" + amount: int = 0 + pay_channel: str = "Zfb" + sku_id: int = 0 + unit_price: int = 0 + count: int = 1 + product_name: str = "" + + +def run_open_flow( + client: Any, + *, + uid: int, + cookie: str, + pid: int, + spu_id: str, + sku_id: int = 0, + count: int = 1, + pay_channel: str = "Zfb", + supplier_id: int = SUPPLIER_ID_YELLOW_CAR, + snapshot_price: int = 0, + log: Callable[[str], None] | None = None, + stopped: Callable[[], bool] | None = None, +) -> ShopOrderOutcome: + """执行抓包链路;成功时返回「已生成支付二维码」的订单信息。""" + + def emit(message: str) -> None: + if log is not None: + log(message) + + def fail(message: str, **extra: Any) -> ShopOrderOutcome: + return ShopOrderOutcome(ok=False, message=message, **extra) + + # 1) 商品详情(拿 skuId / 价格 / 商品名) + detail_resp = client.get_goods_info( + uid=uid, + guid="", + cookie=cookie, + pid=pid, + spu_id=spu_id, + sku_id=sku_id or 0, + game_id="", + ) + if detail_resp is None: + return fail("虎牙充值商品详情接口无响应") + detail = detail_resp.to_dict() + if detail_resp.code != 200: + return fail( + detail_resp.message or f"虎牙充值商品详情获取失败: {detail_resp.code}", + detail=detail, + ) + + sku_id = int(detail.get("sku_id") or sku_id or 0) + product_name = str(detail.get("name") or spu_id) + unit_price = int(detail.get("price") or snapshot_price or 0) + if not sku_id: + return fail("充值商品缺少 SKU,请先刷新充值商品列表", detail=detail) + + # 2) 供应商(小店)信息 + supplier = client.get_supplier_info(uid=uid, guid="", cookie=cookie) + supplier_name = "" + if supplier is not None: + raw_name = supplier.value("tag2", "tag0") + supplier_name = raw_name if isinstance(raw_name, str) else "" + emit(f"[{uid}] 小店:{supplier_name or '未知'}(supplierId={supplier_id})") + + # 3) 支付渠道 + channels = client.list_pay_channels( + uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=0 + ) + available_channels = set(getattr(channels, "channels", []) or []) + if ( + channels is None + or channels.code != 200 + or pay_channel not in available_channels + ): + return fail( + "当前支付渠道不可用", + detail=detail, + supplier_name=supplier_name, + ) + + # 4) 商城协议校验 + protocol = client.check_hy_protocol(uid=uid, guid="", cookie=cookie) + if protocol is None or protocol.code != 200: + return fail( + getattr(protocol, "message", "") or "商城协议校验失败", + detail=detail, + supplier_name=supplier_name, + ) + + # 5) 返利/促销查询 + 下单试算 + promotion_info = client.play_mall_get_my_promotion( + uid=uid, + guid="", + cookie=cookie, + spu_id=spu_id, + sku_id=sku_id, + price=unit_price, + ) + promotion = client.calc_order_promotion( + uid=uid, + guid="", + cookie=cookie, + pid=pid, + spu_id=spu_id, + sku_id=sku_id, + item_count=count, + ) + promotion_dict = promotion.to_dict() if promotion is not None else None + if promotion is not None and promotion.code not in (0, 200): + emit(f"[{uid}] 促销试算返回 {promotion.code}:{promotion.message}") + + # 6) 同意商城协议(抓包:这一步在 checkUserBuyAuth 之前) + accept = client.accept_hy_protocol(uid=uid, guid="", cookie=cookie) + if accept is None or accept.code != 200: + return fail( + getattr(accept, "message", "") or "虎牙商城协议确认失败", + detail=detail, + supplier_name=supplier_name, + promotion=promotion_dict, + promotion_info=( + promotion_info.to_dict() if promotion_info is not None else None + ), + ) + + if stopped is not None and stopped(): + return fail("已停止", detail=detail, supplier_name=supplier_name) + + # 7) 购买权限 + auth = client.check_user_buy_auth( + uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=sku_id + ) + if auth is None or auth.code != 200: + return fail( + getattr(auth, "message", "") or "购买权限校验失败", + detail=detail, + supplier_name=supplier_name, + promotion=promotion_dict, + ) + + # 8) 下单 + order_resp = client.create_order( + uid=uid, + guid="", + cookie=cookie, + pid=pid, + spu_id=spu_id, + sku_id=sku_id, + item_count=count, + game_id="0", + order_type=6, + ) + common = { + "detail": detail, + "supplier_name": supplier_name, + "promotion": promotion_dict, + "promotion_info": ( + promotion_info.to_dict() if promotion_info is not None else None + ), + "sku_id": sku_id, + "unit_price": unit_price, + "count": count, + "product_name": product_name, + "pay_channel": pay_channel, + } + if order_resp is None: + return fail("虎牙下单接口无响应", **common) + order_raw = order_resp.to_dict() + common["order_raw"] = order_raw + if order_resp.code != 200 or not order_resp.orderId: + return fail( + order_resp.message or f"虎牙下单失败: {order_resp.code}", + **common, + ) + + # 9) 起支付(出支付宝/微信二维码) + pay_resp = client.pay_order_submit( + uid=uid, + guid="", + cookie=cookie, + order_id=order_resp.orderId, + pay_type=pay_channel, + pid=pid, + item_count=count, + ) + if pay_resp is None: + return fail("虎牙支付接口无响应", **common) + pay_raw = pay_resp.to_dict() + common["pay_raw"] = pay_raw + if pay_resp.code != 200 or not pay_resp.payUrl: + return fail( + pay_resp.message or f"虎牙支付二维码生成失败: {pay_resp.code}", + **common, + ) + + amount = int(pay_resp.amount or unit_price * count or 0) + return ShopOrderOutcome( + ok=True, + message="已生成支付二维码", + order_id=int(order_resp.orderId), + app_order_id=pay_resp.appOrderId, + pay_order_id=pay_resp.payOrderId, + pay_url=pay_resp.payUrl, + amount=amount, + **common, + )