10 Commits
Author SHA1 Message Date
yml2213 0b9a01ab3f feat(huya): 开通支付码复用未支付旧单 + 二维码改用支付宝收银台直达地址
- 限购商品(精英宝典 buy_limit=1)挂着未支付旧单时,真正先失败的是购买权限
  校验 checkUserBuyAuth(真机 703「已超过该商品的购买上限,下单失败~」),
  createOrderV5 根本不会执行;现在 checkUserBuyAuth 与 createOrderV5 两处失败
  都会回退 find_reusable_order,拿同一商品的未支付旧单继续 payOrderSubmitV5。
- 新增支付宝收银台直达地址解析(resolve_pay_entry_url):跟随网关 302 后的
  excashier.alipay.com/standard/auth.htm?payOrderId=…(93 字符,原始网关地址
  1616 字符)写入结果 pay_cashier_url;解析失败回落本站短链
  /api/huya/pay/<task_id>?k=<hmac>,后端跑在 localhost 时客户也扫得开。
- 前端 QRCode 显式 color="#000" bgColor="#fff":antd v6 暗色主题默认
  color=token.colorText、bgColor=transparent,白码落在白底容器里根本看不见。
- 支付成功后列表「二维码」列不再展示二维码(qrDoneLabel → 已支付/已开通)。

测试:pytest 767 passed / 6 skipped;typecheck、eslint、ruff 通过。
2026-10-15 19:28:26 +08:00
yml2213 f61284e808 feat(huya): 开通支付码支持多选批量 + 支付后自动确认开通
多选账号点「生成开通支付码」以前只有弹窗里最后一个码能被看到(每个账号一个
任务,前端只留一个 qrTask),实际只能一个账号一个账号地开。

- 前端:支付码弹窗改成列表 —— 一次列出该批次所有账号的二维码(账号/UID/
  商品金额/状态),未支付的排前面,可逐个扫也可一起扫;行点击也会打开对应批次
- 支付成功后自动确认开通:新增 EliteMixin._refresh_elite_open_after_payment,
  交付有几秒延迟,tag5 还没翻成 1 时重试(默认 4 次 × 3 秒),顺带取最新积分,
  并把 elite_opened/elite_open_time/elite_expire_time 写回账号
- 已支付或已开通的账号二维码自动从弹窗收起,只留一行「已开通」标签
- 开通时间优先用支付回调里的支付时间(比再去翻订单更准,也少一次请求)
- 补 3 条测试:重试到已开通、重试到上限、支付成功后任务结果与账号字段齐全

全量 746 passed / 6 skipped,前端 tsc 通过
2026-10-15 17:14:20 +08:00
yml2213 369361a62c style(huya): 精英宝典工作台表格表头与单元格统一居中
列宽按比例分配,所有列(含账号/游戏名/精英宝典/最近操作的双行内容)统一
align: center,积分不再单独右对齐 —— 之前左右跳着看很别扭。
2026-10-15 16:58:06 +08:00
yml2213 73536d62c8 feat(huya): 工作台补手机号/精英宝典列与一键查询
- 手机号列:外部 CK 的 `----手机号` 本来就落在 huya_accounts.game_phone,
  列表一直没展示;现在单独成列,并纳入搜索
- 精英宝典列:显示「已开通/未开通/未查询」+ 开通时间 + 有效期
  · 开通状态 = 积分中心 getRedeemNeedGoods 的 tag5(真机对照网页:1=已开通,
    0=未开通,此时 tag7 会列出开通套餐),拿不准时为 NULL(显示「未查询」)
  · 开通时间 = revenueWebUI.queryUserOrderList 里已支付的宝典订单 pay_time
    (按 SPU 白名单 + 订单名含「精英宝典」识别,未支付订单不计,取最近一次)
  · 有效期 = PlayMallUI.queryAllocation 页面配置的本赛季节点 tag10/tag11
    (2026-10-15 抓包:精英宝典福利季丨Q4,2026-10-09 ~ 2026-12-31 23:59:59),
    不写死索引,递归找带 tag10/tag11 的节点
- 新任务 query_all「一键查询」:勾选账号一次跑完角色绑定 + 宝典开通 + 积分,
  按部分失败如实汇总(某个接口挂了不影响其它结论),并把宝典状态写回账号
- 迁移 20261015_0053:huya_accounts 新增 elite_opened / elite_open_time /
  elite_expire_time(时间存 Unix 秒,与斗鱼 elite_expire_time 同约定)
- 开通商品按页面「赠送指定礼物得积分」那一排对齐成 6 款(去掉页面已不用的
  旧版精英宝典 hy-5879340),列表接口只返回账号级快照并按 spu 去重
- 建 WSS 会话失败(积分中心端点静默不回包)时回退 HTTP cdnws,
  不再让整批任务判失败
- 列表列宽改按比例分配,避免宽屏下被拉出奇怪的宽度;最近操作不再重复状态
- 新增 tests/test_huya_elite_query.py(10 条);同步迁移头版本断言

真机验证:#65 已开通(10-13 20:41:45,有效期 12-31)、#70 新开通
(10-15 16:37:37)判定与订单/网页一致
2026-10-15 16:53:30 +08:00
yml2213 7ca0f7ee28 fix(huya): 刷新开通商品不再依赖已下线的活动任务接口
真机(2026-10-15)实测 webActUI.getActTaskDetail(act 25135) 返回
601「活动已下线」,刷新开通商品第一步就失败,下拉框一直为空。

- 商品来源改为内置候选(积分中心页面「赠送指定礼物得积分」那一排,
  全部经 getGoodsInfoV5 真机验证 code=200):精英宝典 hy-8328015 ¥30、
  精英币 hy-8327356 ¥0.1、精英徽章 hy-5872824 ¥1、精英令 hy-5879346 ¥10、
  精英令*10 hy-5874269 ¥100、精英令*100 hy-5874270 ¥1000;
  旧版精英宝典 hy-5879340 页面已不再使用,从候选移除
- 活动任务详情降级为可选补充:返回非 200 只记 warning 并写入
  result.task_detail_error,不再让整次刷新失败;失败原因以商品详情为准
- 刷新时清掉该账号全部旧商品行(不限 sid),避免同名商品重复
- 列表接口只返回账号级快照并过滤 2026-07-04 的全局种子行,
  同一 spu_id 保留最新一行(原先 精英宝典 会出现两次)
- 前端:下拉标签带 spu 便于区分,按内置顺序排序,默认自动选中第一项
- 新增 tests/test_huya_recharge_goods_source.py(6 条):活动下线响应字节
  回归、下线不阻断刷新、活动商品仍会并入、失败原因归属、跨 sid 清理、
  列表去重与隐藏种子行(均已做反向验证)

真机验证:刷新成功 6 个商品,价格/库存与网页一致
2026-10-15 15:57:25 +08:00
yml2213 905a7ef22c fix(huya): 查询积分改走积分中心新接口(含成长等级)
旧活动接口 webActUI.getUserScore 对任何 sid 都返回 603「活动已结束」
(接口已下线,与工作台 SID/活动配置无关),刷新积分只会报错。

- 协议层新增两个 RPC(WSS + HTTP 双侧同签名):
  shopMiddleUI.getRedeemNeedGoods(tag2=当前积分、tag3=兑换门槛,
  兑换商品号 POINTS_REDEEM_GOODS_NUM=8315982,传错直接 500)
  与 GameBizUI.getGrowLevelUserInfo(成长值/成长等级/昵称/头像)
- 新增结构体 GetRedeemNeedGoodsReq / GetGrowLevelUserInfoReq,
  与 HuyaEliteWssSession 透传
- 服务层 _execute_query_points 主源改为积分中心接口,结果带
  points/redeem_threshold/grow_level/grow_value,并同步 account.points;
  接口无响应时才回退旧活动接口并如实报告其 603 返回
- 开通支付成功后的积分刷新同样改走积分中心接口
- 前端任务页积分结果优先读 points(兼容旧记录的 available_score),
  并在有成长等级时一并展示
- 新增 tests/test_huya_points_query.py:真机响应字节回归 + 请求参数
  字面量断言 + 服务层积分来源/回退语义(已做反向验证)

真机验证:HTTP 通道取到积分 280 / 门槛 20 / 成长等级 3
2026-10-15 15:32:46 +08:00
yml2213 b5d8d5b5d8 feat(huya): 缺网页设备态的 CK 回退 HTTP cdnws 通道
问题:外部 CK(只带登录态)导入工作台后,任何任务都被「Cookie 缺少网页设备态
(sdid/udb_deviceid/udb_guiddata/udb_anobiztoken)」直接拦下,查询角色/开通都用不了。

实测结论(2026-10-15,同一张外部 CK):
- 这些字段是 WSS 通道的门禁,不是业务必需 —— 同一条 CK 走 HTTP cdnws 可以正常查询
  角色、商品,并走完整条开通链路(商品/小店/渠道/协议/返利/试算/同意/购买权限)
- A/B 对照(同一账号只抽掉 sdid):含 sdid 服务端回包,去掉即完全不回包,说明 sdid
  是 WSS 的硬门槛,而 HTTP 通道不需要
- 因此改为按能力选通道:设备态齐全走 WSS(行为不变),缺设备态回退 HTTP 并记日志

- http_client:补齐积分中心链路(get_supplier_info / accept_hy_protocol /
  calc_order_promotion / play_mall_get_my_promotion / play_mall_query_allocation /
  get_user_profile / get_follow_wechat_status);下单与支付参数对齐 2026-10-13 抓包
  (appInfo.scene=7、订单 src/orderScene=4、orderType=6、jifencenter 标记、空点击序列、
  m-shop.huya.com/points.html 回调),并去掉 orderType 1→10 的重试循环(有重复下单风险)
- huya_runner_core:_activity_client/_shop_client 不再抛 COOKIE_INCOMPLETE,改为
  返回 HTTP cdnws 客户端(方法签名与 WSS 会话保持一致,任务侧无感)

验证:tests/test_huya_http_shop_flow.py(下单/支付参数与回调域名)、
tests/test_huya_runner_transport.py(通道选择:缺设备态走 HTTP、齐全仍走 WSS);
真机 HTTP 开通链路 8 步全通(末步服务端返回业务提示「已超过该商品的购买上限」,
说明通道可用而非被丢弃)。反向验证:关掉回退即复现原报错。全量 pytest 717 passed。
2026-10-15 15:21:51 +08:00
yml2213 a9d711a7e9 fix(huya): 结构体尾部字段容错解析(服务端新增 ZERO 字段不再打挂整个 RPC)
真机现象(2026-10-15,外部 CK 导入后查询角色):checkUserBindGameAccount 响应结构
尾部多了 tag6(ZERO 类型 0x6c),共享的 read_struct 读到非 STRUCT_END 直接抛
「期望 STRUCT_END, 实际 0x0c」,整个 RPC 返回 None —— 工作台「查询角色」永远失败。

- taf_protocol:read_struct 收尾改为按 TAF 语义跳过未建模的尾部字段(上限 32 个,
  防止解析错位时无限吞字节);新增 skip_to_struct_end()
- frame_decoder / shop_structs:抽出 decode_struct_bytes 与 ShopRawRsp.from_payload,
  WSS 与 HTTP 两条通道共用一份通用解码逻辑(wss_client 同步改用)

验证:tests/test_huya_struct_parse_resilience.py 用真机响应字节回归(含 tag6=ZERO 的
响应能解析出角色「泪雨全是谎言」);按 AGENTS.md 反向验证 —— 注掉
skip_to_struct_end() 即复现线上报错「期望 STRUCT_END, 实际 0x0c」,还原后恢复。
全量 pytest 通过。
2026-10-15 15:21:34 +08:00
yml2213 4ce30e5c26 feat(huya): 精英宝典工作台支持导入外部 CK
- 新增 POST /api/huya/workbench-accounts/import-cookies(huya:task + huya:import):
  外部 CK 复用现有解析入库后直接加入当前用户的工作台集合,导入完即可在工作台执行
  「生成开通支付码/绑定二维码/查询角色/刷新积分」等操作
- 新账号自动 assigned_to=导入者:客服的账号列表按归属过滤,不设归属会「导入成功但看不到」
- import_huya_cookies_detailed 返回账号对象供工作台复用,原 import_huya_cookies 行为不变
- 工作台账号卡片新增「导入外部 CK」入口(huya:import 权限控制)与导入弹窗

验证:新增 tests/test_huya_workbench_import_ck.py(入库、归属、工作台集合、重复导入幂等、
全脏数据不建记录);按 AGENTS.md 做了反向验证(关掉归属赋值后该用例变红,还原后恢复)。
前端 tsc -b 与全量 pytest 通过。
2026-10-15 14:56:58 +08:00
yml2213 f540dcfc29 feat(huya): 对齐积分中心开通链路(2026-10-13 抓包)
按 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 通过。
2026-10-15 14:56:30 +08:00
37 changed files with 5310 additions and 428 deletions
+54 -8
View File
@@ -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,34 @@ 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))
def get_redeem_need_goods(self, **kwargs):
return self._run(self.client.get_redeem_need_goods(**kwargs))
def get_grow_level_user_info(self, **kwargs):
return self._run(self.client.get_grow_level_user_info(**kwargs))
__all__ = ["HuyaEliteWssSession"]
+19
View File
@@ -215,6 +215,25 @@ def _decode_wup_body(body: bytes) -> dict:
return result
def decode_struct_bytes(data: bytes) -> dict:
"""把裸结构体字节解成通用 dict(``tagN`` → 值);非结构体或解析失败返回 {}。
WSS 与 HTTP 两条通道都要用「未逐字段建模」的通用解码,统一放在这里,
避免两边各写一份。
"""
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 {}
def _truncate(obj, max_str=80):
"""截断过长的值,使日志紧凑"""
if isinstance(obj, str):
+487 -67
View File
@@ -11,13 +11,27 @@ import base64
import hashlib
import json
import random
import re
import time
import urllib.parse
import urllib.request
from collections.abc import Callable
from typing import Any
from .cookie_utils import cookie_pairs, normalize_cookie_pairs, normalize_huya_cookie
from .frame_decoder import decode_struct_bytes
from .taf_protocol import TafInputStream, TafOutputStream, TafStruct
# 积分中心链路常量与 WSS 通道共用(wss_client 不反向依赖本模块,无循环导入)
from .wss_client import (
GAME_CATEGORY_ID_HUYA,
JIFENCENTER_BIZ_PARAMS,
ORDER_BIZ_TYPE,
ORDER_SCENE,
POINTS_PAY_CALLBACK,
POINTS_REDEEM_GOODS_NUM,
SHOP_APP_SCENE,
)
from .wup_protocol import WupRequest, WupResponse
CDNWS_HOST = "cdnws.api.huya.com"
@@ -121,6 +135,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 客户端"""
@@ -218,8 +258,8 @@ class HuyaHttpClient:
return user
@staticmethod
def _build_shop_app(source_id: str = "yellowcarlist", scene: int = 7):
"""构造 HTTP 业务 ShopAppInfo。"""
def _build_shop_app(source_id: str = "yellowcarlist", scene: int = SHOP_APP_SCENE):
"""构造 HTTP 业务 ShopAppInfo(积分中心抓包 scene=7)。"""
from .shop_structs import ShopAppInfo
info = ShopAppInfo()
@@ -230,15 +270,12 @@ class HuyaHttpClient:
return info
@staticmethod
def _build_order_env(item_count: int = 1):
"""构造下单/支付环境参数。"""
import time
def _build_order_env():
"""构造下单/支付环境参数。
click_time = int(time.time() * 1000)
return {
"user_click_seq": f'[{{"x":258,"y":487,"time":{click_time},"id":""}}]',
"input_1": str(item_count),
}
2026-10-13 积分中心抓包:仅一个空点击序列,没有旧版坐标数组与 input_1。
"""
return {"user_click_seq": "[]"}
@staticmethod
def _build_activity_user(uid: int, cookie: str):
@@ -261,6 +298,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 +311,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 +339,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 +390,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,
@@ -847,13 +922,13 @@ class HuyaHttpClient:
sku_id=0,
game_id="",
source_id="yellowcarlist",
scene=7,
app_scene=SHOP_APP_SCENE,
):
from .shop_structs import GetGoodsInfoReqV5, GoodsInfoRsp
req = GetGoodsInfoReqV5()
req.userId = self._build_shop_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
@@ -876,7 +951,7 @@ class HuyaHttpClient:
req = ListPayChannelReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", 4)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.supplierId = int(supplier_id or 0)
req.spuId = spu_id
req.skuId = int(sku_id or 0)
@@ -898,7 +973,7 @@ class HuyaHttpClient:
req = CheckHyProtocolReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", 4)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
return self.call_rpc(
"shopMiddleUI",
"checkHyProtocolV5",
@@ -923,7 +998,7 @@ class HuyaHttpClient:
req = CheckUserBuyAuthReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", 4)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.spuId = spu_id
req.skuId = int(sku_id or 0)
return self.call_rpc(
@@ -990,7 +1065,7 @@ class HuyaHttpClient:
req = OrderDetailReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", 4)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.orderId = int(order_id or 0)
return self.call_rpc(
"shopMiddleUI",
@@ -1014,10 +1089,16 @@ class HuyaHttpClient:
item_count=1,
source_id="yellowcarlist",
game_id="",
scene=7,
order_type=None,
app_scene=SHOP_APP_SCENE,
order_scene=ORDER_SCENE,
order_type=6,
biz_params=JIFENCENTER_BIZ_PARAMS,
):
"""order_type=None 时自动尝试从 1 到 10 找到有效值"""
"""下单(HTTP 通道),参数与 2026-10-13 积分中心抓包一致。
旧实现会从 orderType=1 试到 10,失败重试有重复下单风险;抓包已确认
和平精英虚拟商品固定 orderType=6,这里改为单次调用。
"""
from .shop_structs import (
CreateOrderAccountParam,
CreateOrderExtraParam,
@@ -1026,47 +1107,40 @@ class HuyaHttpClient:
CreateOrderRsp,
)
# 如果指定了具体值,直接试
types_to_try = [order_type] if order_type is not None else list(range(1, 11))
req = CreateOrderReqV5()
req.userId = self._build_shop_user(uid, cookie)
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 = order_scene
req.scene = 0
req.sourceId = source_id
req.orderType = order_type
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 = ORDER_BIZ_TYPE
req.gameCategoryId = GAME_CATEGORY_ID_HUYA
req.ext = ""
last_result = None
for ot in types_to_try:
req = CreateOrderReqV5()
req.userId = self._build_shop_user(uid, 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: Any = self.call_rpc(
"shopMiddleUI", "createOrderV5", req, CreateOrderRsp, uid, guid, cookie
result: Any = self.call_rpc(
"shopMiddleUI", "createOrderV5", req, CreateOrderRsp, uid, guid, cookie
)
if result is not None:
self.logger(
f" createOrderV5: code={result.code} orderId={result.orderId} msg={result.message}"
)
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
else:
self.logger(" createOrderV5: 无响应")
return result
@staticmethod
def _normalize_pay_channel(pay_type) -> str:
@@ -1087,27 +1161,27 @@ class HuyaHttpClient:
pay_type=1,
pid=0,
source_id="yellowcarlist",
scene=7,
app_scene=SHOP_APP_SCENE,
item_count=1,
):
"""发起支付,结构与 WSS HAR 中 payOrderSubmitV5 对齐。"""
"""发起支付(HTTP 通道),字段与 2026-10-13 积分中心抓包一致。"""
from .shop_structs import PayOrderRes
os = TafOutputStream()
os.write_struct_begin(0)
os.write_struct(0, self._build_shop_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, self._normalize_pay_channel(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}"
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_map(6, self._build_order_env())
os.write_string(7, "null")
os.write_string(8, "")
os.write_struct_end()
@@ -1160,6 +1234,268 @@ class HuyaHttpClient:
result = wup_resp.readStruct("tResp", PayOrderRes)
return result
# ============================================================
# 积分中心链路新增 RPC(HTTP 通道版本,参数与 WSS 侧一致)
# ============================================================
@staticmethod
def _raw_from_wup(wup_resp: WupResponse):
"""已解码的 WUP 响应 → ShopRawRsp(未逐字段建模的接口用)。"""
from .shop_structs import ShopRawRsp
data = wup_resp.newdata.get("tRsp") or wup_resp.newdata.get("tResp")
payload = decode_struct_bytes(data) if isinstance(data, bytes) else {}
return ShopRawRsp.from_payload(payload)
def get_supplier_info(
self,
uid: int,
guid: str,
cookie: str,
supplier_id: int = 87401,
timeout: float = 15.0,
):
"""shopMiddleUI.getSupplierInfoV5(供应商/小店信息)。"""
from .shop_structs import GetSupplierInfoReqV5
req = GetSupplierInfoReqV5()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.supplierId = int(supplier_id or 0)
resp = self.call_rpc(
"shopMiddleUI",
"getSupplierInfoV5",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def accept_hy_protocol(
self, uid: int, guid: str, cookie: str, timeout: float = 15.0
):
"""shopMiddleUI.acceptHyProtocolV5(同意商城协议)。"""
from .shop_structs import AcceptHyProtocolReq, ShopCodeRsp
req = AcceptHyProtocolReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
return self.call_rpc(
"shopMiddleUI",
"acceptHyProtocolV5",
req,
ShopCodeRsp,
uid,
guid,
cookie,
timeout=timeout,
)
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 = 9815,
timeout: float = 15.0,
):
"""shopMiddleUI.calcOrderPromotion(下单前试算)。"""
from .shop_structs import CalcOrderPromotionReqV5, shop_spu_number
spu_num = shop_spu_number(spu_id)
req = CalcOrderPromotionReqV5()
req.userId = self._build_shop_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)
resp = self.call_rpc(
"shopMiddleUI",
"calcOrderPromotion",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def play_mall_query_allocation(
self,
uid: int,
guid: str,
cookie: str,
source_id: str = "yellowcarlist",
page_code: str = "heping_baodian_credit_center_page",
timeout: float = 15.0,
):
"""PlayMallUI.queryAllocation(积分中心配额查询)。"""
from .shop_structs import PlayMallQueryAllocationReq
req = PlayMallQueryAllocationReq()
req.userId = self._build_shop_user(uid, cookie)
req.pageCode = page_code
req.appInfo.sourceId = source_id
resp = self.call_rpc(
"PlayMallUI",
"queryAllocation",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
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 = 87401,
game_id: int = 9815,
source_id: str = "yellowcarlist",
timeout: float = 15.0,
):
"""PlayMallUI.getMyPromotion(返利/促销查询)。"""
from .shop_structs import (
PlayMallGetMyPromotionReq,
PromotionGoodsKey,
shop_spu_number,
)
spu_num = shop_spu_number(spu_id)
req = PlayMallGetMyPromotionReq()
req.userId = self._build_shop_user(uid, cookie)
req.appInfo.sourceId = 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
resp = self.call_rpc(
"PlayMallUI",
"getMyPromotion",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def get_user_profile(
self,
uid: int,
guid: str,
cookie: str,
target_uid: int = 0,
timeout: float = 15.0,
):
"""huyauserui.getUserProfile(单个用户资料,资料在 tag0.tag0)。"""
from .shop_structs import GetUserProfileReq
req = GetUserProfileReq()
req.userId = self._build_shop_user(uid, cookie)
req.targetUid = int(target_uid or uid or 0)
resp = self.call_rpc(
"huyauserui",
"getUserProfile",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def get_follow_wechat_status(
self, uid: int, guid: str, cookie: str, timeout: float = 15.0
):
"""wupui.getUserFollowWeChatOfficialStatus(是否关注公众号)。"""
from .shop_structs import FollowWeChatStatusReq
req = FollowWeChatStatusReq()
req.userId = self._build_shop_user(uid, cookie)
resp = self.call_rpc(
"wupui",
"getUserFollowWeChatOfficialStatus",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def get_redeem_need_goods(
self,
uid: int,
guid: str,
cookie: str,
goods_num: int = POINTS_REDEEM_GOODS_NUM,
timeout: float = 15.0,
):
"""shopMiddleUI.getRedeemNeedGoods(当前积分 tag2 / 兑换门槛 tag3)。"""
from .shop_structs import GetRedeemNeedGoodsReq
req = GetRedeemNeedGoodsReq()
req.userId = self._build_shop_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.goodsNum = int(goods_num or 0)
resp = self.call_rpc(
"shopMiddleUI",
"getRedeemNeedGoods",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def get_grow_level_user_info(
self, uid: int, guid: str, cookie: str, timeout: float = 15.0
):
"""GameBizUI.getGrowLevelUserInfo(成长值 tag1.tag0 / 等级 tag1.tag1)。"""
from .shop_structs import GetGrowLevelUserInfoReq
req = GetGrowLevelUserInfoReq()
req.userId = self._build_shop_user(uid, cookie)
resp = self.call_rpc(
"GameBizUI",
"getGrowLevelUserInfo",
req,
None,
uid,
guid,
cookie,
timeout=timeout,
)
return self._raw_from_wup(resp) if isinstance(resp, WupResponse) else None
def _self_check():
uid = 1199647239697
@@ -1189,5 +1525,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()
+343
View File
@@ -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,344 @@ 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
@classmethod
def from_payload(cls, payload: dict | None) -> "ShopRawRsp":
"""从通用解码结果构造:code/message 支持扁平与嵌套(tag0.tag0/tag0.tag1)两种形态。"""
data = payload or {}
code = 0
message = ""
head = data.get("tag0")
if isinstance(head, int):
code = int(head)
if isinstance(data.get("tag1"), str):
message = data["tag1"]
elif isinstance(head, dict):
if isinstance(head.get("tag0"), int):
code = int(head["tag0"])
if isinstance(head.get("tag1"), str):
message = head["tag1"]
return cls(code=code, message=message, payload=data)
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
class GetRedeemNeedGoodsReq(ShopAppRequest):
"""shopMiddleUI.getRedeemNeedGoods 请求(兑换所需商品 + 当前积分)。
tag2 是兑换商品的数字商品号(抓包为精英宝典兑换商品 ``hy-8315982`` →
``8315982``);传错会返回 500「系统异常」,所以调用方必须给真实商品号。
"""
def __init__(self):
super().__init__()
self.goodsNum: 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.goodsNum)
def read_from(self, ins: TafInputStream):
pass
class GetGrowLevelUserInfoReq(TafStruct):
"""GameBizUI.getGrowLevelUserInfo 请求(抓包 tReq 只有 tag0 UserId)。"""
def __init__(self):
self.userId = UserId() # tag 0
def write_to(self, os: TafOutputStream):
os.write_struct(0, self.userId)
def read_from(self, ins: TafInputStream):
self.userId = ins.read_struct(0, UserId) or self.userId
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
+24 -1
View File
@@ -431,6 +431,28 @@ class TafInputStream:
result.append(self._read_value(it, item_reader))
return result
#: 结构体尾部允许跳过的未解析字段上限(解析错位时避免无限吞字节)
STRUCT_TAIL_SKIP_LIMIT = 32
def skip_to_struct_end(self) -> int:
"""跳过结构体尾部未建模的字段,返回跳过的字段数(STRUCT_END 不消费)。
服务端会给结构体追加新字段(常见是值为 0 的 ZERO 类型:例如
checkUserBindGameAccount 响应在 tag5 之后多出 tag6=ZERO)。读取方只消费
自己认识的字段,其余按 TAF 语义跳过,由 read_struct 统一收尾 ——
否则一个新增字段就会让整个 RPC 解析失败、上层读到 None。
"""
skipped = 0
while skipped < self.STRUCT_TAIL_SKIP_LIMIT:
pos = self.buf.tell()
_tag, dtype = self.read_head()
if dtype == TafType.STRUCT_END:
self.buf.seek(pos)
return skipped
self.skip_field(dtype)
skipped += 1
raise ValueError("结构体尾部未解析字段过多,疑似解析错位")
def read_struct(self, tag: int, struct_class, required: bool = False):
"""读取结构体,struct_class 需有无参构造 + read_from"""
found = self._find_tag(tag, required)
@@ -440,7 +462,8 @@ class TafInputStream:
raise ValueError(f"期望 struct, 实际 0x{found[1]:02x}")
obj = struct_class()
obj.read_from(self)
# 消费 STRUCT_END
# 尾部未建模字段先跳过,再消费 STRUCT_END
self.skip_to_struct_end()
_t, dt = self.read_head()
if dt != TafType.STRUCT_END:
raise ValueError(f"期望 STRUCT_END, 实际 0x{dt:02x}")
+381 -111
View File
@@ -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
@@ -27,7 +26,12 @@ from typing import Any, cast
import websockets
from .cookie_utils import cookie_pairs, normalize_cookie_pairs
from .frame_decoder import _decode_taf_struct, _truncate, format_wss_log
from .frame_decoder import (
_decode_taf_struct,
_truncate,
decode_struct_bytes,
format_wss_log,
)
from .taf_protocol import TafInputStream, TafOutputStream, TafStruct, TafType
from .wup_protocol import WupRequest, WupResponse
@@ -43,6 +47,38 @@ 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
# getRedeemNeedGoods 的兑换商品号:抓包里的精英宝典兑换商品 hy-8315982 → 8315982。
# 服务端只认这个商品号(传 0/其它值直接 500「系统异常」)。
POINTS_REDEEM_GOODS_NUM = 8315982
# createOrderV5 的 extraParam.bizParams:标记「积分中心」来源,缺了会走成普通商城单。
JIFENCENTER_BIZ_PARAMS = '{ "jifencenter": 1 }'
class _ActivityConfigReq(TafStruct):
def __init__(self, user):
@@ -67,6 +103,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 +160,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 +280,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 +292,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 +444,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 +467,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 +569,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 +601,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 +698,7 @@ class HuyaWssClient:
cookie: str,
sequence: int = SEQ_WSLAUNCH,
guid: str = "",
ua: str = "",
):
"""cmd 0x0a AUTH — 对齐 9.1 抓包(828 活动帧)。
@@ -624,12 +712,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 +747,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 +801,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 +816,37 @@ 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")
return decode_struct_bytes(data) if isinstance(data, bytes) else {}
@classmethod
def _raw_rsp_from_body(cls, body: bytes):
"""响应 → ShopRawRsp(code/message + 通用解码结构)。"""
from .shop_structs import ShopRawRsp
return ShopRawRsp.from_payload(cls._decode_rsp_dict(body))
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 +855,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 +918,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 +1096,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 +1117,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 +1134,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 +1175,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 +1199,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 +1214,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 +1252,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 +1262,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 +1320,165 @@ 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
)
async def get_redeem_need_goods(
self,
uid: int,
guid: str,
cookie: str,
goods_num: int = POINTS_REDEEM_GOODS_NUM,
):
"""shopMiddleUI.getRedeemNeedGoods — 兑换所需商品与当前积分。
响应:``tag2`` 当前积分、``tag3`` 兑换门槛积分(抓包 + 真机实证)。
"""
from .shop_structs import GetRedeemNeedGoodsReq
req = GetRedeemNeedGoodsReq()
req.userId = self._build_biz_user(uid, cookie)
req.shopAppInfo = self._build_shop_app("yellowcarlist", SHOP_APP_SCENE)
req.goodsNum = int(goods_num or 0)
return await self.call_rpc_raw("shopMiddleUI", "getRedeemNeedGoods", req)
async def get_grow_level_user_info(self, uid: int, guid: str, cookie: str):
"""GameBizUI.getGrowLevelUserInfo — 成长值/成长等级/昵称。
响应:``tag1.tag0`` 成长值、``tag1.tag1`` 成长等级、``tag2`` 昵称、
``tag3`` 头像(抓包 + 真机实证)。
"""
from .shop_structs import GetGrowLevelUserInfoReq
req = GetGrowLevelUserInfoReq()
req.userId = self._build_biz_user(uid, cookie)
return await self.call_rpc_raw("GameBizUI", "getGrowLevelUserInfo", req)
+545
View File
@@ -0,0 +1,545 @@
"""虎牙精英宝典开通状态与「一键查询」(2026-10-15 真机实测)。
判定来源与真机结论:
* 宝典开通状态 = 积分中心 ``shopMiddleUI.getRedeemNeedGoods`` 的 ``tag5``。
下面固化的两段响应字节分别来自已开通账号(hy_302016799)与未开通账号
(hy_260034554),与网页显示的「已开通精英宝典 / 获取积分需先开通精英宝典」
一致。
* 开通时间 = ``revenueWebUI.queryUserOrderList`` 里已支付的宝典订单。
"""
import json
from types import SimpleNamespace
from core.huya.frame_decoder import decode_struct_bytes
from core.huya.http_client import HuyaHttpClient
from core.huya.shop_structs import ShopRawRsp
from web.backend.models import HuyaAccount
from web.backend.services.huya_pay_link import pay_qr_path
from web.backend.services.huya_runner import HuyaBatchRunner
UID = 1199668595203
COOKIE = f"yyuid={UID}; udb_uid={UID}"
# 真机 getRedeemNeedGoods 响应:已开通(tag5=1、tag6=1、tag7 为空)
REDEEM_OPENED_HEX = "0a0100c8160ce69fa5e8afa2e68890e58a9f21011830144c50016001790c0b"
# 真机 getRedeemNeedGoods 响应:未开通(tag5=0、tag6=0、tag7 列出开通套餐)
REDEEM_NOT_OPENED_HEX = (
"0a0100c8160ce69fa5e8afa2e68890e58a9f2c301440145c6c7900040a02007f134f1200"
"765c0b260ce7b2bee88bb1e5ae9de585b830054101fb51012c610bb87c9001a90cb90cca010"
"bb8110bb82c310bb8490c5c610bb8790c8c9cacbcccdc0bf00f010b0a02007ede691200766"
"17f2616e5bc80e9809ae5ae9de585b82be7b2bee88bb1e5b88130054101fc51012d610bc2"
"70018900020a02007ede6912007f134f2200765c0b310bb841012c5001660ce7b2bee88bb1"
"e5ae9de585b87c0b0a02007ede6912007f10bc220076662f300a400150016609e7b2bee88b"
"b1e5b88170010b9ca90cb90cca010bc2110bc22c310bc2490c5c610bc2790c8c9cacbcccdc0b"
"fc0f0b"
)
# 真机订单列表里已支付的宝典订单(pay_time 与 spu 均来自真机响应)
PAID_ELITE_ORDER = {
"item_name": "精英宝典",
"order_status": 60,
"pay_time": 1791895396000,
"goods_detail": {"spu_id": "hy-8328015", "sku_id": 7756811},
}
UNPAID_ELITE_ORDER = {
"item_name": "精英宝典",
"order_status": 10,
"pay_time": 0,
"goods_detail": {"spu_id": "hy-8328015", "sku_id": 7756811},
}
OTHER_ORDER = {
"item_name": "电竞徽章",
"order_status": 60,
"pay_time": 1788000000000,
"goods_detail": {"spu_id": "hy-7000000", "sku_id": 1},
}
# 真机 queryAllocation 响应里的赛季节点(精英宝典福利季丨Q4:2026-10-09 ~ 2026-12-31)
ALLOCATION_SEASON_PAYLOAD = {
"tag0": {"tag0": 200, "tag1": "成功", "tag2": ""},
"tag1": {
"tag0": "和平精英宝典积分中心",
"tag1": "heping_baodian_credit_center_page",
},
"tag2": [
{"tag0": 343, "tag4": 6},
{
"tag0": 1,
"tag2_2": {
"tag0": {
"tag0": 15,
"tag1": "精英宝典福利季",
"tag2": "精英宝典福利季丨Q4",
"tag3": 3203,
"tag5": 17096,
"tag6": 9815,
"tag10": 1791475200000,
"tag11": 1798732799000,
},
"tag4": {"tag0": 300},
},
},
],
}
def _redeem(hex_text: str) -> ShopRawRsp:
return ShopRawRsp.from_payload(decode_struct_bytes(bytes.fromhex(hex_text)))
class _FakeOrder:
def __init__(self, payload: dict):
self._payload = payload
def to_dict(self) -> dict:
return dict(self._payload)
class _FakeOrderList:
def __init__(self, orders: list[dict], total_count: int | None = None):
self.orders = [_FakeOrder(item) for item in orders]
self.totalCount = len(orders) if total_count is None else total_count
class _FakeBindStatus:
"""只喂给 EliteMixin 用到的那几个字段(角色解析由 BindMixin 自己的用例覆盖)。"""
def __init__(self, status: int = 200, msg: str = ""):
self.status = status
self.msg = msg
def to_dict(self) -> dict:
return {"status": self.status, "msg": self.msg}
class _StubClient:
"""积分中心通道的假客户端:可返回宝典状态/订单列表/赛季配置,并记录调用。"""
def __init__(self, redeem=None, order_pages=None, season: bool = False):
self.redeem = redeem
self.order_pages = order_pages or []
self.season_payload = ALLOCATION_SEASON_PAYLOAD if season else None
self.calls: list[tuple[str, dict]] = []
self.redeem_calls = 0
def get_redeem_need_goods(self, **kwargs):
self.calls.append(("get_redeem_need_goods", kwargs))
self.redeem_calls += 1
return self.redeem
def play_mall_query_allocation(self, **kwargs):
self.calls.append(("play_mall_query_allocation", kwargs))
if self.season_payload is None:
return None
return ShopRawRsp.from_payload(self.season_payload)
def query_user_order_list(self, **kwargs):
self.calls.append(("query_user_order_list", kwargs))
offset = int(kwargs.get("offset") or 0)
index = offset // 20
if index >= len(self.order_pages):
return None
page = self.order_pages[index]
return _FakeOrderList(page, total_count=sum(len(p) for p in self.order_pages))
def _runner(monkeypatch, shop_client, activity_client=None):
runner = HuyaBatchRunner(db=None, batch_id="test-batch", task_type="query_all")
marks: list[tuple[str, str, dict | None]] = []
logs: list[tuple[str, str]] = []
monkeypatch.setattr(
runner, "_shop_client", lambda uid, cookie: shop_client, raising=False
)
if activity_client is not None:
monkeypatch.setattr(
runner,
"_activity_client",
lambda uid, cookie: activity_client,
raising=False,
)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
raising=False,
)
monkeypatch.setattr(
runner,
"_push_log",
lambda level, message: logs.append((level, message)),
raising=False,
)
return runner, marks, logs
def test_real_redeem_bytes_report_elite_opened():
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
assert runner._elite_opened_from_redeem(_redeem(REDEEM_OPENED_HEX)) is True
assert runner._elite_opened_from_redeem(_redeem(REDEEM_NOT_OPENED_HEX)) is False
# 不是 200 或没有 tag5 时不下结论(界面显示「未查询」而不是猜一个值)
assert runner._elite_opened_from_redeem(None) is None
assert (
runner._elite_opened_from_redeem(ShopRawRsp.from_payload({"tag0": 500})) is None
)
def test_elite_open_time_uses_latest_paid_handbook_order():
client = _StubClient(
order_pages=[[OTHER_ORDER, UNPAID_ELITE_ORDER, PAID_ELITE_ORDER]]
)
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
assert runner._resolve_elite_open_time(client, UID, COOKIE) == 1791895396000
def test_elite_open_time_ignores_unpaid_handbook_order():
"""未支付的宝典订单不算开通时间(真机:order_status=10、pay_time=0)。"""
client = _StubClient(order_pages=[[UNPAID_ELITE_ORDER]])
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
assert runner._resolve_elite_open_time(client, UID, COOKIE) is None
def test_elite_open_time_scans_following_pages():
later_order = {**PAID_ELITE_ORDER, "pay_time": 1792000000000}
client = _StubClient(order_pages=[[OTHER_ORDER] * 20, [later_order]])
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
assert runner._resolve_elite_open_time(client, UID, COOKIE) == 1792000000000
offsets = [
kwargs.get("offset")
for name, kwargs in client.calls
if name == "query_user_order_list"
]
assert offsets == [0, 20]
def test_extract_elite_season_from_allocation_payload():
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
season = runner._extract_elite_season(ALLOCATION_SEASON_PAYLOAD)
assert season == {
"name": "精英宝典福利季丨Q4",
"start_ms": 1791475200000,
"end_ms": 1798732799000,
"config_id": 15,
}
# 认不出赛季结构时不下结论(界面就不显示有效期)
assert runner._extract_elite_season({"tag0": {"tag1": "x"}}) is None
assert runner._extract_elite_season(None) is None
def test_query_all_fills_expire_time_from_season(monkeypatch):
shop_client = _StubClient(
redeem=_redeem(REDEEM_OPENED_HEX),
order_pages=[[PAID_ELITE_ORDER]],
season=True,
)
runner, marks, _logs = _runner(monkeypatch, shop_client, activity_client=object())
monkeypatch.setattr(
runner, "_resolve_bind_status", lambda **kwargs: (None, {}), raising=False
)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_all(
None, None, account, {"uid": UID, "cookie": COOKIE}, {"bind_act_id": "9271"}
)
status, message, result = marks[-1]
assert status == "success"
assert result["elite_expire_time"] == 1798732799
assert result["elite_season"]["name"] == "精英宝典福利季丨Q4"
assert account.elite_expire_time == 1798732799
assert "有效期至 2026-12-31" in message
def test_refresh_elite_open_after_payment_retries_until_opened():
"""刚支付完 tag5 可能还是 0(交付延迟)→ 重试到已开通,并写回账号。"""
class _FlakyClient(_StubClient):
def get_redeem_need_goods(self, **kwargs):
result = super().get_redeem_need_goods(**kwargs)
if self.redeem_calls > 1:
return _redeem(REDEEM_OPENED_HEX)
return result
client = _FlakyClient(season=True)
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="create_recharge_order")
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
state = runner._refresh_elite_open_after_payment(
client,
account,
UID,
COOKIE,
goods_num=8315982,
pay_time_ms=1792053457000,
attempts=3,
interval=0,
)
assert client.redeem_calls == 2 # 第一次未开通 → 重试一次即成功
assert state["elite_opened"] is True
assert state["elite_open_time"] == 1792053457
assert state["elite_expire_time"] == 1798732799
assert state["redeem_points"] == 280
assert account.elite_opened is True
assert account.elite_open_time == 1792053457
assert account.elite_expire_time == 1798732799
def test_refresh_elite_open_after_payment_gives_up_after_attempts():
client = _StubClient(redeem=_redeem(REDEEM_NOT_OPENED_HEX))
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="create_recharge_order")
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
state = runner._refresh_elite_open_after_payment(
client,
account,
UID,
COOKIE,
goods_num=8315982,
pay_time_ms=1792053457000,
attempts=2,
interval=0,
)
assert client.redeem_calls == 2 # 重试到上限
assert state["elite_opened"] is False
assert account.elite_opened is False
assert account.elite_open_time is None
def test_create_recharge_order_confirms_elite_open_after_payment(db, monkeypatch):
"""支付成功后自动确认开通状态:任务结果与账号字段都带上宝典状态。"""
outcome = SimpleNamespace(
ok=True,
message="",
detail={"spu_id": "hy-8328015", "sku_id": 7756811, "name": "精英宝典"},
sku_id=7756811,
product_name="精英宝典",
unit_price=3000,
order_raw={"order_id": 11399999},
pay_raw={"pay_order_id": "pay-1"},
amount=3000,
order_id=11399999,
app_order_id="app-1",
pay_order_id="pay-1",
pay_url="https://example.com/pay",
supplier_name="和平精英官方小店",
promotion={},
promotion_info="本单无返利",
reused_order={},
)
shop_client = _StubClient(redeem=_redeem(REDEEM_OPENED_HEX), season=True)
runner = HuyaBatchRunner(
db=None,
batch_id="t",
task_type="create_recharge_order",
payload={"spu_id": "hy-8328015", "sku_id": 7756811, "count": 1},
)
marks: list[tuple[str, str, dict | None]] = []
monkeypatch.setattr(
runner, "_shop_client", lambda uid, cookie: shop_client, raising=False
)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
raising=False,
)
monkeypatch.setattr(
runner, "_update_task_progress", lambda *args, **kwargs: None, raising=False
)
monkeypatch.setattr(
runner, "_push_log", lambda *args, **kwargs: None, raising=False
)
def fake_wait_payment(**kwargs):
# 真实现会边轮询边写 result,这里照抄「已支付」那几个字段
target = kwargs.get("result")
if isinstance(target, dict):
target.update(
{
"payment_status": "paid",
"payment_status_label": "已支付",
"payment_paid": True,
}
)
return "paid", {"pay_time": 1792053457000}
monkeypatch.setattr(
runner, "_wait_recharge_payment", fake_wait_payment, raising=False
)
monkeypatch.setattr(
"web.backend.services.huya_runner_recharge.run_open_flow",
lambda *args, **kwargs: outcome,
)
# 二维码内容优先用支付宝收银台直达地址(真机:网关 302 后的落点)
monkeypatch.setattr(
"web.backend.services.huya_runner_recharge.resolve_pay_entry_url",
lambda _pay_url, **_kwargs: (
"https://excashier.alipay.com/standard/auth.htm?payOrderId=x.25"
),
)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
db.add(account)
db.commit()
runner._execute_create_recharge_order(
db,
SimpleNamespace(id=587),
account,
{"uid": UID, "cookie": COOKIE},
{"room_pid": "1199650619883", "pay_channel": "Zfb", "sid": "2203"},
)
status, _message, result = marks[-1]
assert status == "success"
assert result["payment_paid"] is True
assert result["elite_opened"] is True
assert result["elite_open_time"] == 1792053457
assert result["elite_expire_time"] == 1798732799
assert result["post_payment_points"] == 280
# 二维码内容给前端两条短地址(原始支付地址 1626 字符,扫码扫不动)
assert result["pay_qr_path"] == pay_qr_path(587)
# 优先用支付宝收银台直达地址(公网域名,localhost 下客户也扫得开)
assert result["pay_cashier_url"].startswith("https://excashier.alipay.com/")
assert account.elite_opened is True
assert account.elite_expire_time == 1798732799
assert account.points == 280
assert account.status == "recharge_paid"
def test_query_all_combines_points_elite_and_role(monkeypatch):
shop_client = _StubClient(
redeem=_redeem(REDEEM_OPENED_HEX), order_pages=[[PAID_ELITE_ORDER]]
)
runner, marks, _logs = _runner(monkeypatch, shop_client, activity_client=object())
monkeypatch.setattr(
runner,
"_resolve_bind_status",
lambda **kwargs: (_FakeBindStatus(), {"bind_status_source": "outer"}),
raising=False,
)
monkeypatch.setattr(
runner,
"_bind_role_result",
staticmethod(
lambda _status: {"role_name": "软踏日潺湲", "game_title": "和平精英"}
),
raising=False,
)
monkeypatch.setattr(
runner,
"_bind_change_state",
staticmethod(lambda _status: {"is_bound": True}),
raising=False,
)
monkeypatch.setattr(
runner,
"_role_channel",
staticmethod(lambda _status: "苹果(iOS) / 手Q"),
raising=False,
)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_all(
None, None, account, {"uid": UID, "cookie": COOKIE}, {"bind_act_id": "9271"}
)
status, message, result = marks[-1]
assert status == "success"
assert result["points"] == 280
assert result["elite_opened"] is True
assert result["elite_open_time"] == 1791895396
assert result["role_name"] == "软踏日潺湲"
assert result["failures"] == []
assert account.points == 280
assert account.elite_opened is True
assert account.elite_open_time == 1791895396
assert account.game_name == "软踏日潺湲"
assert account.game_channel == "苹果(iOS) / 手Q"
assert account.status == "all_queried"
assert (
"积分 280" in message
and "已开通宝典" in message
and "角色 软踏日潺湲" in message
)
def test_query_all_reports_not_opened_without_order_lookup(monkeypatch):
shop_client = _StubClient(redeem=_redeem(REDEEM_NOT_OPENED_HEX))
runner, marks, _logs = _runner(monkeypatch, shop_client, activity_client=object())
monkeypatch.setattr(
runner, "_resolve_bind_status", lambda **kwargs: (None, {}), raising=False
)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_all(
None, None, account, {"uid": UID, "cookie": COOKIE}, {"bind_act_id": "9271"}
)
status, message, result = marks[-1]
# 角色接口挂了不影响宝典/积分结论
assert status == "success"
assert result["elite_opened"] is False
assert account.elite_opened is False
assert account.elite_open_time is None
assert "未开通宝典" in message
assert "角色信息接口无响应" in message
# 未开通不查订单(省一次请求)
assert [name for name, _kwargs in shop_client.calls] == ["get_redeem_need_goods"]
def test_query_all_fails_when_points_center_unreachable(monkeypatch):
shop_client = _StubClient(redeem=None)
runner, marks, _logs = _runner(monkeypatch, shop_client, activity_client=object())
monkeypatch.setattr(
runner, "_resolve_bind_status", lambda **kwargs: (None, {}), raising=False
)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_all(
None, None, account, {"uid": UID, "cookie": COOKIE}, {"bind_act_id": "9271"}
)
status, message, _result = marks[-1]
assert status == "failed"
assert "积分中心接口无响应" in message
def test_shop_client_falls_back_to_http_when_wss_init_fails(monkeypatch):
"""设备态齐全但积分中心端点不回包时(wsLaunch 超时)回退 HTTP,而不是判整批失败。"""
cookie = (
"udb_cred=cred; udb_biztoken=biz; udb_uid=1199659425268; yyuid=1199659425268; "
"sdid=sdid; udb_deviceid=w_1234567890123456789; udb_guiddata=guiddata; "
"udb_anobiztoken=anobiz"
)
logs: list[tuple[str, str]] = []
runner = HuyaBatchRunner(db=None, batch_id="t", task_type="query_all")
def boom(uid: int, cookie_text: str, kind: str):
raise RuntimeError(f"虎牙 {kind} WSS 初始化失败")
monkeypatch.setattr(runner, "_open_wss_session", boom, raising=False)
monkeypatch.setattr(
runner,
"_push_log",
lambda level, message: logs.append((level, message)),
raising=False,
)
client = runner._shop_client(1199659425268, cookie)
assert isinstance(client, HuyaHttpClient)
assert logs and logs[-1][0] == "warning"
assert "WSS 会话不可用" in logs[-1][1]
assert "sdid" not in json.dumps(logs[-1][1]) # 日志不带 Cookie 值
+95
View File
@@ -0,0 +1,95 @@
"""HTTP cdnws 通道的下单/支付参数对齐(2026-10-13 积分中心抓包)。
外部 CK(只有登录态、无网页设备态)会走 HTTP 通道,因此 HTTP 侧的参数必须与
抓包一致:jifencenter 标记、空点击序列、m-shop.huya.com 回调、appInfo.scene 与
订单 src/orderScene 分离。
"""
from core.huya.http_client import HuyaHttpClient
def _recording_client():
client = HuyaHttpClient(logger=lambda _message: None)
recorded: list[tuple[str, str, object]] = []
def fake_call_rpc(
service, method, req_struct, rsp_class=None, uid=0, guid="", cookie="", **kwargs
):
recorded.append((service, method, req_struct))
client.call_rpc = fake_call_rpc # type: ignore[method-assign]
return client, recorded
def test_http_create_order_matches_points_capture():
client, recorded = _recording_client()
client.create_order(
uid=1199665170519,
guid="",
cookie="yyuid=1199665170519",
pid=1199650619883,
spu_id="hy-8328015",
sku_id=7756811,
)
service, method, req = recorded[-1]
assert (service, method) == ("shopMiddleUI", "createOrderV5")
assert req.shopAppInfo.scene == 7 # appInfo scene
assert req.src == 4 # 订单侧 scene
assert req.orderScene == 4
assert req.orderType == 6
assert req.extraParam.bizParams == '{ "jifencenter": 1 }'
assert req.env == {"user_click_seq": "[]"}
assert req.bizType == 5
assert req.gameCategoryId == 507
def test_http_get_goods_info_uses_app_scene():
client, recorded = _recording_client()
client.get_goods_info(
uid=1199665170519,
guid="",
cookie="yyuid=1199665170519",
pid=1199650619883,
spu_id="hy-8328015",
)
service, method, req = recorded[-1]
assert (service, method) == ("shopMiddleUI", "getGoodsInfoV5")
assert req.shopAppInfo.scene == 7
assert req.pid == 1199650619883
assert req.spuId == "hy-8328015"
def test_http_pay_order_submit_points_callback_and_env(monkeypatch):
captured: dict[str, bytes] = {}
class _StopAfterCapture(Exception):
pass
def fake_urlopen(request, timeout=None):
captured["body"] = request.data
raise _StopAfterCapture
monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
client = HuyaHttpClient(logger=lambda _message: None)
result = client.pay_order_submit(
uid=1199665170519,
guid="",
cookie="yyuid=1199665170519",
order_id=11339649,
pay_type="Zfb",
pid=1199650619883,
)
assert result is None # 捕获到请求即中断,不关心响应
body = captured["body"]
assert (
b"https://m-shop.huya.com/points.html#/consumer/paycallback"
b"?orderId=11339649&pid=1199650619883&sourceId=yellowcarlist"
) in body
assert b"user_click_seq" in body
assert b"input_1" not in body
+181
View File
@@ -0,0 +1,181 @@
"""开通支付码二维码内容:1600+ 字符的支付地址 → 手机扫得动、打得开的地址。
生产实测(2026-10-15):`payOrderSubmitV5` 返回的支付宝网关地址有 **1626** 字符
(`https://openapi.alipay.com/gateway.do?...&sign=...`)。直接把它编成二维码是
version 29+(140+ 个模块),在 150px 的画面上每个模块只有约 1 像素 —— 手机扫不上。
现在的优先级:
1. **支付宝收银台直达地址**(`resolve_pay_entry_url`):网关地址 302 两次后落到
`https://excashier.alipay.com/standard/auth.htm?payOrderId=...`(约 74 字符),
公网域名,后端跑在 localhost 时客户也扫得开;
2. **本站短链** `/api/huya/pay/<task_id>?k=<hmac>`(约 38 字符):后端 302 跳到网关地址,
但要求本页域名手机能访问到。
"""
import pytest
from fastapi import HTTPException
from web.backend.models import HuyaAccount, HuyaTask, User
from web.backend.routers.huya.pay import redirect_huya_pay
from web.backend.services import huya_pay_link
from web.backend.services.huya_pay_link import (
PAY_PATH_PREFIX,
is_alipay_url,
pay_qr_path,
pay_token,
resolve_pay_entry_url,
verify_pay_token,
)
# 真机取到的支付宝网关地址形态(长度同量级)
ALIPAY_LONG_URL = (
"https://openapi.alipay.com/gateway.do"
"?alipay_sdk=alipay-sdk-java-4.40.272.ALL&app_id=2017123456789012"
"&method=alipay.trade.page.pay&sign=" + "a" * 1500
)
# 真机实测:上面的网关地址 302 两次后的落点(任务 191 原样取回)
CASHIER_URL = (
"https://excashier.alipay.com/standard/auth.htm"
"?payOrderId=6cb86f1d259642ac843522b85dab8a52.25"
)
def _create_pay_task(db, pay_url: str) -> HuyaTask:
user = User(username="pay-link-test", password_hash="x", role="support")
db.add(user)
db.commit()
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
task = HuyaTask(
batch_id="test-batch",
account_id=account.id,
task_type="create_recharge_order",
handbook_scope="elite",
status="running",
created_by=user.id,
result={"pay_url": pay_url} if pay_url else {},
)
db.add(task)
db.commit()
return task
def test_pay_token_round_trip_and_rejects_others():
token = pay_token(587)
assert len(token) == 16
assert verify_pay_token(587, token) is True
# 大小写不同就是另一个签名(hex 严格比对)
assert verify_pay_token(587, token.upper()) is False
assert verify_pay_token(587, "") is False
assert verify_pay_token(588, token) is False
def test_pay_qr_path_is_short_enough_to_scan():
path = pay_qr_path(587)
assert path.startswith(f"{PAY_PATH_PREFIX}/587?k=")
# 短链必须足够短:36 字符 → 二维码约 30 个模块(长链是 140+ 个模块)
assert len(path) <= 48
# 原始支付地址长度对比(就是它导致扫不上)
assert len(ALIPAY_LONG_URL) > 1000
def test_pay_redirect_route_returns_pay_url(db):
task = _create_pay_task(db, ALIPAY_LONG_URL)
response = redirect_huya_pay(task.id, pay_token(task.id), db)
assert response.status_code == 302
assert response.headers["location"] == ALIPAY_LONG_URL
def test_pay_redirect_route_rejects_bad_token(db):
task = _create_pay_task(db, ALIPAY_LONG_URL)
with pytest.raises(HTTPException) as excinfo:
redirect_huya_pay(task.id, "deadbeefdeadbeef", db)
assert excinfo.value.status_code == 404
def test_pay_redirect_route_rejects_task_without_pay_url(db):
task = _create_pay_task(db, "")
with pytest.raises(HTTPException) as excinfo:
redirect_huya_pay(task.id, pay_token(task.id), db)
assert excinfo.value.status_code == 404
class _FakeResponse:
"""假的 requests 响应:只需要 ``url`` 和 ``close()``。"""
def __init__(self, url: str):
self.url = url
self.closed = False
def close(self) -> None:
self.closed = True
def _patch_get(monkeypatch, *, final_url: str | None = None, error=None):
calls: list[dict] = []
def fake_get(url, **kwargs):
calls.append({"url": url, **kwargs})
if error is not None:
raise error
return _FakeResponse(final_url or "")
monkeypatch.setattr(huya_pay_link.requests, "get", fake_get)
return calls
def test_resolve_pay_entry_url_follows_redirect_to_cashier(monkeypatch):
calls = _patch_get(monkeypatch, final_url=CASHIER_URL)
assert resolve_pay_entry_url(ALIPAY_LONG_URL) == CASHIER_URL
assert calls[0]["url"] == ALIPAY_LONG_URL
# 必须跟随 302,否则拿到的是网关页自己
assert calls[0]["allow_redirects"] is True
assert "Mozilla" in calls[0]["headers"]["User-Agent"]
def test_resolve_pay_entry_url_rejects_non_alipay_target(monkeypatch):
"""落到非支付宝域名就当没解析出来(调用方回落到本站短链)。"""
_patch_get(monkeypatch, final_url="https://evil.example.com/cashier")
assert resolve_pay_entry_url(ALIPAY_LONG_URL) == ""
def test_resolve_pay_entry_url_swallows_errors(monkeypatch):
_patch_get(monkeypatch, error=RuntimeError("network down"))
assert resolve_pay_entry_url(ALIPAY_LONG_URL) == ""
def test_resolve_pay_entry_url_ignores_blank_or_relative():
assert resolve_pay_entry_url("") == ""
assert resolve_pay_entry_url("/api/huya/pay/191?k=x") == ""
def test_resolve_pay_entry_url_is_shorter_than_raw_url(monkeypatch):
_patch_get(monkeypatch, final_url=CASHIER_URL)
resolved = resolve_pay_entry_url(ALIPAY_LONG_URL)
# 收银台直达地址约 74 字符 → 二维码模块数远低于原始地址
assert len(resolved) < 120
assert len(resolved) < len(ALIPAY_LONG_URL)
def test_is_alipay_url_matches_only_alipay_domains():
assert is_alipay_url(CASHIER_URL) is True
assert is_alipay_url("https://openapi.alipay.com/gateway.do?x=1") is True
assert is_alipay_url("https://alipay.com/") is True
assert is_alipay_url("https://alipay.com.evil.com/") is False
assert is_alipay_url("https://excashier.alipay.com.evil.com/") is False
assert is_alipay_url("") is False
+295
View File
@@ -0,0 +1,295 @@
"""查询积分改走积分中心新接口(2026-10-15 真机实测)。
背景:旧活动接口 ``webActUI.getUserScore`` 对任何 sid 都返回
603「活动已结束」(该接口已下线,与工作台里的 SID/活动配置无关);
积分中心用 ``shopMiddleUI.getRedeemNeedGoods`` 查积分:
``tag2``=当前积分、``tag3``=兑换门槛。下面固化的响应字节来自真机 HTTP 通道。
抓包/真机字面值直接写在测试里(不引用实现常量),避免断言跟着实现漂移。
"""
import asyncio
from core.huya.activity_structs import GetUserScoreResp
from core.huya.frame_decoder import _decode_wup_body, decode_struct_bytes
from core.huya.http_client import HuyaHttpClient
from core.huya.shop_structs import ShopRawRsp
from core.huya.wss_client import HuyaWssClient, WssMessage
from web.backend.models import HuyaAccount
from web.backend.services.huya_runner import HuyaBatchRunner
UID = 1199665170519
GUID = "0a8995af9218ce6a340261946294a9e7"
COOKIE = f"udb_uid={UID}; yyuid={UID}; guid={GUID}"
# 真机(2026-10-15,账号 hy_297832664)getRedeemNeedGoods 响应:200 / 积分 280 / 门槛 20
REDEEM_RSP_HEX = "0a0100c8160ce69fa5e8afa2e68890e58a9f21011830144c50016001790c0b"
# 真机 getGrowLevelUserInfo 响应:成长值 980 / 成长等级 3 / 昵称 / 头像
GROW_RSP_HEX = (
"0a0a0c1606e68890e58a9f0b1a0103d41003230000019f124082043c4c50"
"0360ff7101f48103e80b260fe8bdafe8b88fe697a5e6bdbae6b9b236386874"
"7470733a2f2f6469792d6173736574732e6d737374617469632e636f6d2f6371"
"68666f6c6465722f4e657744656661756c742e706e670b"
)
class _FakeWs:
"""记录发出的帧,并立刻兑现 RPC future(离线跑完整链路)。"""
def __init__(self, client: HuyaWssClient):
self.client = client
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(b"")
def last_request(self) -> dict:
return _decode_wup_body(WssMessage.decode(self.sent[-1]).body)
def _points_client() -> HuyaWssClient:
client = HuyaWssClient(logger=lambda _message: None)
client._points_mode = True
client.ws = _FakeWs(client)
return client
def _raw_rsp(payload_hex: str) -> ShopRawRsp:
return ShopRawRsp.from_payload(
decode_struct_bytes(bytes.fromhex("".join(payload_hex.split())))
)
class _StubClient:
"""按需返回真机响应字节的积分中心客户端。"""
def __init__(self, redeem=True, grow=True):
self.redeem = _raw_rsp(REDEEM_RSP_HEX) if redeem else None
self.grow = _raw_rsp(GROW_RSP_HEX) if grow else None
self.calls: list[tuple[str, dict]] = []
def get_redeem_need_goods(self, **kwargs):
self.calls.append(("get_redeem_need_goods", kwargs))
return self.redeem
def get_grow_level_user_info(self, **kwargs):
self.calls.append(("get_grow_level_user_info", kwargs))
return self.grow
class _LegacyClient:
"""旧活动接口:真机实测任何 sid 都返回 603「活动已结束」。"""
def query_user_score(self, uid: int, cookie: str, sid: int):
response = GetUserScoreResp()
response.status = 603
response.msg = "活动已结束"
response.score = 0
return response
def _runner(monkeypatch, client, legacy=None) -> tuple[HuyaBatchRunner, list]:
runner = HuyaBatchRunner(db=None, batch_id="test-batch", task_type="query_points")
marks: list[tuple[str, str, dict | None]] = []
monkeypatch.setattr(
runner, "_shop_client", lambda uid, cookie: client, raising=False
)
if legacy is not None:
monkeypatch.setattr(
runner, "_activity_client", lambda uid, cookie: legacy, raising=False
)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
raising=False,
)
return runner, marks
def test_wss_redeem_need_goods_request_matches_real_call():
async def run():
client = _points_client()
await client.get_redeem_need_goods(uid=UID, guid=GUID, cookie=COOKIE)
message = WssMessage.decode(client.ws.sent[-1])
# 积分中心业务帧统一 0x1d000107(只有下单/支付用 0x1d000108)
assert message.sequence == 0x1D000107
decoded = client.ws.last_request()
assert (decoded["servant"], decoded["func"]) == (
"shopMiddleUI",
"getRedeemNeedGoods",
)
t_req = decoded["tReq"]
assert t_req["tag0"]["tag0"] == UID
assert t_req["tag1"]["tag0"] == "huya"
assert t_req["tag1"]["tag4"] == 7
assert t_req["tag1"]["tag5"] == "yellowcarlist"
# 默认兑换商品号必须是真机可用的 hy-8315982 的数字形式
assert t_req["tag2"] == 8315982
asyncio.run(run())
def test_wss_grow_level_request_carries_only_user_id():
async def run():
client = _points_client()
await client.get_grow_level_user_info(uid=UID, guid=GUID, cookie=COOKIE)
decoded = client.ws.last_request()
assert (decoded["servant"], decoded["func"]) == (
"GameBizUI",
"getGrowLevelUserInfo",
)
t_req = decoded["tReq"]
assert t_req["tag0"]["tag0"] == UID
# 抓包 tReq 只有 tag0,没有 shopAppInfo
assert set(t_req) == {"tag0"}
asyncio.run(run())
def test_http_redeem_need_goods_request_matches_real_call():
client = HuyaHttpClient(logger=lambda _message: None)
recorded: list[tuple] = []
def fake_call_rpc(
service, method, req_struct, rsp_class=None, uid=0, guid="", cookie="", **kwargs
):
recorded.append((service, method, req_struct))
client.call_rpc = fake_call_rpc # type: ignore[method-assign]
client.get_redeem_need_goods(uid=UID, guid="", cookie=COOKIE)
service, method, req = recorded[-1]
assert (service, method) == ("shopMiddleUI", "getRedeemNeedGoods")
assert req.userId.lUid == UID
assert req.shopAppInfo.scene == 7
assert req.shopAppInfo.sourceId == "yellowcarlist"
assert req.goodsNum == 8315982
def test_real_redeem_response_bytes_are_points_and_threshold():
rsp = _raw_rsp(REDEEM_RSP_HEX)
assert rsp.code == 200
assert rsp.message == "查询成功"
# tag2 = 当前积分,tag3 = 兑换门槛积分(真机 280 / 20)
assert rsp.value("tag2") == 280
assert rsp.value("tag3") == 20
def test_real_grow_level_response_bytes_are_level_and_nickname():
rsp = _raw_rsp(GROW_RSP_HEX)
assert rsp.code == 0
assert rsp.message == "成功"
assert rsp.value("tag1", "tag0") == 980 # 成长值
assert rsp.value("tag1", "tag1") == 3 # 成长等级
assert rsp.value("tag2") == "软踏日潺湲"
assert str(rsp.value("tag3")).startswith("https://diy-assets.msstatic.com/")
def test_query_points_reads_points_from_points_center(monkeypatch):
client = _StubClient()
runner, marks = _runner(monkeypatch, client)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_points(
None, None, account, {"uid": UID, "cookie": COOKIE}, {}
)
assert [name for name, _kwargs in client.calls] == [
"get_redeem_need_goods",
"get_grow_level_user_info",
]
assert client.calls[0][1]["goods_num"] == 8315982
status, message, result = marks[-1]
assert status == "success"
assert message == "积分: 280"
assert account.points == 280
assert result["points"] == 280
assert result["redeem_threshold"] == 20
assert result["grow_level"] == 3
assert result["grow_value"] == 980
assert result["nickname"] == "软踏日潺湲"
def test_query_points_keeps_working_when_grow_level_fails(monkeypatch):
client = _StubClient(grow=False)
runner, marks = _runner(monkeypatch, client)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_points(
None, None, account, {"uid": UID, "cookie": COOKIE}, {}
)
status, message, result = marks[-1]
assert status == "success"
assert message == "积分: 280"
assert "grow_level" not in result
def test_query_points_reports_server_error_of_points_center(monkeypatch):
class _FailingClient(_StubClient):
def get_redeem_need_goods(self, **kwargs):
self.calls.append(("get_redeem_need_goods", kwargs))
return ShopRawRsp.from_payload(
decode_struct_bytes(
bytes.fromhex(
"0a0101f4161ee7b3bbe7bb9fe5bc82e5b8b8efbc8ce8afb7e7a88de5"
"908ee9878de8af952c3c4c5c6c0b"
)
)
)
client = _FailingClient()
runner, marks = _runner(monkeypatch, client)
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_points(
None, None, account, {"uid": UID, "cookie": COOKIE}, {}
)
status, message, result = marks[-1]
assert status == "failed"
assert message == "系统异常,请稍后重试"
assert result["code"] == 500
assert result["goods_num"] == 8315982
def test_query_points_fallback_reports_legacy_interface_offline(monkeypatch):
client = _StubClient(redeem=False)
runner, marks = _runner(monkeypatch, client, legacy=_LegacyClient())
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_points(
None, None, account, {"uid": UID, "cookie": COOKIE}, {"sid": "2203"}
)
status, message, _result = marks[-1]
assert status == "failed"
# 旧接口的真实返回必须如实暴露,而不是只报「活动已结束」
assert "旧活动接口(sid=2203)返回 603 活动已结束" in message
assert "积分中心接口无响应" in message
def test_query_points_without_sid_reports_points_center_offline(monkeypatch):
client = _StubClient(redeem=False)
runner, marks = _runner(monkeypatch, client, legacy=_LegacyClient())
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
runner._execute_query_points(
None, None, account, {"uid": UID, "cookie": COOKIE}, {}
)
status, message, _result = marks[-1]
assert status == "error"
assert "积分中心接口无响应" in message
+391
View File
@@ -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
+286
View File
@@ -0,0 +1,286 @@
"""开通商品来源:不再依赖已下线的旧活动任务接口(2026-10-15 真机实测)。
真机现状(账号 hy_297832664,HTTP cdnws 通道):
- ``webActUI.getActTaskDetail(act_id=25135)`` → 601「活动已下线」
- ``shopMiddleUI.getGoodsInfoV5`` 对 hy-8328015 / hy-8327356 / hy-5879340 均 code=200
因此刷新开通商品改为「内置商品候选 + getGoodsInfoV5 详情」,活动任务详情只做可选
补充:它失败只记 warning,不再让整次刷新失败。
"""
from core.huya.activity_structs import GetActTaskDetailResp
from core.huya.frame_decoder import decode_struct_bytes
from core.huya.taf_protocol import TafInputStream, TafType
from web.backend.models import HuyaAccount, HuyaRechargeGoodsSnapshot
from web.backend.services.huya_runner import HuyaBatchRunner
ROOM_PID = 1199650619883
CONFIG = {"room_pid": str(ROOM_PID)}
# 真机 webActUI.getActTaskDetail(act 25135) 响应字节(status=601 / msg=活动已下线)
ACT_TASK_OFFLINE_HEX = "0a010259160fe6b4bbe58aa8e5b7b2e4b88be7babf0b"
# 积分中心页面上的开通商品(getGoodsInfoV5 真机验证 code=200)
BUILTIN_SPU_LITERALS = [
"hy-8328015",
"hy-8327356",
"hy-5872824",
"hy-5879346",
"hy-5874269",
"hy-5874270",
]
class _FakeActTaskDetail:
def __init__(self, status: int, msg: str, tasks: list[dict] | None = None):
self.status = status
self.msg = msg
self._tasks = tasks or []
def to_dict(self) -> dict:
return {
"status": self.status,
"msg": self.msg,
"task_count": len(self._tasks),
"tasks": self._tasks,
}
class _FakeGoodsInfo:
def __init__(self, spu_id: str, sku_id: str, name: str, price: int):
self.code = 200
self.message = ""
self._data = {
"spu_id": spu_id,
"sku_id": sku_id,
"name": name,
"price": price,
"stock": 100,
"buy_limit": 1,
"icon": "",
"description": "",
}
def to_dict(self) -> dict:
return dict(self._data)
class _StubShopClient:
def __init__(self, task: _FakeActTaskDetail | None, goods: bool = True):
self.task = task
self.goods = goods
self.goods_calls: list[str] = []
def get_act_task_detail(self, uid: int, cookie: str, act_id: int):
return self.task
def get_goods_info(self, **kwargs):
self.goods_calls.append(kwargs["spu_id"])
if not self.goods:
return None
return _FakeGoodsInfo(
spu_id=kwargs["spu_id"],
sku_id=f"sku-{kwargs['spu_id']}",
name=f"name-{kwargs['spu_id']}",
price=3000,
)
def _runner(monkeypatch, client) -> tuple[HuyaBatchRunner, list, list]:
runner = HuyaBatchRunner(
db=None, batch_id="test-batch", task_type="refresh_recharge_goods"
)
marks: list[tuple[str, str, dict | None]] = []
logs: list[tuple[str, str]] = []
monkeypatch.setattr(
runner, "_shop_client", lambda uid, cookie: client, raising=False
)
monkeypatch.setattr(
runner,
"_mark_task",
lambda _db, _task, status, message, result=None: marks.append(
(status, message, result)
),
raising=False,
)
monkeypatch.setattr(
runner,
"_push_log",
lambda level, message: logs.append((level, message)),
raising=False,
)
return runner, marks, logs
def test_real_offline_response_bytes_report_activity_offline():
payload = decode_struct_bytes(bytes.fromhex(ACT_TASK_OFFLINE_HEX))
assert payload["tag0"] == 601
assert payload["tag1"] == "活动已下线"
# 结构体解析路径:tRsp 以 STRUCT_BEGIN 包一层(同 WupResponse.readStruct)
ins = TafInputStream(bytes.fromhex(ACT_TASK_OFFLINE_HEX))
_tag, dtype = ins.peek_head()
assert dtype == TafType.STRUCT_BEGIN
ins.read_head()
parsed = GetActTaskDetailResp()
parsed.read_from(ins)
assert (parsed.status, parsed.msg) == (601, "活动已下线")
def test_refresh_recharge_goods_survives_offline_activity(db, monkeypatch):
client = _StubShopClient(_FakeActTaskDetail(601, "活动已下线"))
runner, marks, logs = _runner(monkeypatch, client)
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
runner._execute_refresh_recharge_goods(
db, None, account, {"uid": 1199665170519, "cookie": account.cookie}, CONFIG
)
status, message, result = marks[-1]
assert status == "success"
assert message == "已刷新开通商品 6 个"
assert result["goods_count"] == 6
assert result["task_detail_error"] == "活动已下线"
assert client.goods_calls == BUILTIN_SPU_LITERALS
assert [item["spu_id"] for item in result["goods"]] == BUILTIN_SPU_LITERALS
# 活动接口不可用只记 warning,不把任务标失败
assert logs and logs[-1][0] == "warning" and "活动已下线" in logs[-1][1]
rows = (
db.query(HuyaRechargeGoodsSnapshot)
.filter(HuyaRechargeGoodsSnapshot.account_id == account.id)
.all()
)
assert sorted(row.spu_id for row in rows) == sorted(BUILTIN_SPU_LITERALS)
assert all(row.sku_id for row in rows)
def test_refresh_recharge_goods_still_merges_activity_candidates(db, monkeypatch):
task = _FakeActTaskDetail(
200,
"请求成功",
[
{"task_type": 67, "spu_id": "hy-7770001", "name": "活动商品", "task_id": 5},
{"task_type": 66, "spu_id": "hy-ignore-me", "name": "非充值任务"},
],
)
client = _StubShopClient(task)
runner, marks, logs = _runner(monkeypatch, client)
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
runner._execute_refresh_recharge_goods(
db, None, account, {"uid": 1199665170519, "cookie": account.cookie}, CONFIG
)
status, _message, result = marks[-1]
assert status == "success"
assert result["task_detail_error"] == ""
assert "hy-7770001" in client.goods_calls
assert "hy-ignore-me" not in client.goods_calls
assert result["goods_count"] == len(BUILTIN_SPU_LITERALS) + 1
assert logs == []
def test_refresh_recharge_goods_reports_goods_failure_not_activity_status(
db, monkeypatch
):
client = _StubShopClient(_FakeActTaskDetail(601, "活动已下线"), goods=False)
runner, marks, _logs = _runner(monkeypatch, client)
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
runner._execute_refresh_recharge_goods(
db, None, account, {"uid": 1199665170519, "cookie": account.cookie}, CONFIG
)
status, message, result = marks[-1]
assert status == "failed"
assert message == "开通商品刷新失败: 商品详情接口无响应"
# 失败原因必须来自商品详情,而不是把旧活动接口的「活动已下线」当结论
assert "活动已下线" not in message
assert result["failed_count"] == len(BUILTIN_SPU_LITERALS)
def test_refresh_recharge_goods_drops_stale_rows_of_other_sids(db, monkeypatch):
"""同账号跨 sid 的旧行必须清掉,否则列表会出现同名重复商品。"""
client = _StubShopClient(_FakeActTaskDetail(601, "活动已下线"))
runner, marks, _logs = _runner(monkeypatch, client)
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
# 上次刷新用的是另一个 sid(真实库里就存在 sid=0 的旧行)
db.add(
HuyaRechargeGoodsSnapshot(
account_id=account.id,
sid=0,
spu_id="hy-5879340",
sku_id="old-sku",
name="精英宝典",
)
)
db.commit()
runner._execute_refresh_recharge_goods(
db, None, account, {"uid": 1199665170519, "cookie": account.cookie}, CONFIG
)
assert marks[-1][0] == "success"
rows = (
db.query(HuyaRechargeGoodsSnapshot)
.filter(HuyaRechargeGoodsSnapshot.account_id == account.id)
.all()
)
assert len(rows) == len(BUILTIN_SPU_LITERALS)
assert {row.sid for row in rows} == {2203}
assert len({row.spu_id for row in rows}) == len(rows)
def test_list_recharge_goods_hides_global_seed_rows_and_dedupes(db):
"""列表只返回账号级快照:隐藏全局默认行,同一 spu 只留最新一行。"""
from web.backend.routers.huya import list_recharge_goods
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
db.add(account)
db.commit()
# 历史全局默认行(2026-07-04 种子,含旧版精英宝典):不属于当前在售商品
db.add(
HuyaRechargeGoodsSnapshot(
account_id=None,
sid=0,
spu_id="hy-5879340",
sku_id="seed-sku",
name="精英宝典",
)
)
db.commit()
# 同一 spu 的两次账号刷新结果:只保留最新一行
db.add(
HuyaRechargeGoodsSnapshot(
account_id=account.id,
sid=2203,
spu_id="hy-8328015",
sku_id="stale-sku",
name="精英宝典",
)
)
db.commit()
db.add(
HuyaRechargeGoodsSnapshot(
account_id=account.id,
sid=2203,
spu_id="hy-8328015",
sku_id="fresh-sku",
name="精英宝典",
)
)
db.commit()
rows = list_recharge_goods(db=db, current=None)
assert [row.spu_id for row in rows] == ["hy-8328015"]
assert rows[0].sku_id == "fresh-sku"
+62 -1
View File
@@ -1,7 +1,29 @@
"""虎牙精英宝典传输选择的联调前置检查。"""
"""虎牙传输选择:网页设备态齐全走 WSS,缺设备态回退 HTTP cdnws。
背景(2026-10-15 实测,外部 CK 导入后):只带登录态、缺 sdid/udb_deviceid/
udb_guiddata/udb_anobiztoken 的 Cookie 在 WSS 上会被服务端静默丢弃业务请求
(wsLaunch / 业务 RPC 无响应),同一条 Cookie 走 HTTP cdnws 通道可正常查询。
"""
from core.huya.http_client import HuyaHttpClient
from web.backend.services.huya_runner_core import HuyaBatchRunnerCore
LOGIN_ONLY_COOKIE = (
"udb_cred=cred; udb_biztoken=biz; udb_uid=1199659425268; yyuid=1199659425268"
)
COMPLETE_COOKIE = (
"udb_cred=cred; udb_biztoken=biz; udb_uid=1199659425268; yyuid=1199659425268; "
"sdid=sdid; udb_deviceid=w_1234567890123456789; udb_guiddata=guiddata; "
"udb_anobiztoken=anobiz"
)
def _runner() -> HuyaBatchRunnerCore:
# 这两个方法只用 db 无关的状态,直接构造即可
return HuyaBatchRunnerCore(
db=None, batch_id="test-batch", task_type="query_game_name"
)
def test_minimal_app_cookie_reports_only_missing_web_guid():
cookie = (
@@ -40,3 +62,42 @@ def test_script_only_fields_do_not_block_wss():
assert HuyaBatchRunnerCore._web_wss_cookie_missing(cookie) == ()
assert HuyaBatchRunnerCore._has_web_wss_cookie(cookie)
def test_login_only_cookie_falls_back_to_http_channel():
"""缺网页设备态不再抛 COOKIE_INCOMPLETE,改用 HTTP cdnws 客户端。"""
runner = _runner()
activity = runner._activity_client(1199659425268, LOGIN_ONLY_COOKIE)
shop = runner._shop_client(1199659425268, LOGIN_ONLY_COOKIE)
assert isinstance(activity, HuyaHttpClient)
assert isinstance(shop, HuyaHttpClient)
# HTTP 客户端具备任务侧需要的同名方法(含新增的积分中心 RPC)
for method in (
"check_user_bind_game_account",
"get_act_task_detail",
"query_user_score",
"get_goods_info",
"get_supplier_info",
"accept_hy_protocol",
"calc_order_promotion",
"create_order",
"pay_order_submit",
):
assert callable(getattr(activity, method)), method
def test_complete_cookie_keeps_using_wss(monkeypatch):
opened: list[str] = []
def fake_open(self, uid: int, cookie: str, kind: str):
opened.append(kind)
return f"wss-{kind}"
monkeypatch.setattr(HuyaBatchRunnerCore, "_open_wss_session", fake_open)
runner = _runner()
assert runner._activity_client(1199659425268, COMPLETE_COOKIE) == "wss-activity"
assert runner._shop_client(1199659425268, COMPLETE_COOKIE) == "wss-shop"
assert opened == ["activity", "shop"]
+310
View File
@@ -0,0 +1,310 @@
"""限购商品的旧订单复用:已有未支付订单时不该「已超过该商品的购买上限」直接失败。
生产反馈(2026-10-15):账号上挂着上一张没付掉的宝典订单时,先是**购买权限校验**
`checkUserBuyAuth` 返回 703
已超过该商品的购买上限,下单失败~(如有未支付订单,请及时完成支付)
(后端日志 18:34 / 18:48 / 19:00 三批都停在 checkUserBuyAuth,createOrderV5 根本没发),
下单接口 `createOrderV5` 也可能返回同一句。限购 1 件的商品,旧单没付掉就再也下不了
新单 —— 所以这两种失败都要复用那张旧单去发起支付(官方页面同样是复用旧单继续付)。
"""
from types import SimpleNamespace
from web.backend.services.huya_shop_flow import find_reusable_order, run_open_flow
BUY_LIMIT_MESSAGE = (
"已超过该商品的购买上限,下单失败~(如有未支付订单,请及时完成支付)"
)
SPU_ID = "hy-8328015"
UNPAID_ELITE_ORDER = {
"order_id": "11346649",
"item_name": "精英宝典",
"order_status": 10,
"pay_time": 0,
"goods_detail": {"spu_id": SPU_ID, "sku_id": 7756811},
}
PAID_ELITE_ORDER = {
"order_id": "11346648",
"item_name": "精英宝典",
"order_status": 60,
"pay_time": 1791895396000,
"goods_detail": {"spu_id": SPU_ID, "sku_id": 7756811},
}
OTHER_GOODS_ORDER = {
"order_id": "11346647",
"item_name": "精英币",
"order_status": 10,
"pay_time": 0,
"goods_detail": {"spu_id": "hy-8327356", "sku_id": 7759407},
}
#: 真机 2026-10-15:账号 66 的旧单被用户取消 → order_status=90、pay_time=0
CANCELLED_ELITE_ORDER = {
"order_id": "11357769",
"item_name": "精英宝典",
"order_status": 90,
"pay_time": 0,
"goods_detail": {"spu_id": SPU_ID, "sku_id": 7756811},
}
class _Order(SimpleNamespace):
def to_dict(self) -> dict:
return dict(self.__dict__)
class _OrderList(SimpleNamespace):
pass
class _Client:
"""商城链路假客户端:只造流程需要的那几个返回。"""
def __init__(
self,
*,
create_code: int,
create_message: str = "",
orders=None,
auth_code: int = 200,
auth_message: str = "",
):
self.create_code = create_code
self.create_message = create_message
self.orders = orders or []
self.auth_code = auth_code
self.auth_message = auth_message
self.pay_order_ids: list[int] = []
self.order_list_calls = 0
self.create_calls = 0
def get_goods_info(self, **kwargs):
return SimpleNamespace(
code=200,
message="",
to_dict=lambda: {
"sku_id": 7756811,
"name": "精英宝典",
"price": 3000,
},
)
def get_supplier_info(self, **kwargs):
resp = SimpleNamespace(code=200, message="", payload={})
resp.value = lambda *path: "和平精英官方小店"
return resp
def list_pay_channels(self, **kwargs):
return SimpleNamespace(code=200, message="", channels=["Zfb"])
def check_hy_protocol(self, **kwargs):
return SimpleNamespace(code=200, message="")
def play_mall_get_my_promotion(self, **kwargs):
return SimpleNamespace(code=200, message="", to_dict=lambda: {"code": 200})
def calc_order_promotion(self, **kwargs):
return SimpleNamespace(code=200, message="", to_dict=lambda: {"code": 200})
def accept_hy_protocol(self, **kwargs):
return SimpleNamespace(code=200, message="")
def check_user_buy_auth(self, **kwargs):
return SimpleNamespace(code=self.auth_code, message=self.auth_message)
def create_order(self, **kwargs):
self.create_calls += 1
if self.create_code == 200:
return SimpleNamespace(
code=200,
message="",
orderId=11346649,
to_dict=lambda: {"order_id": 11346649, "code": 200},
)
return SimpleNamespace(
code=self.create_code,
message=self.create_message,
orderId=0,
to_dict=lambda: {"code": self.create_code, "message": self.create_message},
)
def query_user_order_list(self, **kwargs):
self.order_list_calls += 1
return _OrderList(
totalCount=len(self.orders),
orders=[_Order(**item) for item in self.orders],
)
def pay_order_submit(self, **kwargs):
self.pay_order_ids.append(int(kwargs.get("order_id") or 0))
return SimpleNamespace(
code=200,
message="",
payUrl="https://openapi.alipay.com/gateway.do?probe=1",
appOrderId="app-1",
payOrderId="pay-1",
amount=3000,
to_dict=lambda: {
"code": 200,
"pay_url": "https://openapi.alipay.com/gateway.do?probe=1",
},
)
def _run(client: _Client):
return run_open_flow(
client,
uid=1199665170519,
cookie="yyuid=1199665170519",
pid=1199650619883,
spu_id=SPU_ID,
sku_id=7756811,
count=1,
pay_channel="Zfb",
)
def test_reuse_unpaid_order_when_create_hits_buy_limit():
client = _Client(
create_code=703, create_message=BUY_LIMIT_MESSAGE, orders=[UNPAID_ELITE_ORDER]
)
outcome = _run(client)
assert outcome.ok is True
assert outcome.order_id == 11346649 # 复用旧单
assert outcome.message == "已复用未支付订单 #11346649"
assert outcome.pay_url.startswith("https://openapi.alipay.com/gateway.do")
assert client.pay_order_ids == [11346649] # 支付发给的是旧单
assert client.create_calls == 1 # 先试过下单,失败后才复用
assert outcome.reused_order["order_id"] == "11346649"
def test_auth_buy_limit_reuses_unpaid_order_without_creating():
"""真机 2026-10-15:限购校验先报 703,这时复用旧单且不该再发下单请求。"""
client = _Client(
create_code=200,
orders=[UNPAID_ELITE_ORDER],
auth_code=703,
auth_message=BUY_LIMIT_MESSAGE,
)
outcome = _run(client)
assert outcome.ok is True
assert outcome.order_id == 11346649
assert outcome.message == "已复用未支付订单 #11346649"
assert client.pay_order_ids == [11346649]
assert client.create_calls == 0
assert outcome.reused_order["order_status"] == 10
def test_auth_buy_limit_without_unpaid_order_keeps_original_error():
"""没有可复用的旧单时保持原样:报限购错误、不下单、不起支付。"""
client = _Client(
create_code=200,
orders=[],
auth_code=703,
auth_message=BUY_LIMIT_MESSAGE,
)
outcome = _run(client)
assert outcome.ok is False
assert outcome.message == BUY_LIMIT_MESSAGE
assert client.pay_order_ids == []
assert client.create_calls == 0
def test_auth_buy_limit_ignores_paid_and_cancelled_orders():
client = _Client(
create_code=200,
orders=[CANCELLED_ELITE_ORDER, PAID_ELITE_ORDER],
auth_code=703,
auth_message=BUY_LIMIT_MESSAGE,
)
outcome = _run(client)
assert outcome.ok is False
assert outcome.message == BUY_LIMIT_MESSAGE
assert client.pay_order_ids == []
def test_auth_no_response_fails_without_touching_orders():
client = _Client(create_code=200, orders=[UNPAID_ELITE_ORDER], auth_code=200)
client.check_user_buy_auth = lambda **kwargs: None
outcome = _run(client)
assert outcome.ok is False
assert outcome.message == "购买权限校验接口无响应"
assert client.create_calls == 0
assert client.order_list_calls == 0
def test_paid_order_is_not_reused():
client = _Client(
create_code=703, create_message=BUY_LIMIT_MESSAGE, orders=[PAID_ELITE_ORDER]
)
outcome = _run(client)
assert outcome.ok is False
assert outcome.message == BUY_LIMIT_MESSAGE
assert client.pay_order_ids == []
def test_cancelled_order_is_not_reused():
"""已取消(90)的旧单不能复用(真机:用户取消后状态变 90)。"""
client = _Client(
create_code=703,
create_message=BUY_LIMIT_MESSAGE,
orders=[CANCELLED_ELITE_ORDER],
)
outcome = _run(client)
assert outcome.ok is False
assert client.pay_order_ids == []
def test_other_goods_order_is_not_reused():
client = _Client(
create_code=703, create_message=BUY_LIMIT_MESSAGE, orders=[OTHER_GOODS_ORDER]
)
outcome = _run(client)
assert outcome.ok is False
assert client.pay_order_ids == []
def test_create_success_does_not_look_up_old_orders():
client = _Client(create_code=200)
outcome = _run(client)
assert outcome.ok is True
assert outcome.message == "已生成支付二维码"
assert outcome.reused_order == {}
# 下单成功就不该多打一次订单列表
assert client.order_list_calls == 0
def test_find_reusable_order_skips_to_next_page():
class _PagedClient(_Client):
def query_user_order_list(self, **kwargs):
self.order_list_calls += 1
offset = int(kwargs.get("offset") or 0)
page = [OTHER_GOODS_ORDER] * 20 if offset == 0 else [UNPAID_ELITE_ORDER]
return _OrderList(totalCount=21, orders=[_Order(**item) for item in page])
client = _PagedClient(create_code=200)
reused = find_reusable_order(client, uid=1, cookie="c", spu_id=SPU_ID)
assert reused["order_id"] == "11346649"
assert client.order_list_calls == 2
@@ -0,0 +1,64 @@
"""TAF 结构体解析韧性:尾部未建模字段(服务端新增/ZERO)与通用响应回落。
回归来源(2026-10-15 真机):`checkUserBindGameAccount` 响应结构尾部多了 tag6
(ZERO 类型),旧解析直接抛 "期望 STRUCT_END, 实际 0x0c",导致整个 RPC 返回 None、
工作台「查询角色」永远失败。修法:按 TAF 语义跳过未建模的尾部字段。
"""
from core.huya.activity_structs import CheckUserBindGameAccountResp
from core.huya.shop_structs import ShopRawRsp
from core.huya.taf_protocol import TafInputStream, TafOutputStream, TafType
# 真机响应(checkUserBindGameAccount,UID 1199665170519,bActId 9271)
BIND_RESP_HEX = (
"0a0100c816002a0001100120013a060016002602717136004612e6b3aae6958fe6849fe"
"79a84e59b9ee5bf86560066000b4a06001612e6b3aae99ba8e585a8e698afe8b08ee8a8"
"802604e6898b51360be88bb9e69e9c28694f53294600560066000b526a2595806c0b36"
"0ce5928ce5b9b3e7b2bee88bb1460050070b"
)
def test_bind_response_with_zero_tail_field_parses():
stream = TafInputStream(bytes.fromhex(BIND_RESP_HEX))
tag, dtype = stream.read_head()
assert (tag, dtype) == (0, TafType.STRUCT_BEGIN)
resp = CheckUserBindGameAccountResp()
resp.read_from(stream)
assert resp.status == 200
assert resp.gameName == "和平精英"
assert resp.accountData.isBindAcount == 1
assert resp.accountData.isBindRole == 1
assert resp.accountData.gameAccount.nick == "泪敏感的回忆"
assert resp.accountData.gameRole.roleName == "泪雨全是谎言"
assert resp.accountData.gameRole.areaName == "手Q"
assert resp.accountData.gameRole.platName == "苹果(iOS)"
# 外层结构正常收尾(内层 tag6=ZERO 已由 read_struct 跳过)
_end_tag, end_type = stream.read_head()
assert end_type == TafType.STRUCT_END
def test_skip_to_struct_end_skips_zero_field():
output = TafOutputStream()
output.write_struct_begin(0)
output.write_int32(0, 1)
output.write_int32(6, 0) # ZERO 类型(0x6c)
output.write_struct_end()
stream = TafInputStream(output.get_bytes())
stream.read_head() # STRUCT_BEGIN
assert stream.read_int32(0) == 1
assert stream.skip_to_struct_end() == 1
_tag, dtype = stream.read_head()
assert dtype == TafType.STRUCT_END
def test_shop_raw_rsp_from_payload_flat_and_nested():
flat = ShopRawRsp.from_payload({"tag0": 200, "tag1": "success"})
assert (flat.code, flat.message) == (200, "success")
nested = ShopRawRsp.from_payload({"tag0": {"tag0": 200, "tag1": "成功"}})
assert (nested.code, nested.message) == (200, "成功")
assert ShopRawRsp.from_payload(None).code == 0
+81
View File
@@ -0,0 +1,81 @@
"""工作台「导入外部 CK」:入库 + 自动加入工作台 + 归属导入者。"""
from tests.support.db import get_test_engine, make_test_session
from web.backend.models import HuyaAccount, HuyaWorkbench, HuyaWorkbenchAccount, User
from web.backend.routers.huya import import_workbench_cookies
from web.backend.schemas import HuyaWorkbenchCookieImport
COOKIE_1 = (
"yyuid=1001; udb_uid=1001; udb_passport=hy_test_1; "
"udb_cred=cred1; udb_biztoken=biz1"
)
COOKIE_2 = (
"yyuid=1002; udb_uid=1002; udb_passport=hy_test_2; "
"udb_cred=cred2; udb_biztoken=biz2"
)
class TestImportExternalCkToWorkbench:
def setup_method(self):
self.engine = get_test_engine()
self.session = make_test_session(self.engine)
self.user = User(username="operator", password_hash="hash", role="super_admin")
self.session.add(self.user)
self.session.commit()
def teardown_method(self):
self.session.close()
def test_import_creates_accounts_and_joins_workbench(self):
result = import_workbench_cookies(
HuyaWorkbenchCookieImport(
text=f"小号A----{COOKIE_1}\n这不是一行 CK\n{COOKIE_2}",
tag="外部CK",
handbook_scope="elite",
),
db=self.session,
current=self.user,
)
assert result["success"] is True
assert result["count"] == 2
assert result["skipped"] == 1
assert len(result["account_ids"]) == 2
accounts = {
account.yyuid: account for account in self.session.query(HuyaAccount).all()
}
assert set(accounts) == {"1001", "1002"}
# 无归属的新账号自动归属导入者,否则客服在工作台看不到自己导入的账号
assert all(account.assigned_to == self.user.id for account in accounts.values())
assert accounts["1001"].tag == "外部CK"
joined = {
row.account_id
for row in self.session.query(HuyaWorkbenchAccount)
.filter(HuyaWorkbenchAccount.user_id == self.user.id)
.all()
}
assert joined == set(result["account_ids"])
assert self.session.query(HuyaWorkbench).count() == 1
def test_reimport_is_idempotent(self):
payload = HuyaWorkbenchCookieImport(text=COOKIE_1, handbook_scope="elite")
first = import_workbench_cookies(payload, db=self.session, current=self.user)
second = import_workbench_cookies(payload, db=self.session, current=self.user)
assert first["account_ids"] == second["account_ids"]
assert len(first["account_ids"]) == 1
assert self.session.query(HuyaAccount).count() == 1
assert self.session.query(HuyaWorkbenchAccount).count() == 1
def test_all_invalid_lines_reports_zero(self):
result = import_workbench_cookies(
HuyaWorkbenchCookieImport(text="垃圾行\n更多垃圾", handbook_scope="elite"),
db=self.session,
current=self.user,
)
assert result["count"] == 0
assert result["skipped"] == 2
assert result["account_ids"] == []
assert self.session.query(HuyaAccount).count() == 0
assert self.session.query(HuyaWorkbench).count() == 0
+1 -1
View File
@@ -26,7 +26,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261008_0052"
HEAD_REVISION = "20261015_0053"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -0,0 +1,79 @@
"""虎牙精英宝典开通状态:`huya_accounts` 新增 elite_opened / elite_open_time / elite_expire_time
工作台列表要能直接看到「这个号开没开宝典、什么时候开的、有效期到什么时候」,
但现在只有一个 `points` 列:开通后把积分花完和从没开通,在界面上长得一模一样。
真机(2026-10-15 两份抓包 + 真机对照网页)核对的来源:
* 开通状态 —— 积分中心 ``shopMiddleUI.getRedeemNeedGoods`` 的 ``tag5``:
``1`` = 已开通(网页显示「已开通精英宝典」),``0`` = 未开通(网页显示
「获取积分需先开通精英宝典」,``tag7`` 还会列出开通套餐)。
* 开通时间 —— ``revenueWebUI.queryUserOrderList`` 里已支付的宝典订单,取最近一次。
* 有效期 —— ``PlayMallUI.queryAllocation`` 响应里的赛季节点(``tag10``/``tag11``
是本赛季起止毫秒时间戳):2026-10-15 抓包为「精英宝典福利季丨Q4」,
即 2026-10-09 ~ 2026-12-31 23:59:59;认不出赛季结构时留空。
两列时间都存 **Unix 秒**(Integer 放不下毫秒时间戳,且与斗鱼 `elite_expire_time`
同一约定)。
历史值不回填:以前没查过宝典状态的账号是 NULL(界面显示「未查询」),
下次「一键查询」会补上 —— 不回填才不会把「没查过」伪装成「未开通」。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261015_0053"
down_revision: str | None = "20261008_0052"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "huya_accounts"
COLUMNS = (
(
"elite_opened",
sa.Boolean(),
"精英宝典是否已开通(积分中心 getRedeemNeedGoods 的 tag5;NULL=未查询)",
),
(
"elite_open_time",
sa.Integer(),
"最近一次宝典订单的支付时间(Unix 秒)",
),
(
"elite_expire_time",
sa.Integer(),
"宝典有效期(Unix 秒):积分中心本赛季结束时间;认不出赛季时留空",
),
)
def _column_exists(name: str) -> bool:
"""可安全重跑(应用启动时会自动跑迁移)。"""
conn = op.get_bind()
count = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() "
"AND table_name = :table AND column_name = :name"
),
{"table": TABLE, "name": name},
).scalar()
return bool(count)
def upgrade() -> None:
for name, column_type, comment in COLUMNS:
if not _column_exists(name):
op.add_column(
TABLE,
sa.Column(name, column_type, nullable=True, comment=comment),
)
def downgrade() -> None:
for name, _column_type, _comment in COLUMNS:
if _column_exists(name):
op.drop_column(TABLE, name)
+7
View File
@@ -539,6 +539,13 @@ class HuyaAccount(Base):
game_name: Mapped[str] = mapped_column(String(128), default="")
game_channel: Mapped[str] = mapped_column(String(64), default="")
game_phone: Mapped[str] = mapped_column(String(64), default="")
# 精英宝典开通状态(积分中心 getRedeemNeedGoods 的 tag5;NULL = 还没查过)。
# 光看积分区分不了「开通后花完」和「从没开通」,必须单独落库。
elite_opened: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
# 最近一次宝典订单的支付时间(Unix 秒;与斗鱼 elite_expire_time 同一约定)。
elite_open_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 宝典有效期(Unix 秒):取积分中心页面配置里本赛季的结束时间(福利季 Q4 → 12-31)。
elite_expire_time: Mapped[int | None] = mapped_column(Integer, nullable=True)
sms_url: Mapped[str] = mapped_column(Text, default="")
assigned_to: Mapped[int | None] = mapped_column(
ForeignKey("users.id"), nullable=True, index=True
+6
View File
@@ -39,6 +39,7 @@ from .workbench import (
create_task_batch,
get_config,
get_task,
import_workbench_cookies,
list_goods,
list_huya_workbench_accounts,
list_recharge_goods,
@@ -50,6 +51,8 @@ from .workbench import (
update_huya_workbench_accounts,
ws_huya_logs,
)
from .pay import redirect_huya_pay
from .pay import router as pay_router
from .workbench import router as workbench_router
router = APIRouter(prefix="/api/huya", tags=["虎牙"])
@@ -59,6 +62,7 @@ router.include_router(register_router)
router.include_router(cookies_router)
router.include_router(workbench_router)
router.include_router(devices_router)
router.include_router(pay_router)
__all__ = [
"app_password_login_account",
@@ -79,6 +83,7 @@ __all__ = [
"get_task",
"import_cookies",
"import_password_accounts",
"import_workbench_cookies",
"list_accounts",
"list_goods",
"list_huya_account_ids",
@@ -88,6 +93,7 @@ __all__ = [
"list_tasks",
"password_login_account",
"password_login_selected_accounts",
"redirect_huya_pay",
"router",
"send_sms_code",
"set_account_tag",
+8
View File
@@ -89,6 +89,7 @@ from ...schemas import (
HuyaTaskOut,
HuyaTestSmsUrlRequest,
HuyaWorkbenchAccountsUpdate,
HuyaWorkbenchCookieImport,
)
from ...services.audit_service import record_audit
from ...services.huya_exchange_targets import (
@@ -111,6 +112,7 @@ from ...services.huya_service import (
ensure_huya_config,
huya_config_value,
import_huya_cookies,
import_huya_cookies_detailed,
import_huya_password_accounts,
rebuild_web_cookie_from_raw,
save_huya_login_cookie_to_account,
@@ -349,6 +351,9 @@ def _account_out(account: HuyaAccount, include_cookie: bool = True) -> HuyaAccou
game_name=account.game_name or "",
game_channel=account.game_channel or "",
game_phone=account.game_phone or "",
elite_opened=account.elite_opened,
elite_open_time=account.elite_open_time,
elite_expire_time=account.elite_expire_time,
sms_url=account.sms_url or "",
assigned_to=account.assigned_to,
assigned_username=account.assigned_user.username
@@ -381,6 +386,9 @@ def _account_out_light(
game_name=account.game_name or "",
game_channel=account.game_channel or "",
game_phone=account.game_phone or "",
elite_opened=account.elite_opened,
elite_open_time=account.elite_open_time,
elite_expire_time=account.elite_expire_time,
sms_url=account.sms_url or "",
assigned_to=account.assigned_to,
assigned_username=account.assigned_user.username
+35
View File
@@ -0,0 +1,35 @@
"""虎牙支付短链:把「开通支付码」的二维码内容换成可扫的短链。
手机扫码时没有登录态(不是当前浏览器),所以这条路由**不带鉴权依赖**,
只校验 `huya_pay_link.pay_qr_path` 里那个 HMAC 签名;签名不对或任务里没有
支付地址就 404。除了跳到支付宝/微信的支付地址,这里不返回任何数据。
"""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import RedirectResponse
from sqlalchemy.orm import Session
from ...database import get_db
from ...models import HuyaTask
from ...services.huya_pay_link import verify_pay_token
router = APIRouter(tags=["虎牙"])
@router.get("/pay/{task_id}")
def redirect_huya_pay(task_id: int, k: str = "", db: Session = Depends(get_db)):
"""302 到该任务真实的下单支付地址(供手机扫码后打开)。"""
if not verify_pay_token(task_id, k):
raise HTTPException(status_code=404, detail="支付链接无效")
task = db.query(HuyaTask).filter(HuyaTask.id == int(task_id)).first()
pay_url = str(
((task.result or {}) if task is not None else {}).get("pay_url") or ""
)
if not pay_url.startswith(("http://", "https://")):
raise HTTPException(status_code=404, detail="支付链接不存在")
return RedirectResponse(pay_url, status_code=302)
+77 -3
View File
@@ -132,15 +132,22 @@ def list_recharge_goods(
db: Session = Depends(get_db),
current: User = Depends(require_permission("huya:task")),
):
"""查看已缓存的虎牙充值商品快照。"""
"""查看已缓存的虎牙充值商品快照。
只返回账号级快照(account_id 非空):库里还有一批 2026-07-04 写入的全局默认行
(account_id 为空、sid=0,含旧版精英宝典/精英令/精英徽章),它们已不是当前在售
商品,未刷新过的账号显示空列表、点一次「刷新开通商品」即可。同一 spu_id 只保留
最新一行,避免下拉框出现同名重复项。
"""
rows = (
db.query(HuyaRechargeGoodsSnapshot)
.filter(HuyaRechargeGoodsSnapshot.account_id.is_not(None))
.order_by(HuyaRechargeGoodsSnapshot.id.desc())
.all()
)
latest = {}
latest: dict[str, HuyaRechargeGoodsSnapshot] = {}
for row in rows:
latest.setdefault((row.sid, row.spu_id), row)
latest.setdefault(row.spu_id, row)
return list(latest.values())
@@ -384,3 +391,70 @@ async def ws_huya_logs(websocket: WebSocket, batch_id: str):
latest = huya_batch_registry.get(batch_id)
if latest and latest.get("finished"):
huya_batch_registry.pop(batch_id)
@router.post("/workbench-accounts/import-cookies")
def import_workbench_cookies(
req: HuyaWorkbenchCookieImport,
db: Session = Depends(get_db),
current: User = Depends(require_permission("huya:task")),
):
"""导入外部 CK:入库为虎牙账号并直接加入当前用户的工作台。
导入后的账号会出现在工作台账号列表里,可照常执行「生成开通支付码 / 绑定二维码 /
查询角色 / 刷新积分」等操作。没有归属的新账号自动归属到导入者,否则客服看不到。
"""
_require_huya_perm(current, "huya:import")
accounts, skipped = import_huya_cookies_detailed(
db, req.text, req.tag, assign_to=current.id
)
imported_ids = sorted({account.id for account in accounts})
if imported_ids:
workbench = (
db.query(HuyaWorkbench)
.filter(
HuyaWorkbench.user_id == current.id,
HuyaWorkbench.handbook_scope == req.handbook_scope,
)
.first()
)
if workbench is None:
db.add(HuyaWorkbench(user_id=current.id, handbook_scope=req.handbook_scope))
else:
workbench.updated_at = datetime.now(UTC)
existing_ids = {
account_id
for (account_id,) in db.query(HuyaWorkbenchAccount.account_id)
.filter(
HuyaWorkbenchAccount.user_id == current.id,
HuyaWorkbenchAccount.handbook_scope == req.handbook_scope,
)
.all()
}
db.add_all(
[
HuyaWorkbenchAccount(
user_id=current.id,
handbook_scope=req.handbook_scope,
account_id=account_id,
)
for account_id in imported_ids
if account_id not in existing_ids
]
)
record_audit(
db,
current,
action="huya:workbench:import_ck",
target=f"huya_workbench:{req.handbook_scope}",
detail={"count": len(imported_ids), "skipped": skipped, "tag": req.tag},
)
db.commit()
return {
"message": f"导入 {len(imported_ids)} 条,跳过 {skipped} 条",
"success": True,
"count": len(imported_ids),
"skipped": skipped,
"account_ids": _workbench_account_ids(db, current, req.handbook_scope),
}
+15
View File
@@ -580,6 +580,10 @@ class HuyaAccountOut(BaseModel):
game_name: str = ""
game_channel: str = ""
game_phone: str = ""
# 精英宝典开通状态(NULL = 未查询);有效期接口没给时为空
elite_opened: bool | None = None
elite_open_time: int | None = None
elite_expire_time: int | None = None
sms_url: str = ""
assigned_to: int | None = None
assigned_username: str | None = None
@@ -608,6 +612,9 @@ class HuyaAccountOut(BaseModel):
"game_name": self.game_name,
"game_channel": self.game_channel,
"game_phone": self.game_phone,
"elite_opened": self.elite_opened,
"elite_open_time": self.elite_open_time,
"elite_expire_time": self.elite_expire_time,
"sms_url": self.sms_url,
"assigned_to": self.assigned_to,
"assigned_username": self.assigned_username,
@@ -657,6 +664,14 @@ class HuyaWorkbenchAccountsUpdate(BaseModel):
account_ids: list[int] = Field(default_factory=list)
class HuyaWorkbenchCookieImport(BaseModel):
"""工作台「导入外部 CK」:把外部 Cookie 入库并直接加入自己的工作台。"""
text: str = Field(..., min_length=1)
tag: str = ""
handbook_scope: str = Field("elite", pattern="^elite$|^browser_exchange$")
class HuyaBrowserExchangeRequest(BaseModel):
"""浏览器兑换的目标页选择(常量见 services/huya_exchange_targets.py)。"""
+96
View File
@@ -0,0 +1,96 @@
"""开通支付码的**二维码内容**:让手机一定扫得动、打得开。
问题(生产实测 2026-10-15):`payOrderSubmitV5` 返回的 `payUrl` 是
`https://openapi.alipay.com/gateway.do?...&sign=...`,长度 **1626** 字符。
直接把它编成二维码是 version 29+(约 140 个模块),在 150px 的画面上每个模块
只有约 1 像素 —— 手机怎么都扫不上。
两条出路,二维码里按顺序取第一个可用的:
1. **支付宝收银台直达地址**(首选):网关地址 302 两次后落到
`https://excashier.alipay.com/standard/auth.htm?payOrderId=...`(约 74 字符),
公网域名、支付宝扫一扫直接识别,后端跑在 localhost 时也能发给客户扫。
见 `resolve_pay_entry_url`。
2. **本站短链** `/api/huya/pay/<task_id>?k=<hmac>`(约 38 字符):手机打开后由
后端 302 跳到上面的网关地址。要求「本页域名」手机能访问到(localhost 不行)。
扫码的是没登录的手机,所以路由只校验 HMAC 签名(用 JWT 密钥派生,不额外存库)。
"""
from __future__ import annotations
import hashlib
import hmac
from urllib.parse import urlsplit
import requests
from ..security import SECRET_KEY_TYPED
TOKEN_LENGTH = 16
PAY_PATH_PREFIX = "/api/huya/pay"
#: 解析收银台直达地址时冒充浏览器(支付宝对无 UA 的请求会走风控页)。
BROWSER_UA = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36"
)
def pay_token(task_id: int) -> str:
"""按任务号派生短链签名(16 位十六进制,48 bit 抗枚举)。"""
return hmac.new(
SECRET_KEY_TYPED.encode("utf-8"),
f"huya-pay:{int(task_id)}".encode(),
hashlib.sha256,
).hexdigest()[:TOKEN_LENGTH]
def verify_pay_token(task_id: int, token: str) -> bool:
"""校验短链签名(常数时间比较)。"""
text = str(token or "").strip()
if not text:
return False
return hmac.compare_digest(pay_token(task_id), text)
def pay_qr_path(task_id: int) -> str:
"""短链路径;前端拼上 ``window.location.origin`` 就是手机能打开的地址。"""
return f"{PAY_PATH_PREFIX}/{int(task_id)}?k={pay_token(task_id)}"
def is_alipay_url(url: str) -> bool:
"""是否支付宝域名(网关/收银台)。"""
host = (urlsplit(str(url or "")).hostname or "").lower()
return bool(host) and (host == "alipay.com" or host.endswith(".alipay.com"))
def resolve_pay_entry_url(pay_url: str, *, timeout: float = 6.0) -> str:
"""跟随支付宝网关的 302,取**收银台直达地址**(约 74 字符,公网可达)。
真机实测(2026-10-15):`openapi.alipay.com/gateway.do?...` 会 302 到
`unitradeprod.alipay.com/appAssign.htm?...` 再 302 到
`https://excashier.alipay.com/standard/auth.htm?payOrderId=<id>`。
这个地址编二维码又小又好扫,且不依赖本服务的域名能不能被手机访问。
解析失败、超时、或最终落到非支付宝域名都返回空串 —— 调用方回落到本站短链,
绝不能让解析失败影响支付码本身。
"""
url = str(pay_url or "").strip()
if not url.startswith(("http://", "https://")):
return ""
try:
response = requests.get(
url,
headers={"User-Agent": BROWSER_UA, "Accept": "text/html,*/*"},
timeout=timeout,
allow_redirects=True,
)
try:
final_url = str(getattr(response, "url", "") or "").strip()
finally:
close = getattr(response, "close", None)
if callable(close):
close()
except Exception: # noqa: BLE001 - 解析失败不能打断支付码生成
return ""
return final_url if is_alipay_url(final_url) else ""
+7
View File
@@ -16,6 +16,7 @@ from .huya_runner_core import ( # noqa: F401 (huya_batch_registry 供 routers
HuyaBatchRunnerCore,
huya_batch_registry,
)
from .huya_runner_elite import EliteMixin
from .huya_runner_goods import GoodsMixin
from .huya_runner_recharge import RechargeMixin
from .huya_service import HUYA_CONFIG_FIELDS, ensure_huya_config, huya_config_value
@@ -26,6 +27,7 @@ class HuyaBatchRunner(
BindMixin,
GoodsMixin,
RechargeMixin,
EliteMixin,
):
"""批量执行虎牙任务(功能域 Mixin 聚合 + 批次调度)。"""
@@ -64,6 +66,7 @@ class HuyaBatchRunner(
if self.task_type not in {
"query_act_tasks",
"query_points",
"query_all",
"get_bind_qr",
"confirm_bind",
"query_game_name",
@@ -88,6 +91,10 @@ class HuyaBatchRunner(
self._execute_query_points(
worker_db, task, account, account_info, config_info
)
elif self.task_type == "query_all":
self._execute_query_all(
worker_db, task, account, account_info, config_info
)
elif self.task_type == "refresh_goods":
self._execute_refresh_goods(
worker_db, task, account, account_info, config_info
+42 -12
View File
@@ -94,19 +94,48 @@ class HuyaBatchRunnerCore:
return bucket
def _activity_client(self, uid: int, cookie: str):
"""创建活动 WSS 会话;网页 Cookie 不完整时直接阻断任务。"""
"""活动通道客户端:网页设备态齐全走 WSS,否则回退 HTTP cdnws。
2026-10-15 实测(外部 CK 导入后):只带登录态、缺 sdid/udb_deviceid/
udb_guiddata/udb_anobiztoken 的 Cookie 在 WSS 上会被服务端静默丢弃业务请求
(wsLaunch 或业务 RPC 无响应);同一条 Cookie 走 HTTP cdnws 通道可以正常
查询角色与商品。因此这里不再直接失败,而是按能力选通道。
"""
missing = self._web_wss_cookie_missing(cookie)
if missing:
detail = ", ".join(missing)
self._push_log(
"error",
f"[{uid}] Cookie 缺少网页设备态({detail}),已停止活动 HTTP 回退",
"info",
f"[{uid}] Cookie 缺少网页设备态({', '.join(missing)}),改用 HTTP cdnws 通道",
)
raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})")
session = self._open_wss_session(uid, cookie, "activity")
return self._http_client()
session = self._open_wss_or_http(uid, cookie, "activity")
if session is None:
return self._http_client()
self._push_log("info", f"[{uid}] 活动链路使用 WSS 会话")
return session
def _open_wss_or_http(self, uid: int, cookie: str, kind: str):
"""建 WSS 会话;服务端不理会握手(wsLaunch 超时)时返回 None 让调用方回退 HTTP。
2026-10-15 实测:设备态字段齐全的账号也可能被积分中心端点静默丢弃
(wsLaunch 无响应),而同一账号走 HTTP cdnws 一切正常 —— 会话建不起来时
直接回退,而不是把整批任务判失败。
"""
try:
return self._open_wss_session(uid, cookie, kind)
except Exception as exc: # noqa: BLE001 - 任何建连/初始化异常都回退 HTTP
self._push_log(
"warning",
f"[{uid}] {kind} WSS 会话不可用({type(exc).__name__}: {exc}),改用 HTTP cdnws 通道",
)
return None
def _http_client(self):
"""HTTP cdnws 通道客户端(无需网页设备态,方法签名与 WSS 会话保持一致)。"""
from core.huya.http_client import HuyaHttpClient
return HuyaHttpClient(logger=lambda message: self._push_log("info", message))
@staticmethod
def _web_wss_cookie_missing(cookie: str) -> tuple[str, ...]:
"""返回 WSS 前置字段中缺失的名称,不输出任何 Cookie 值。
@@ -134,16 +163,17 @@ class HuyaBatchRunnerCore:
return not cls._web_wss_cookie_missing(cookie)
def _shop_client(self, uid: int, cookie: str):
"""创建商城 WSS 会话;网页 Cookie 不完整时直接阻断任务。"""
"""商城通道客户端:网页设备态齐全走 WSS,否则回退 HTTP cdnws(原因同活动通道)。"""
missing = self._web_wss_cookie_missing(cookie)
if missing:
detail = ", ".join(missing)
self._push_log(
"error",
f"[{uid}] Cookie 缺少网页设备态({detail}),已停止商城 HTTP 回退",
"info",
f"[{uid}] Cookie 缺少网页设备态({', '.join(missing)}),改用 HTTP cdnws 通道",
)
raise RuntimeError(f"COOKIE_INCOMPLETE: 缺少网页设备态({detail})")
session = self._open_wss_session(uid, cookie, "shop")
return self._http_client()
session = self._open_wss_or_http(uid, cookie, "shop")
if session is None:
return self._http_client()
self._push_log("info", f"[{uid}] 商城链路使用 WSS 会话")
return session
+393
View File
@@ -0,0 +1,393 @@
"""虎牙任务执行器:精英宝典开通状态与「一键查询」(由 huya_runner.py 按功能域拆分)。
真机(2026-10-15)核对过的判定来源:
* 宝典开通状态 —— 积分中心 ``shopMiddleUI.getRedeemNeedGoods`` 的 ``tag5``:
``1`` = 已开通(网页显示「已开通精英宝典」),``0`` = 未开通(网页显示
「获取积分需先开通精英宝典」,``tag7`` 还会列出开通套餐)。
两个已开通账号(hy_297832664 / hy_302016799)与两个未开通账号
(hy_260034554 / hy_274193170)实测与网页一致。
* 开通时间 —— ``revenueWebUI.queryUserOrderList`` 里已支付的宝典订单,取最近一次支付时间。
* 有效期 —— 商城订单(orderDetailV5)与积分中心都**不返回**到期时间,所以留空,
界面上「有就显示」。
"""
from __future__ import annotations
import time
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any
from sqlalchemy.orm import Session
from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM
from ..models import HuyaAccount, HuyaTask
# 宝典订单识别:spu 白名单 + 订单名兜底(官方换过多次 SKU,历史订单名带赛季,
# 例如「精英宝典⎜得300积分⎜26年Q2」)。
ELITE_HANDBOOK_SPU_IDS = frozenset(
{"hy-8328015", "hy-5879340", "hy-3845257", "hy-2947756"}
)
ELITE_HANDBOOK_NAME_KEYWORD = "精英宝典"
ELITE_ORDER_PAGE_SIZE = 20
ELITE_ORDER_MAX_PAGES = 3
# 赛季(福利季)节点的毫秒时间戳下限:2001-09 之后的值才认
ELITE_SEASON_MS_FLOOR = 1_000_000_000_000
class EliteMixin:
"""精英宝典域:开通状态判定与一键查询。"""
if TYPE_CHECKING:
payload: dict
@staticmethod
def _to_int(value: Any) -> int: ...
@staticmethod
def _format_local_time(timestamp: int) -> str: ...
def _resolve_uid(self, account_info: dict) -> int: ...
def _shop_client(self, uid: int, cookie: str): ...
def _activity_client(self, uid: int, cookie: str): ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
# 来自 BindMixin
@staticmethod
def _bind_role_result(bind_status) -> dict: ...
@staticmethod
def _bind_change_state(bind_status) -> dict: ...
@staticmethod
def _role_channel(bind_status) -> str: ...
def _resolve_bind_status(
self, client: Any, uid: int, cookie: str, b_act_id_int: int
): ...
@staticmethod
def _elite_opened_from_redeem(redeem: Any) -> bool | None:
"""``getRedeemNeedGoods`` 的 tag5 → 开通状态;拿不准时返回 None(不猜)。"""
if redeem is None or getattr(redeem, "code", 0) != 200:
return None
flag = redeem.value("tag5")
if isinstance(flag, bool) or not isinstance(flag, int):
return None
return flag == 1
@staticmethod
def _is_elite_order(item: dict) -> bool:
detail = item.get("goods_detail") or {}
if str(detail.get("spu_id") or "") in ELITE_HANDBOOK_SPU_IDS:
return True
return ELITE_HANDBOOK_NAME_KEYWORD in str(item.get("item_name") or "")
def _resolve_elite_open_time(
self, client: Any, uid: int, cookie: str
) -> int | None:
"""最近一次已支付宝典订单的时间(Unix 毫秒);查不到返回 None。
订单列表按时间倒序分页返回,宝典订单可能落在后面,所以最多翻
``ELITE_ORDER_MAX_PAGES`` 页;中途任何一次失败都按「没查到」处理。
未支付订单(真机:order_status=10)没有 pay_time,自然不参与。
"""
latest = 0
offset = 0
for _page in range(ELITE_ORDER_MAX_PAGES):
resp = client.query_user_order_list(
uid=uid,
guid="",
cookie=cookie,
offset=offset,
page_size=ELITE_ORDER_PAGE_SIZE,
order_type=1,
status=0,
)
if resp is None:
break
orders = list(getattr(resp, "orders", None) or [])
for order in orders:
item = order.to_dict() if hasattr(order, "to_dict") else dict(order)
if not self._is_elite_order(item):
continue
pay_time = int(item.get("pay_time") or 0)
if pay_time > 0:
latest = max(latest, pay_time)
total = self._to_int(getattr(resp, "totalCount", 0))
if len(orders) < ELITE_ORDER_PAGE_SIZE or offset + len(orders) >= total:
break
offset += len(orders)
return latest or None
@classmethod
def _walk_season_nodes(cls, node: Any, found: list[dict]) -> None:
"""递归找「赛季」节点:同时带 tag10/tag11 毫秒起止时间的结构。"""
if isinstance(node, dict):
start = node.get("tag10")
end = node.get("tag11")
if (
isinstance(start, int)
and isinstance(end, int)
and start >= ELITE_SEASON_MS_FLOOR
and end > start
):
found.append(
{
"name": str(node.get("tag2") or node.get("tag1") or ""),
"start_ms": start,
"end_ms": end,
"config_id": node.get("tag0")
if isinstance(node.get("tag0"), int)
else None,
}
)
for value in node.values():
cls._walk_season_nodes(value, found)
elif isinstance(node, list):
for value in node:
cls._walk_season_nodes(value, found)
@classmethod
def _extract_elite_season(cls, payload: Any) -> dict | None:
"""从积分中心页面配置里取宝典赛季(= 有效期)信息。
真机(2026-10-15 抓包)实证:``PlayMallUI.queryAllocation`` 响应里
``tag2[1].tag2_2.tag0`` 是本赛季配置 —— tag1/tag2 = 「精英宝典福利季」/
「精英宝典福利季丨Q4」,tag10/tag11 = 赛季起止毫秒时间戳
(1791475200000 → 2026-10-09 00:00,1798732799000 → 2026-12-31 23:59:59)。
这里不写死索引,按「带 tag10/tag11 的节点」找,取结束时间最晚的那个。
"""
found: list[dict] = []
cls._walk_season_nodes(payload, found)
if not found:
return None
return max(found, key=lambda item: item["end_ms"])
def _resolve_elite_season(self, client: Any, uid: int, cookie: str) -> dict | None:
"""查询积分中心页面配置并解析本赛季信息;查不到返回 None。"""
resp = client.play_mall_query_allocation(uid=uid, guid="", cookie=cookie)
if resp is None or getattr(resp, "code", 0) != 200:
return None
return self._extract_elite_season(getattr(resp, "payload", None))
def _refresh_elite_open_after_payment(
self,
client: Any,
account: HuyaAccount,
uid: int,
cookie: str,
*,
goods_num: int,
pay_time_ms: int | None = None,
attempts: int = 4,
interval: float = 3.0,
) -> dict:
"""支付完成后确认宝典是否已开通,并写回账号。
交付有几秒延迟,所以 ``tag5`` 还没翻成 1 时会重试(默认 4 次 × 3 秒)。
返回可直接并入任务结果的 dict(含 ``redeem_points``,省掉一次重复查询)。
"""
redeem = None
opened: bool | None = None
total = max(1, attempts)
for index in range(total):
redeem = client.get_redeem_need_goods(
uid=uid, guid="", cookie=cookie, goods_num=int(goods_num or 0)
)
opened = self._elite_opened_from_redeem(redeem)
if opened or index == total - 1:
break
time.sleep(interval)
state: dict[str, Any] = {"elite_checked_at": datetime.now(UTC).isoformat()}
if redeem is not None and getattr(redeem, "code", 0) == 200:
state["redeem"] = redeem.to_dict()
state["redeem_points"] = self._to_int(redeem.value("tag2"))
if opened is None:
return state
open_time: int | None = pay_time_ms or None
if opened and not open_time:
open_time = self._resolve_elite_open_time(client, uid, cookie)
season = self._resolve_elite_season(client, uid, cookie) if opened else None
expire_time = self._to_int(season["end_ms"]) if season else None
self._apply_elite_state(account, opened, open_time, expire_time)
state["elite_opened"] = opened
state["elite_open_time"] = (open_time // 1000) if open_time else None
state["elite_open_time_text"] = (
self._format_local_time(open_time // 1000) if open_time else ""
)
if season:
state["elite_season"] = season
state["elite_expire_time"] = expire_time // 1000
state["elite_expire_time_text"] = self._format_local_time(
expire_time // 1000
)
return state
def _apply_elite_state(
self,
account: HuyaAccount,
opened: bool | None,
open_time: int | None,
expire_time: int | None = None,
) -> None:
"""把宝典状态写到账号上;``opened`` 为 None(没查到)时不动旧值。
库里存 **Unix 秒**(Integer 放不下毫秒级时间戳,且与斗鱼一致),
方法内部一路用的是毫秒(协议原值),落库时统一除 1000。
"""
if opened is None:
return
account.elite_opened = opened
account.elite_open_time = (
(int(open_time) // 1000 if open_time else None) if opened else None
)
account.elite_expire_time = (
(int(expire_time) // 1000 if expire_time else None) if opened else None
)
def _execute_query_all(
self,
worker_db: Session,
task: HuyaTask,
account: HuyaAccount,
account_info: dict,
config_info: dict,
):
"""一键查询:角色绑定 + 精英宝典开通 + 积分(勾选账号批量跑)。"""
uid = self._resolve_uid(account_info)
if not uid:
self._mark_task(worker_db, task, "failed", "无法从账号或 Cookie 解析 yyuid")
return
cookie = account_info.get("cookie") or ""
if not cookie:
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
return
result: dict[str, Any] = {"uid": uid}
failures: list[str] = []
message_parts: list[str] = []
# ---- 积分 + 宝典开通(积分中心同一个接口) ----
shop_client: Any = self._shop_client(uid, cookie)
goods_num = (
self._to_int(self.payload.get("goods_num")) or POINTS_REDEEM_GOODS_NUM
)
redeem = shop_client.get_redeem_need_goods(
uid=uid, guid="", cookie=cookie, goods_num=goods_num
)
points: int | None = None
opened: bool | None = None
if redeem is None:
failures.append("积分中心接口无响应")
elif redeem.code != 200:
failures.append(redeem.message or f"积分查询失败: {redeem.code}")
else:
points = self._to_int(redeem.value("tag2"))
opened = self._elite_opened_from_redeem(redeem)
result.update(
{
"points": points,
"redeem_threshold": self._to_int(redeem.value("tag3")),
"goods_num": goods_num,
"redeem": redeem.to_dict(),
}
)
message_parts.append(f"积分 {points}")
open_time: int | None = None
if opened:
# 已开通才去翻订单:既省一次请求,也避免给未开通账号显示旧订单时间
open_time = self._resolve_elite_open_time(shop_client, uid, cookie)
season = (
self._resolve_elite_season(shop_client, uid, cookie) if opened else None
)
expire_time = self._to_int(season["end_ms"]) if season else None
if opened is not None:
self._apply_elite_state(account, opened, open_time, expire_time)
result["elite_opened"] = opened
result["elite_open_time"] = (open_time // 1000) if open_time else None
result["elite_open_time_text"] = (
self._format_local_time(open_time // 1000) if open_time else ""
)
if season:
result["elite_season"] = season
result["elite_expire_time"] = expire_time // 1000
result["elite_expire_time_text"] = self._format_local_time(
expire_time // 1000
)
if opened:
opened_text = "已开通宝典"
if open_time:
opened_text += f"({self._format_local_time(open_time // 1000)})"
if expire_time:
opened_text += (
f",有效期至 {self._format_local_time(expire_time // 1000)}"
)
else:
opened_text = "未开通宝典"
message_parts.append(opened_text)
# ---- 角色绑定(活动通道) ----
b_act_id_int = self._to_int(
self.payload.get("bind_act_id") or config_info.get("bind_act_id")
)
role_name = ""
if not b_act_id_int:
failures.append("未配置绑定 bActId")
else:
bind_client: Any = self._activity_client(uid, cookie)
bind_status, bind_query_result = self._resolve_bind_status(
client=bind_client,
uid=uid,
cookie=cookie,
b_act_id_int=b_act_id_int,
)
if bind_status is None:
failures.append("角色信息接口无响应")
elif bind_status.status != 200:
failures.append(
bind_status.msg or f"角色信息查询失败: {bind_status.status}"
)
else:
role_info = self._bind_role_result(bind_status)
role_name = role_info.get("role_name") or ""
result.update(
{
"bind_act_id": b_act_id_int,
**role_info,
**self._bind_change_state(bind_status),
**bind_query_result,
}
)
if role_name:
account.game_name = role_name
account.game_channel = (
self._role_channel(bind_status) or account.game_channel
)
message_parts.append(f"角色 {role_name}")
else:
message_parts.append("未绑定角色")
account.points = points if points is not None else account.points
account.status = "all_queried"
account.updated_at = datetime.now(UTC)
result["failures"] = failures
fetched_anything = points is not None or role_name or opened is not None
if not fetched_anything:
self._mark_task(
worker_db,
task,
"failed",
";".join(failures) or "一键查询全部失败",
result,
)
return
message = "|".join(message_parts) or "一键查询完成"
if failures:
message += f";部分失败: {';'.join(failures)}"
self._mark_task(worker_db, task, "success", message, result)
+81 -12
View File
@@ -8,6 +8,8 @@ from typing import TYPE_CHECKING, Any
from sqlalchemy.orm import Session
from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM
from ..models import HuyaAccount, HuyaGoodsSnapshot, HuyaTask
@@ -26,6 +28,7 @@ class GoodsMixin:
def _resolve_uid(self, account_info: dict) -> int: ...
def _push_log(self, level: str, message: str) -> None: ...
def _activity_client(self, uid: int, cookie: str): ...
def _shop_client(self, uid: int, cookie: str): ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
def _wait_until(self, when: datetime, uid: int) -> bool: ...
def _parse_scheduled_time(self, value: Any) -> datetime | None: ...
@@ -90,16 +93,13 @@ class GoodsMixin:
account_info: dict,
config_info: dict,
):
sid = str(self.payload.get("sid") or config_info.get("sid") or "").strip()
if not sid:
self._mark_task(worker_db, task, "failed", "请先配置虎牙活动 SID")
return
sid_int = self._to_int(sid)
if not sid_int:
self._mark_task(worker_db, task, "failed", f"虎牙活动 SID 无效: {sid}")
return
"""查询积分:主源是积分中心的 shopMiddleUI.getRedeemNeedGoods。
2026-10-15 真机实测:旧活动接口 webActUI.getUserScore 对任何 sid 都返回
603「活动已结束」(该接口已下线,与配置无关);积分中心接口返回
``tag2``=当前积分、``tag3``=兑换门槛积分,另可顺手取 GameBizUI
的成长值/成长等级。
"""
uid = self._resolve_uid(account_info)
if not uid:
self._mark_task(worker_db, task, "failed", "无法从账号或 Cookie 解析 yyuid")
@@ -110,10 +110,76 @@ class GoodsMixin:
self._mark_task(worker_db, task, "failed", "账号 Cookie 为空")
return
goods_num = (
self._to_int(self.payload.get("goods_num")) or POINTS_REDEEM_GOODS_NUM
)
client: Any = self._shop_client(uid, cookie)
redeem = client.get_redeem_need_goods(
uid=uid, guid="", cookie=cookie, goods_num=goods_num
)
if redeem is None:
self._query_points_legacy(
worker_db, task, account, uid, cookie, config_info
)
return
result = redeem.to_dict()
result["goods_num"] = goods_num
if redeem.code != 200:
self._mark_task(
worker_db,
task,
"failed",
redeem.message or f"虎牙积分查询失败: {redeem.code}",
result,
)
return
points = self._to_int(redeem.value("tag2"))
result["points"] = points
result["redeem_threshold"] = self._to_int(redeem.value("tag3"))
growth = client.get_grow_level_user_info(uid=uid, guid="", cookie=cookie)
if growth is not None and growth.code == 0:
result["grow_value"] = self._to_int(growth.value("tag1", "tag0"))
result["grow_level"] = self._to_int(growth.value("tag1", "tag1"))
result["nickname"] = growth.value("tag2") or ""
account.points = points
account.status = "points_queried"
account.updated_at = datetime.now(UTC)
self._mark_task(worker_db, task, "success", f"积分: {points}", result)
def _query_points_legacy(
self,
worker_db: Session,
task: HuyaTask,
account: HuyaAccount,
uid: int,
cookie: str,
config_info: dict,
):
"""积分中心接口没有响应时回退旧活动接口,并如实报告旧接口的返回。"""
sid = str(self.payload.get("sid") or config_info.get("sid") or "").strip()
if not sid:
self._mark_task(
worker_db, task, "error", "积分中心接口无响应,且未配置可回退的活动 SID"
)
return
sid_int = self._to_int(sid)
if not sid_int:
self._mark_task(worker_db, task, "failed", f"虎牙活动 SID 无效: {sid}")
return
client: Any = self._activity_client(uid, cookie)
response = client.query_user_score(uid=uid, cookie=cookie, sid=sid_int)
if response is None:
self._mark_task(worker_db, task, "error", "虎牙积分接口无响应")
self._mark_task(
worker_db,
task,
"error",
"虎牙积分接口无响应(积分中心与旧活动接口均失败)",
)
return
result = response.to_dict()
@@ -123,7 +189,8 @@ class GoodsMixin:
worker_db,
task,
"failed",
response.msg or f"虎牙积分查询失败: {response.status}",
f"积分中心接口无响应;旧活动接口(sid={sid_int})返回 "
f"{response.status} {response.msg}".strip(),
result,
)
return
@@ -132,7 +199,9 @@ class GoodsMixin:
account.points = points
account.status = "points_queried"
account.updated_at = datetime.now(UTC)
self._mark_task(worker_db, task, "success", f"积分: {points}", result)
self._mark_task(
worker_db, task, "success", f"积分: {points}(旧活动接口)", result
)
def _execute_query_exchange_records(
self,
+189 -181
View File
@@ -8,20 +8,70 @@ from typing import TYPE_CHECKING, Any
from sqlalchemy.orm import Session
from core.huya.wss_client import POINTS_REDEEM_GOODS_NUM, SHOP_APP_SCENE
from ..models import HuyaAccount, HuyaRechargeGoodsSnapshot, HuyaTask
from .huya_pay_link import pay_qr_path, resolve_pay_entry_url
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 = [
# 内置开通商品候选 = 积分中心页面(m-shop.huya.com/points.html)「赠送指定礼物得积分」
# 那一排商品,全部经 shopMiddleUI.getGoodsInfoV5 真机验证 code=200:
# hy-8328015 精英宝典 ¥30(送300积分,2026-10-13 抓包下单商品)
# hy-8327356 精英币 ¥0.1(已开通后首格「自定义数量」,送1积分)
# hy-5872824 精英徽章 ¥1(送10积分)、hy-5879346 精英令 ¥10(送100积分)
# hy-5874269 精英令*10 ¥100(送1000积分)、hy-5874270 精英令*100 ¥1000(送10000积分)
# 旧版精英宝典 hy-5879340 页面上已不再使用,从候选里去掉。
# 旧活动接口 webActUI.getActTaskDetail(act 25135) 已下线(601 活动已下线),
# 商品来源不能再依赖它,只能作为可选补充。
HUYA_RECHARGE_BUILTIN_PRODUCTS = [
{
"spu_id": "hy-5879340",
"spu_id": "hy-8328015",
"name": "精英宝典",
"task_name": "开通精英宝典",
"description": "得300积分丨解锁道具兑换权益",
"sort": 0,
},
{
"spu_id": "hy-8327356",
"name": "精英币",
"task_name": "购买精英币",
"description": "得1积分丨可兑指定返场皮肤道具",
"sort": 1,
},
{
"spu_id": "hy-5872824",
"name": "精英徽章",
"task_name": "购买精英徽章",
"description": "送10积分",
"sort": 2,
},
{
"spu_id": "hy-5879346",
"name": "精英令",
"task_name": "购买精英令",
"description": "送100积分",
"sort": 3,
},
{
"spu_id": "hy-5874269",
"name": "精英令*10",
"task_name": "购买精英令*10",
"description": "送1000积分",
"sort": 4,
},
{
"spu_id": "hy-5874270",
"name": "精英令*100",
"task_name": "购买精英令*100",
"description": "送10000积分",
"sort": 5,
},
]
from .huya_runner_core import HUYA_RECHARGE_SOURCE_ID
@@ -42,6 +92,18 @@ class RechargeMixin:
def _update_task_progress(self, *args: Any, **kwargs: Any) -> None: ...
def _open_wss_session(self, uid: int, cookie: str, kind: str): ...
def _shop_client(self, uid: int, cookie: str): ...
def _refresh_elite_open_after_payment(
self,
client: Any,
account: HuyaAccount,
uid: int,
cookie: str,
*,
goods_num: int,
pay_time_ms: int | None = None,
attempts: int = 4,
interval: float = 3.0,
) -> dict: ...
@staticmethod
def _format_local_time(timestamp: int) -> str: ...
@@ -221,23 +283,6 @@ class RechargeMixin:
return
client: Any = self._shop_client(uid, cookie)
task_resp = client.get_act_task_detail(
uid=uid, cookie=cookie, act_id=HUYA_RECHARGE_ACT_ID
)
if task_resp is None:
self._mark_task(worker_db, task, "error", "虎牙充值任务详情接口无响应")
return
task_result = task_resp.to_dict()
if task_resp.status != 200:
self._mark_task(
worker_db,
task,
"failed",
task_resp.msg or f"虎牙充值任务详情获取失败: {task_resp.status}",
task_result,
)
return
candidates: list[dict] = []
seen: set[str] = set()
@@ -249,29 +294,51 @@ class RechargeMixin:
seen.add(spu_id)
candidates.append(item)
for item in HUYA_RECHARGE_EXTRA_PRODUCTS:
for item in HUYA_RECHARGE_BUILTIN_PRODUCTS:
add_candidate(dict(item))
for index, item in enumerate(task_result.get("tasks", []), start=1):
if int(item.get("task_type") or 0) != 67:
continue
add_candidate(
{
"spu_id": item.get("spu_id") or "",
"name": item.get("name") or "",
"task_id": str(item.get("task_id") or ""),
"task_name": item.get("name") or "",
"description": item.get("description") or "",
"icon": item.get("icon") or "",
"task_url": item.get("task_url") or "",
"prizes": item.get("prizes") or [],
"sort": index,
}
# 旧活动任务接口(webActUI.getActTaskDetail,act 25135)已下线
# (真机 2026-10-15:601 活动已下线),只作为可选补充:
# 能返回就并入活动里的商品,失败不再阻断整次刷新。
task_result: dict | None = None
task_error = ""
task_resp = client.get_act_task_detail(
uid=uid, cookie=cookie, act_id=HUYA_RECHARGE_ACT_ID
)
if task_resp is None:
task_error = "活动任务详情接口无响应"
else:
task_result = task_resp.to_dict()
if task_resp.status == 200:
for index, item in enumerate(task_result.get("tasks", []), start=1):
if int(item.get("task_type") or 0) != 67:
continue
add_candidate(
{
"spu_id": item.get("spu_id") or "",
"name": item.get("name") or "",
"task_id": str(item.get("task_id") or ""),
"task_name": item.get("name") or "",
"description": item.get("description") or "",
"icon": item.get("icon") or "",
"task_url": item.get("task_url") or "",
"prizes": item.get("prizes") or [],
"sort": 1000 + index,
}
)
else:
task_error = (
task_resp.msg or f"活动任务详情获取失败: {task_resp.status}"
)
if task_error:
self._push_log(
"warning",
f"[{uid}] 活动任务接口不可用({task_error}),按内置开通商品刷新",
)
if not candidates:
self._mark_task(
worker_db, task, "failed", "未从活动任务中发现充值商品", task_result
worker_db, task, "failed", "未发现可用的开通商品", task_result or {}
)
return
@@ -290,7 +357,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": "商品详情接口无响应"})
@@ -323,10 +390,10 @@ class RechargeMixin:
}
goods.append(item)
# 清掉该账号的全部旧商品行(不限 sid):否则跨 sid 的旧行会和本次结果
# 在列表接口里叠成同一商品的重复项(如 精英宝典 x2)。
worker_db.query(HuyaRechargeGoodsSnapshot).filter(
HuyaRechargeGoodsSnapshot.account_id == account.id,
HuyaRechargeGoodsSnapshot.sid
== (self._to_int(config_info.get("sid")) or 2203),
).delete(synchronize_session=False)
for item in goods:
worker_db.add(
@@ -350,9 +417,6 @@ class RechargeMixin:
account.status = "recharge_goods_refreshed"
account.updated_at = now
message = f"已刷新充值商品 {len(goods)} 个"
if failed:
message += f",失败 {len(failed)} 个"
result = {
"act_id": HUYA_RECHARGE_ACT_ID,
"goods_count": len(goods),
@@ -360,10 +424,19 @@ class RechargeMixin:
"goods": goods,
"failed": failed,
"task_detail": task_result,
"task_detail_error": task_error,
}
self._mark_task(
worker_db, task, "success" if goods else "failed", message, result
)
if not goods:
reason = failed[0].get("message") if failed else "无候选商品"
self._mark_task(
worker_db, task, "failed", f"开通商品刷新失败: {reason}", result
)
return
message = f"已刷新开通商品 {len(goods)} 个"
if failed:
message += f",失败 {len(failed)} 个"
self._mark_task(worker_db, task, "success", message, result)
def _execute_create_recharge_order(
self,
@@ -419,143 +492,51 @@ 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
# 二维码内容:优先支付宝收银台直达地址(约 74 字符、公网可达,手机一定打得开),
# 解析不到再回落到本站短链(要求本页域名手机能访问)。
pay_cashier_url = resolve_pay_entry_url(outcome.pay_url)
if pay_cashier_url:
self._push_log("info", f"[{uid}] 支付二维码改用支付宝收银台直达地址")
else:
self._push_log(
"warning", f"[{uid}] 未解析到支付宝收银台直达地址,二维码回落到本站短链"
)
result = {
"spu_id": spu_id,
"sku_id": sku_id,
@@ -566,24 +547,38 @@ 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,
# 支付地址 1600+ 字符,直接编成二维码扫不动(真机反馈);给前端两条更短的路径:
# pay_cashier_url = 支付宝收银台直达地址(公网域名,任意手机可打开);
# pay_qr_path = 本站短链 /api/huya/pay/<task_id>?k=...(需本页域名手机可达)。
"pay_cashier_url": pay_cashier_url,
"pay_qr_path": pay_qr_path(task.id) if task is not None else "",
# 复用未支付旧单时为那张单的原始信息(限购商品:旧单没付完就下不了新单)
"reused_unpaid_order": bool(outcome.reused_order),
"reused_order": outcome.reused_order or None,
"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)
message = f"{product_name} x{count} {self._pay_channel_label(pay_channel)} {result['amount_text']}"
if result.get("reused_unpaid_order"):
message += f"(复用未支付订单 #{result['order_id']})"
self._update_task_progress(
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,19 +586,32 @@ 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,
)
account.updated_at = datetime.now(UTC)
if payment_status == "paid":
account.status = "recharge_paid"
post_score = client.query_user_score(
uid=uid, cookie=cookie, sid=self._to_int(config_info.get("sid")) or 2203
# 支付后自动确认宝典开通状态(顺带取最新积分):交付有几秒延迟,
# _refresh_elite_open_after_payment 会重试到 tag5 变成已开通。
elite_state = self._refresh_elite_open_after_payment(
client,
account,
uid,
cookie,
goods_num=self._to_int(self.payload.get("goods_num"))
or POINTS_REDEEM_GOODS_NUM,
pay_time_ms=(
self._to_int(payment_order.get("pay_time"))
if payment_order
else None
),
)
if post_score is not None:
result["post_payment_score"] = post_score.to_dict()
account.points = post_score.available_score
result.update(elite_state)
if "redeem_points" in elite_state:
result["post_payment_points"] = elite_state["redeem_points"]
account.points = elite_state["redeem_points"]
paid_message = f"支付成功: {product_name} x{count} {result['amount_text']}"
if payment_order and payment_order.get("pay_time"):
paid_message += f",支付时间 {self._format_local_time(int(payment_order['pay_time']) // 1000)}"
+26 -7
View File
@@ -18,6 +18,7 @@ SUPPORTED_TASK_TYPES = {
"get_bind_qr": "获取绑定二维码",
"query_points": "一键查询积分",
"query_game_name": "一键查询游戏名",
"query_all": "一键查询(角色+宝典+积分)",
"query_exchange_records": "一键查询兑换记录",
"confirm_bind": "确认绑定",
"refresh_goods": "刷新商品列表",
@@ -32,6 +33,7 @@ HUYA_HANDBOOK_TASK_TYPES = {
"confirm_bind",
"query_points",
"query_game_name",
"query_all",
"refresh_goods",
"exchange_goods",
"query_exchange_records",
@@ -349,9 +351,16 @@ def upsert_huya_cookie(
return account
def import_huya_cookies(db: Session, text: str, tag: str = "") -> tuple[int, int]:
"""导入虎牙 Cookie,返回 (成功数, 跳过数)。"""
created_or_updated = 0
def import_huya_cookies_detailed(
db: Session, text: str, tag: str = "", assign_to: int | None = None
) -> tuple[list[HuyaAccount], int]:
"""导入虎牙 Cookie,返回 (账号列表, 跳过数)。
与 ``import_huya_cookies`` 的差别:把每个账号对象交回调用方 —— 工作台
「导入外部 CK」需要拿到刚导入的账号加入自己的工作台集合;``assign_to``
用于给尚无归属的新账号打上导入者(否则客服看不到自己导入的账号)。
"""
accounts: list[HuyaAccount] = []
skipped = 0
tag = (tag or "").strip()
@@ -361,12 +370,22 @@ def import_huya_cookies(db: Session, text: str, tag: str = "") -> tuple[int, int
skipped += 1
continue
_upsert_huya_account(db, parsed, tag=tag)
created_or_updated += 1
account = _upsert_huya_account(db, parsed, tag=tag)
if assign_to and account.assigned_to is None:
account.assigned_to = assign_to
accounts.append(account)
if created_or_updated:
if accounts:
db.commit()
return created_or_updated, skipped
for account in accounts:
db.refresh(account)
return accounts, skipped
def import_huya_cookies(db: Session, text: str, tag: str = "") -> tuple[int, int]:
"""导入虎牙 Cookie,返回 (成功数, 跳过数)。"""
accounts, skipped = import_huya_cookies_detailed(db, text, tag)
return len(accounts), skipped
def persist_huya_session_cookie(
+335
View File
@@ -0,0 +1,335 @@
"""虎牙积分中心(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
#: 订单列表里「已支付/已交付」的状态值(与任务侧 _is_huya_order_paid 对齐)。
PAID_ORDER_STATUSES = frozenset({50, 55, 60, 70, 80})
#: 只有这两种状态能被继续支付:10=待支付、1000=尾款待支付
#: (core.huya.shop_structs.OrderStatus;90=已取消、60=已关闭都不能复用,
#: 真机 2026-10-15:账号 66 的旧单被用户取消后 order_status 变成 90)
REUSABLE_ORDER_STATUSES = frozenset({10, 1000})
#: 复用旧单时最多翻几页订单。
REUSE_ORDER_PAGE_SIZE = 20
REUSE_ORDER_MAX_PAGES = 3
@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 = ""
#: 复用了未支付的旧订单时为那张单的原始信息(限购商品没付掉就下不了新单)
reused_order: dict = field(default_factory=dict)
def find_reusable_order(
client: Any,
*,
uid: int,
cookie: str,
spu_id: str,
page_size: int = REUSE_ORDER_PAGE_SIZE,
max_pages: int = REUSE_ORDER_MAX_PAGES,
) -> dict:
"""找这个账号**同一商品**的未支付订单(用于复用旧单继续支付)。
真机(2026-10-15):已经有一张未支付的精英宝典订单时,**限购校验**
`checkUserBuyAuth` 会先返回 703
「已超过该商品的购买上限,下单失败~(如有未支付订单,请及时完成支付)」,
`createOrderV5` 根本不会执行(下单接口有时也会返回同一句)。限购 1 件的
商品旧单没付掉就再也下不了新单,这时应该拿旧单去发起支付,而不是把任务
判失败(官方页面同样是复用旧单继续付)。
真机核对(账号 hy_300546644):未支付单 #11353073 order_status=10、
pay_time=0、goods_detail.spu_id=hy-8328015;已取消单是 order_status=90。
查不到 / 接口不可用都返回空 dict。
"""
offset = 0
for _page in range(max(1, max_pages)):
resp = client.query_user_order_list(
uid=uid,
guid="",
cookie=cookie,
offset=offset,
page_size=page_size,
order_type=1,
status=0,
)
if resp is None:
return {}
orders = list(getattr(resp, "orders", None) or [])
for order in orders:
item = order.to_dict() if hasattr(order, "to_dict") else dict(order)
goods = item.get("goods_detail") or {}
if str(goods.get("spu_id") or "") != str(spu_id or ""):
continue
if int(item.get("pay_time") or 0) > 0:
continue
# 只认「待支付」:已取消(90)/已关闭(60) 的旧单付不了
if int(item.get("order_status") or 0) not in REUSABLE_ORDER_STATUSES:
continue
return item
total = int(getattr(resp, "totalCount", 0) or 0)
if len(orders) < page_size or offset + len(orders) >= total:
break
offset += len(orders)
return {}
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)
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,
}
order_id = 0
order_raw: dict = {}
reused_order: dict = {}
# 7) 购买权限
#
# 限购商品(精英宝典 buy_limit=1)已经挂着未支付旧单时,**先失败的是这一步**:
# 真机 2026-10-15 实测 checkUserBuyAuth 直接返回 703「已超过该商品的购买上限,
# 下单失败~(如有未支付订单,请及时完成支付)」,createOrderV5 根本不会执行。
# 所以这里失败也要先找同商品的未支付旧单接着付,找不到才判失败。
auth = client.check_user_buy_auth(
uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=sku_id
)
if auth is None:
return fail("购买权限校验接口无响应", **common)
if auth.code != 200:
auth_message = auth.message or f"购买权限校验失败: {auth.code}"
reused_order = find_reusable_order(
client, uid=uid, cookie=cookie, spu_id=spu_id
)
if not reused_order or not reused_order.get("order_id"):
return fail(auth_message, **common)
order_id = int(reused_order["order_id"])
order_raw = dict(reused_order)
emit(f"[{uid}] {auth_message};改为复用未支付订单 #{order_id} 继续支付")
# 8) 下单(限购商品若已有未支付的旧单,就复用旧单发起支付,而不是判失败)
if not order_id:
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,
)
if order_resp is not None and order_resp.code == 200 and order_resp.orderId:
order_id = int(order_resp.orderId)
order_raw = order_resp.to_dict()
else:
create_message = (
order_resp.message if order_resp is not None else "虎牙下单接口无响应"
) or f"虎牙下单失败: {getattr(order_resp, 'code', 0)}"
reused_order = find_reusable_order(
client, uid=uid, cookie=cookie, spu_id=spu_id
)
if not reused_order or not reused_order.get("order_id"):
return fail(create_message, **common)
order_id = int(reused_order["order_id"])
order_raw = dict(reused_order)
emit(f"[{uid}] {create_message};改为复用未支付订单 #{order_id} 继续支付")
common["order_raw"] = order_raw
common["reused_order"] = reused_order
# 9) 起支付(出支付宝/微信二维码)
pay_resp = client.pay_order_submit(
uid=uid,
guid="",
cookie=cookie,
order_id=order_id,
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=(
f"已复用未支付订单 #{order_id}" if reused_order else "已生成支付二维码"
),
order_id=order_id,
app_order_id=pay_resp.appOrderId,
pay_order_id=pay_resp.payOrderId,
pay_url=pay_resp.payUrl,
amount=amount,
**common,
)
+5
View File
@@ -32,6 +32,8 @@ import type {
HuyaTaskItem,
HuyaBrowserExchangeKit,
HuyaExchangeTargetKey,
HuyaExternalCkImportRequest,
HuyaExternalCkImportResult,
HuyaWorkbenchScope,
MessageCountResponse,
MessageDeletedResponse,
@@ -140,6 +142,9 @@ export const huyaApi = {
updateConfig: (data: Partial<HuyaConfig>) => api.put<HuyaConfig, HuyaConfig>('/huya/config', data),
listGoods: () => api.get<HuyaGoodsItem[], HuyaGoodsItem[]>('/huya/goods'),
listRechargeGoods: () => api.get<HuyaRechargeGoodsItem[], HuyaRechargeGoodsItem[]>('/huya/recharge-goods'),
/** 工作台导入外部 CK: 入库并把账号加入自己的工作台 (text 每行一条 CK) */
importWorkbenchCookies: (data: HuyaExternalCkImportRequest) =>
api.post<HuyaExternalCkImportResult, HuyaExternalCkImportResult>('/huya/workbench-accounts/import-cookies', data),
listWorkbenchAccounts: (scope: HuyaWorkbenchScope = 'elite') =>
api.get<{ account_ids: number[]; configured: boolean }, { account_ids: number[]; configured: boolean }>(
'/huya/workbench-accounts', { params: { handbook_scope: scope } },
+19
View File
@@ -695,6 +695,12 @@ export interface HuyaAccountItem {
game_name: string;
game_channel: string;
game_phone: string;
/** 精英宝典是否已开通(null = 还没查过) */
elite_opened?: boolean | null;
/** 最近一次宝典订单支付时间(Unix 毫秒) */
elite_open_time?: number | null;
/** 宝典有效期(Unix 毫秒;接口没给就是空) */
elite_expire_time?: number | null;
sms_url?: string;
assigned_to: number | null;
assigned_username: string | null;
@@ -1027,6 +1033,19 @@ export interface HuyaRechargeGoodsItem {
updated_at: string | null;
}
/** 工作台「导入外部 CK」:请求体 */
export interface HuyaExternalCkImportRequest {
text: string; // 多行文本,每行一条 CK(支持「账号----密码----CK」)
tag?: string;
handbook_scope?: HuyaWorkbenchScope;
}
/** 工作台「导入外部 CK」:结果(account_ids 是导入后的完整工作台账号集合) */
export interface HuyaExternalCkImportResult extends MessageCountResponse {
skipped: number;
account_ids: number[];
}
// ==================== Proxy ====================
export interface ProxyConfig {
@@ -0,0 +1,96 @@
import { useEffect, useState } from 'react';
import { Alert, Input, Modal, Select, Space, Typography } from 'antd';
import { huyaApi, type HuyaExternalCkImportResult, type HuyaWorkbenchScope } from '../api/modules';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
const { Text } = Typography;
export interface HuyaExternalCkImportModalProps {
open: boolean;
onClose: () => void;
/** 已有标签,供下拉选择 */
tags: string[];
defaultTag?: string;
scope?: HuyaWorkbenchScope;
/** 导入成功后回调(带完整的工作台账号集合) */
onImported: (result: HuyaExternalCkImportResult) => void;
}
/** 工作台「导入外部 CK」:粘贴外部 Cookie,入库并直接加入工作台,随后可在工作台操作 */
export default function HuyaExternalCkImportModal({
open, onClose, tags, defaultTag, scope = 'elite', onImported,
}: HuyaExternalCkImportModalProps) {
const [text, setText] = useState('');
const [tag, setTag] = useState(defaultTag || '');
const [importing, setImporting] = useState(false);
const [result, setResult] = useState<HuyaExternalCkImportResult | null>(null);
useEffect(() => {
if (!open) return;
setResult(null);
setTag(defaultTag || '');
}, [defaultTag, open]);
const submit = async () => {
const value = text.trim();
if (!value) { message.warning('请先粘贴 CK,每行一条'); return; }
setImporting(true);
try {
const saved = await huyaApi.importWorkbenchCookies({ text: value, tag, handbook_scope: scope });
setResult(saved);
message.success(saved.message || `已导入 ${saved.count} 条`);
onImported(saved);
} catch (error) {
message.error(getErrorMessage(error));
} finally {
setImporting(false);
}
};
return (
<Modal
open={open}
title="导入外部 CK 到工作台"
width={640}
onCancel={onClose}
onOk={() => void submit()}
confirmLoading={importing}
okText="导入"
cancelText="取消"
>
<Space direction="vertical" size={8} style={{ width: '100%' }}>
<Input.TextArea
rows={8}
value={text}
onChange={(event) => setText(event.target.value)}
placeholder={'每行一条 CK,支持 N 行批量导入\n支持格式:纯 CK 或 账号----密码----CK'}
/>
<Space size={8}>
<Text type="secondary">标签</Text>
<Select
allowClear
showSearch
optionFilterProp="label"
placeholder="可选"
value={tag || undefined}
onChange={(value) => setTag(value || '')}
options={tags.map((item) => ({ value: item, label: item }))}
style={{ width: 220 }}
/>
</Space>
<Text type="secondary" style={{ fontSize: 12 }}>
导入后账号会直接加入当前工作台,可照常执行「生成开通支付码 / 绑定二维码 / 查询角色 / 刷新积分」等操作。
</Text>
{result && (
<Alert
type={result.count ? 'success' : 'warning'}
showIcon
message={result.message}
description={`成功 ${result.count} 条,跳过 ${result.skipped} 条;工作台现有 ${result.account_ids.length} 个账号`}
/>
)}
</Space>
</Modal>
);
}
+154 -20
View File
@@ -5,16 +5,17 @@ import {
} from 'antd';
import type { TableProps } from 'antd';
import {
CheckCircleOutlined, ColumnWidthOutlined, GiftOutlined, ImportOutlined, QrcodeOutlined,
ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined,
CheckCircleOutlined, ColumnWidthOutlined, CopyOutlined, GiftOutlined, ImportOutlined, QrcodeOutlined,
ReloadOutlined, SearchOutlined, SettingOutlined, ShoppingOutlined, StopOutlined, ZoomInOutlined,
} from '@ant-design/icons';
import { huyaApi, type HuyaAccountItem, type HuyaConfig, type HuyaGoodsItem, type HuyaRechargeGoodsItem, type HuyaTaskItem } from '../api/modules';
import HuyaExternalCkImportModal from '../components/HuyaExternalCkImportModal';
import RealtimeLogPanel from '../components/RealtimeLogPanel';
import { usePermissions } from '../hooks/usePermissions';
import { useWebSocketLogs } from '../hooks/useWebSocketLogs';
import { getErrorMessage } from '../utils/error';
import { message } from '../utils/antdMessage';
import { formatTime } from '../utils/time';
import { formatTime, formatUnixSeconds } from '../utils/time';
const { Text } = Typography;
const SCOPE = 'elite' as const;
@@ -26,7 +27,7 @@ const TASK_LABELS: Record<string, string> = {
query_act_tasks: '读取宝典任务', get_bind_qr: '获取绑定二维码', query_game_name: '查询游戏角色',
confirm_bind: '确认绑定角色', query_points: '查询积分', refresh_goods: '刷新商品',
exchange_goods: '兑换商品', query_exchange_records: '查询兑换记录', create_recharge_order: '生成开通支付码',
refresh_recharge_goods: '刷新开通商品',
refresh_recharge_goods: '刷新开通商品', query_all: '一键查询(宝典+角色+积分)',
};
const TASK_COLORS: Record<string, string> = {
planned: 'default', pending: 'default', running: 'processing', success: 'success',
@@ -38,6 +39,7 @@ const TASK_STATUS_LABELS: Record<string, string> = {
};
const HUYA_QUICK_ACTIONS = [
{ key: 'query_all', icon: <SearchOutlined /> },
{ key: 'get_bind_qr', icon: <QrcodeOutlined /> },
{ key: 'query_game_name', icon: <SearchOutlined /> },
{ key: 'confirm_bind', icon: <CheckCircleOutlined /> },
@@ -57,18 +59,59 @@ function resultText(task: HuyaTaskItem | undefined, key: string): string {
return value == null ? '' : String(value);
}
/** 开通支付码是否还需要扫码:已支付或已确认开通就不用再展示了 */
function needsScanPay(task: HuyaTaskItem): boolean {
const result = task.result || {};
return !(result.payment_paid === true || result.elite_opened === true);
}
/**
* 列表「二维码」列的占位文案:扫码这件事做完后就别再挂二维码了(真机反馈:
* 支付成功后那一格还挂着码,容易被当成待支付)。返回 null 表示仍要展示二维码。
*
* 只针对「开通支付码」:绑定二维码那类任务 status=success 只代表码生成成功,
* 客户还没扫,必须继续展示。
*/
function qrDoneLabel(task: HuyaTaskItem): string | null {
if (task.task_type !== 'create_recharge_order') return null;
if (needsScanPay(task)) return null;
return task.result?.elite_opened === true ? '已开通' : '已支付';
}
/**
* 二维码里放**短地址**:支付宝网关地址 1600+ 字符,直接编成二维码有 140+ 个模块,
* 手机根本扫不上(生产实测)。优先级:
* 1. `pay_cashier_url` —— 支付宝收银台直达地址(约 74 字符、公网域名,任意手机可扫码支付);
* 2. `pay_qr_path` —— 本站短链 `/api/huya/pay/<id>?k=<签名>`,手机打开后 302 跳到真实支付地址,
* 但要求当前页面域名手机能访问到(localhost 不行);
* 3. `pay_url` —— 原始网关地址,兜底。
*/
function payQrValue(task: HuyaTaskItem): string {
const cashier = resultText(task, 'pay_cashier_url');
if (cashier) return cashier;
const path = resultText(task, 'pay_qr_path');
return path ? `${window.location.origin}${path}` : resultText(task, 'pay_url');
}
/** 二维码内容指向本机时手机一定扫不开(localhost / 127.0.0.1 / 内网回环)。 */
function isLoopbackUrl(url: string): boolean {
return /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i.test(url);
}
function latestTask(tasks: HuyaTaskItem[], accountId: number): HuyaTaskItem | undefined {
return tasks.filter((task) => task.account_id === accountId).sort((a, b) => b.id - a.id)[0];
}
function taskQrUrl(task: HuyaTaskItem | undefined): string {
if (!task) return '';
return resultText(task, 'bind_redirect_url') || resultText(task, 'pay_url') || resultText(task, 'url');
if (task.task_type === 'create_recharge_order') return payQrValue(task);
return resultText(task, 'bind_redirect_url') || resultText(task, 'url');
}
export default function HuyaElitePage() {
const { can } = usePermissions();
const canConfig = can('huya:config');
const canImport = can('huya:import');
const [pool, setPool] = useState<HuyaAccountItem[]>([]);
const [accounts, setAccounts] = useState<HuyaAccountItem[]>([]);
const [selectedIds, setSelectedIds] = useState<number[]>([]);
@@ -76,7 +119,7 @@ export default function HuyaElitePage() {
const [goods, setGoods] = useState<HuyaGoodsItem[]>([]);
const [selectedGoodsId, setSelectedGoodsId] = useState('');
const [rechargeGoods, setRechargeGoods] = useState<HuyaRechargeGoodsItem[]>([]);
const [selectedRechargeSpu, setSelectedRechargeSpu] = useState('hy-5879340');
const [selectedRechargeSpu, setSelectedRechargeSpu] = useState('');
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(false);
const [starting, setStarting] = useState(false);
@@ -90,6 +133,12 @@ export default function HuyaElitePage() {
const [importTags, setImportTags] = useState<string[]>([]);
const [importSelected, setImportSelected] = useState<number[]>([]);
const [qrTask, setQrTask] = useState<HuyaTaskItem | null>(null);
// 开通支付码:多选账号时可以一次生成多个码,弹窗里逐个展示(按批次收集)
const [payBatchIds, setPayBatchIds] = useState<string[]>([]);
const [payOpen, setPayOpen] = useState(false);
// 放大扫码用(二维码在弹窗里开到底,手机才好扫)
const [zoomPayTask, setZoomPayTask] = useState<HuyaTaskItem | null>(null);
const [ckImportOpen, setCkImportOpen] = useState(false);
const [config, setConfig] = useState<HuyaConfig | null>(null);
const [configDraft, setConfigDraft] = useState<HuyaConfig | null>(null);
const [configOpen, setConfigOpen] = useState(false);
@@ -127,7 +176,7 @@ export default function HuyaElitePage() {
}, []);
useEffect(() => { void load(); }, [load]);
useEffect(() => { if (importOpen) void huyaApi.listTags().then(setImportTags).catch(() => {}); }, [importOpen]);
useEffect(() => { if (importOpen || ckImportOpen) void huyaApi.listTags().then(setImportTags).catch(() => {}); }, [ckImportOpen, importOpen]);
useEffect(() => {
const active = tasks.some((task) => ['planned', 'pending', 'running'].includes(task.status));
const timer = window.setInterval(() => { void loadTasks(); }, (active ? 3 : refreshInterval) * 1000);
@@ -172,13 +221,18 @@ export default function HuyaElitePage() {
})() : {};
const created = await huyaApi.createTasks({ account_ids: accountIds, task_type: taskType, handbook_scope: SCOPE, concurrency, payload });
setActiveBatches((prev) => [...new Set([...prev, created.batch_id])]);
if (taskType === 'create_recharge_order') {
// 多选账号时每个账号一个支付码:收进同一列表,弹窗里一起展示
setPayBatchIds((prev) => [...new Set([...prev, created.batch_id])]);
setPayOpen(true);
}
logs.connectBatch(created.batch_id, `/api/huya/ws/${created.batch_id}`, {
clear: false,
onTask: (raw) => {
const next = raw as unknown as HuyaTaskItem;
setTasks((prev) => [next, ...prev.filter((item) => item.id !== next.id)].slice(0, 300));
const result = next.result || {};
if (next.task_type === 'create_recharge_order' && typeof result.pay_url === 'string' && result.pay_url) setQrTask(next);
if (next.task_type === 'create_recharge_order' && result.pay_url) setPayOpen(true);
if (next.task_type === 'get_bind_qr' && (result.mini_qrcode_image || result.bind_redirect_url)) setQrTask(next);
},
onResult: () => { setActiveBatches((prev) => prev.filter((id) => id !== created.batch_id)); void load(); },
@@ -234,26 +288,56 @@ export default function HuyaElitePage() {
const filteredAccounts = useMemo(() => {
const value = search.trim().toLowerCase();
return accounts.filter((item) => !value || [item.uid, item.nickname, item.username, item.tag, item.game_name].some((v) => String(v || '').toLowerCase().includes(value)));
return accounts.filter((item) => !value || [item.uid, item.nickname, item.username, item.tag, item.game_name, item.game_phone].some((v) => String(v || '').toLowerCase().includes(value)));
}, [accounts, search]);
const filteredGoods = useMemo(() => goods.map((item) => ({ ...item, label: `${item.name} / ${item.price ?? '-'}分 / ${item.remain_text || '动态库存'}` })), [goods]);
const filteredRechargeGoods = useMemo(() => rechargeGoods.map((item) => ({ ...item, label: `${item.name || item.spu_id} / ${item.price ? `${(item.price / 100).toFixed(2)}元` : '价格动态'}` })), [rechargeGoods]);
const filteredRechargeGoods = useMemo(() => rechargeGoods.map((item) => ({ ...item, label: `${item.name || item.spu_id} / ${item.price ? `${(item.price / 100).toFixed(2)}元` : '价格动态'} / ${item.spu_id}` })).sort((a, b) => Number(a.raw?.raw_order ?? 0) - Number(b.raw?.raw_order ?? 0) || a.id - b.id), [rechargeGoods]);
// 默认选中列表里的第一个商品;已选商品从列表消失时同步回落到第一个
useEffect(() => {
if (!filteredRechargeGoods.length) return;
if (!filteredRechargeGoods.some((item) => item.spu_id === selectedRechargeSpu)) {
setSelectedRechargeSpu(filteredRechargeGoods[0].spu_id);
}
}, [filteredRechargeGoods, selectedRechargeSpu]);
const exchangeCount = tasks.filter((task) => task.task_type === 'exchange_goods').length;
// 开通支付码:同一批次里每个账号一个码,未支付的排前面;已支付/已开通的只留一行状态
const payTasks = useMemo(() => {
const list = tasks.filter((task) => task.task_type === 'create_recharge_order'
&& payBatchIds.includes(task.batch_id)
&& Boolean(resultText(task, 'pay_url') || resultText(task, 'mini_qrcode_image')));
return [...list].sort((a, b) => Number(needsScanPay(b)) - Number(needsScanPay(a)) || a.id - b.id);
}, [tasks, payBatchIds]);
const payPendingTasks = payTasks.filter(needsScanPay);
const payDoneTasks = payTasks.filter((task) => !needsScanPay(task));
const openPayTasks = (batchId?: string) => {
if (batchId) setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId]));
setPayOpen(true);
};
const payTaskLabel = (task: HuyaTaskItem) => task.account_nickname || task.account_uid || `#${task.account_id}`;
const copyPayLink = async (text: string, label: string) => {
if (!text) { message.warning('没有可复制的链接'); return; }
try { await navigator.clipboard.writeText(text); message.success(`${label}已复制`); }
catch { message.error('复制失败,请手动选中复制'); }
};
// 列宽按比例分配(percent),表头与单元格统一居中,避免左右跳着看
const accountColumns: TableProps<HuyaAccountItem>['columns'] = [
{ title: '#', width: 45, render: (_value, _row, index) => <Text type="secondary">{index + 1}</Text> },
{ title: '账号', width: 180, render: (_value, row) => <Space direction="vertical" size={0} style={{ width: '100%' }}><Text strong ellipsis title={row.nickname || row.username || row.uid}>{row.nickname || row.username || row.uid}</Text><Text type="secondary" style={{ fontSize: 12 }} ellipsis title={row.username}>UID {row.uid || '-'}</Text></Space> },
{ title: '游戏名', width: 160, render: (_value, row) => <Space direction="vertical" size={0} style={{ width: '100%' }}><Text ellipsis title={row.game_name || row.game_channel}>{row.game_name || <Text type="secondary">未查询</Text>}</Text>{row.game_channel && <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{row.game_channel}</Text>}</Space> },
{ title: '积分', dataIndex: 'points', width: 75, align: 'right', render: (value: number | null) => value ?? <Text type="secondary">-</Text> },
{ title: '最近操作', width: 250, render: (_value, row) => { const task = latestTask(tasks, row.id); return task ? <Space direction="vertical" size={1} style={{ width: '100%' }}><Space size={4}><Tag color={TASK_COLORS[task.status] || 'default'}>{TASK_STATUS_LABELS[task.status] || task.status}</Tag><Text strong ellipsis>{TASK_LABELS[task.task_type] || task.task_type}</Text></Space><Text type="secondary" ellipsis title={task.message}>{task.message || '-'}</Text><Text type="secondary" style={{ fontSize: 12 }}>{formatTime(task.finished_at || task.created_at)}</Text></Space> : <Text type="secondary">暂无操作</Text>; } },
{ title: '二维码', width: 80, align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); const url = taskQrUrl(task); const image = resultText(task, 'mini_qrcode_image'); if (!url && !image) return <Text type="secondary">-</Text>; return <div onClick={(event) => { event.stopPropagation(); if (task) void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0 }} title="点击查看二维码">{image ? <img src={`data:image/png;base64,${image}`} alt="二维码" style={{ width: 52, height: 52, objectFit: 'contain' }} /> : <QRCode value={url} size={52} bordered={false} />}</div>; } },
{ title: '状态', width: 90, render: (_value, row) => { const task = latestTask(tasks, row.id); const status = task?.status || row.status || ''; return <Tag color={TASK_COLORS[status] || 'default'}>{TASK_STATUS_LABELS[status] || status || '待操作'}</Tag>; } },
{ title: '#', width: '4%', align: 'center', render: (_value, _row, index) => <Text type="secondary">{index + 1}</Text> },
{ title: '账号', width: '15%', align: 'center', ellipsis: true, render: (_value, row) => <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Text strong ellipsis title={row.nickname || row.username || row.uid}>{row.nickname || row.username || row.uid}</Text><Text type="secondary" style={{ fontSize: 12 }} ellipsis title={row.username}>UID {row.uid || '-'}</Text></Space> },
{ title: '手机号', width: '10%', align: 'center', ellipsis: true, render: (_value, row) => row.game_phone || <Text type="secondary">-</Text> },
{ title: '游戏名', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Text ellipsis title={row.game_name || row.game_channel}>{row.game_name || <Text type="secondary">未查询</Text>}</Text>{row.game_channel && <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{row.game_channel}</Text>}</Space> },
{ title: '精英宝典', width: '13%', align: 'center', ellipsis: true, render: (_value, row) => <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Tag color={row.elite_opened === true ? 'success' : row.elite_opened === false ? 'default' : undefined}>{row.elite_opened === true ? '已开通' : row.elite_opened === false ? '未开通' : '未查询'}</Tag>{row.elite_opened === true && row.elite_open_time ? <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{`开通 ${formatUnixSeconds(row.elite_open_time)}`}</Text> : null}{row.elite_expire_time ? <Text type="secondary" style={{ fontSize: 12 }} ellipsis>{`有效期至 ${formatUnixSeconds(row.elite_expire_time)}`}</Text> : null}</Space> },
{ title: '积分', dataIndex: 'points', width: '7%', align: 'center', render: (value: number | null) => value ?? <Text type="secondary">-</Text> },
{ title: '最近操作', width: '25%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); return task ? <Space direction="vertical" align="center" size={1} style={{ width: '100%' }}><Text strong ellipsis>{TASK_LABELS[task.task_type] || task.task_type}</Text><Text type="secondary" ellipsis title={task.message}>{task.message || '-'}</Text><Text type="secondary" style={{ fontSize: 12 }}>{formatTime(task.finished_at || task.created_at)}</Text></Space> : <Text type="secondary">暂无操作</Text>; } },
{ title: '二维码', width: '6%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (!task) return <Text type="secondary">-</Text>; const url = taskQrUrl(task); const image = resultText(task, 'mini_qrcode_image'); if (!url && !image) return <Text type="secondary">-</Text>; const doneLabel = qrDoneLabel(task); if (doneLabel) return <Text type="secondary">{doneLabel}</Text>; return <div onClick={(event) => { event.stopPropagation(); if (!task) return; if (task.task_type === 'create_recharge_order') setZoomPayTask(task); else void openQrTask(task); }} style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0, background: '#fff', padding: 3, borderRadius: 4 }} title="点击放大扫码">{image ? <img src={`data:image/png;base64,${image}`} alt="二维码" style={{ width: 52, height: 52, objectFit: 'contain' }} /> : <QRCode value={url} size={52} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" />}</div>; } },
{ title: '状态', width: '7%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); const status = task?.status || row.status || ''; return <Tag color={TASK_COLORS[status] || 'default'}>{TASK_STATUS_LABELS[status] || status || '待操作'}</Tag>; } },
];
const operationBody = (
<Space direction="vertical" size={10} style={{ width: '100%' }}>
<div className="huya-operation-section"><div className="huya-operation-title"><QrcodeOutlined /><span>绑定与查询</span></div><div className="huya-action-grid">
<Button size="small" icon={<QrcodeOutlined />} onClick={() => void startTask('get_bind_qr')} disabled={starting || !selectedIds.length}>绑定二维码</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_game_name')} disabled={starting || !selectedIds.length}>查询角色</Button><Button size="small" icon={<CheckCircleOutlined />} onClick={() => void startTask('confirm_bind')} disabled={starting || !selectedIds.length}>确认绑定</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_points')} disabled={starting || !selectedIds.length}>刷新积分</Button><Button size="small" onClick={() => void startTask('query_act_tasks')} disabled={starting || !selectedIds.length}>宝典任务</Button><Button size="small" onClick={() => void startTask('query_exchange_records')} disabled={starting || !selectedIds.length}>兑换记录</Button>
<Button size="small" type="primary" icon={<SearchOutlined />} onClick={() => void startTask('query_all')} disabled={starting || !selectedIds.length}>一键查询</Button><Button size="small" icon={<QrcodeOutlined />} onClick={() => void startTask('get_bind_qr')} disabled={starting || !selectedIds.length}>绑定二维码</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_game_name')} disabled={starting || !selectedIds.length}>查询角色</Button><Button size="small" icon={<CheckCircleOutlined />} onClick={() => void startTask('confirm_bind')} disabled={starting || !selectedIds.length}>确认绑定</Button><Button size="small" icon={<SearchOutlined />} onClick={() => void startTask('query_points')} disabled={starting || !selectedIds.length}>刷新积分</Button><Button size="small" onClick={() => void startTask('query_act_tasks')} disabled={starting || !selectedIds.length}>宝典任务</Button><Button size="small" onClick={() => void startTask('query_exchange_records')} disabled={starting || !selectedIds.length}>兑换记录</Button>
</div></div>
<div className="huya-operation-section"><div className="huya-operation-title"><ShoppingOutlined /><span>兑换</span></div><Select size="small" showSearch optionFilterProp="label" value={selectedGoodsId || undefined} onChange={setSelectedGoodsId} options={filteredGoods.map((item) => ({ value: item.product_id, label: item.label }))} placeholder="选择兑换商品" style={{ width: '100%' }} /><div className="huya-action-grid"><Button size="small" icon={<ReloadOutlined />} onClick={() => void startTask('refresh_goods')} disabled={starting || !selectedIds.length}>刷新商品</Button><Button size="small" type="primary" icon={<ShoppingOutlined />} onClick={() => void startTask('exchange_goods')} disabled={starting || !selectedIds.length || !selectedGoodsId}>兑换商品</Button></div></div>
<div className="huya-operation-section"><div className="huya-operation-title"><GiftOutlined /><span>开通宝典</span></div><Button block size="small" icon={<QrcodeOutlined />} onClick={() => void startTask('create_recharge_order')} disabled={starting || !selectedIds.length}>生成开通支付码</Button></div>
@@ -262,7 +346,7 @@ export default function HuyaElitePage() {
</Space>
);
const accountsBody = <><Space style={{ marginBottom: 8, width: '100%', justifyContent: 'space-between' }} wrap><Input size="small" allowClear prefix={<SearchOutlined />} placeholder="搜索账号/昵称/游戏名" value={search} onChange={(event) => setSearch(event.target.value)} style={{ width: 240 }} /><Space><Button size="small" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>导入账号</Button>{selectedIds.length > 0 && <Button size="small" danger onClick={() => void saveAccounts(accounts.map((item) => item.id).filter((id) => !selectedIds.includes(id)))}>移出选中</Button>}</Space></Space><div className="huya-account-table"><Table rowKey="id" size="small" loading={loading} tableLayout="fixed" rowSelection={{ selectedRowKeys: selectedIds, onChange: (keys) => setSelectedIds(keys.map(Number)) }} columns={accountColumns} dataSource={filteredAccounts} locale={{ emptyText: '工作台暂无账号,点击右上角「导入账号」添加' }} pagination={{ pageSize: 20, showSizeChanger: true, showTotal: (total) => `共 ${total} 条` }} scroll={{ x: 1040, y: 'calc(100vh - 300px)' }} onRow={(row) => ({ onClick: () => { const task = latestTask(tasks, row.id); if (task && ['get_bind_qr', 'create_recharge_order'].includes(task.task_type) && task.result) void openQrTask(task); }, onContextMenu: (event) => handleRowContextMenu(row, event), style: { cursor: 'context-menu' }, title: '右键打开账号动作' })} /></div></>;
const accountsBody = <><Space style={{ marginBottom: 8, width: '100%', justifyContent: 'space-between' }} wrap><Input size="small" allowClear prefix={<SearchOutlined />} placeholder="搜索账号/昵称/游戏名/手机号" value={search} onChange={(event) => setSearch(event.target.value)} style={{ width: 240 }} /><Space><Button size="small" icon={<ImportOutlined />} onClick={() => setImportOpen(true)}>导入账号</Button>{canImport && <Button size="small" icon={<ImportOutlined />} onClick={() => setCkImportOpen(true)}>导入外部 CK</Button>}{selectedIds.length > 0 && <Button size="small" danger onClick={() => void saveAccounts(accounts.map((item) => item.id).filter((id) => !selectedIds.includes(id)))}>移出选中</Button>}</Space></Space><div className="huya-account-table"><Table rowKey="id" size="small" loading={loading} tableLayout="fixed" rowSelection={{ selectedRowKeys: selectedIds, onChange: (keys) => setSelectedIds(keys.map(Number)) }} columns={accountColumns} dataSource={filteredAccounts} locale={{ emptyText: '工作台暂无账号,点击右上角「导入账号」添加' }} pagination={{ pageSize: 20, showSizeChanger: true, showTotal: (total) => `共 ${total} 条` }} scroll={{ y: 'calc(100vh - 300px)' }} onRow={(row) => ({ onClick: () => { const task = latestTask(tasks, row.id); if (!task?.result) return; if (task.task_type === 'get_bind_qr') void openQrTask(task); else if (task.task_type === 'create_recharge_order') openPayTasks(task.batch_id); }, onContextMenu: (event) => handleRowContextMenu(row, event), style: { cursor: 'context-menu' }, title: '右键打开账号动作' })} /></div></>;
const configField = (key: Exclude<keyof HuyaConfig, 'updated_at'>, label: string) => configDraft && <Space key={key} style={{ width: '100%', justifyContent: 'space-between' }}><Text>{label}</Text><Input value={configDraft[key] || ''} onChange={(event) => setConfigDraft({ ...configDraft, [key]: event.target.value })} style={{ width: 300 }} /></Space>;
const contextMenuStyle = contextMenu ? {
@@ -279,8 +363,58 @@ export default function HuyaElitePage() {
{layoutMode === 'split' ? <div style={{ flex: 1, minHeight: 0, display: 'flex', gap: 12, overflow: 'hidden' }}><Card size="small" title="账号" extra={<Tag color="blue">已选 {selectedIds.length}/{accounts.length}</Tag>} style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} styles={{ body: { flex: 1, minHeight: 0, padding: '4px 6px', overflow: 'hidden', display: 'flex', flexDirection: 'column' } }}>{accountsBody}</Card><Card size="small" title="精英宝典操作" extra={<Space size={4}><Text type="secondary">并发</Text><InputNumber size="small" min={1} max={10} value={concurrency} onChange={(value) => setConcurrency(value || 1)} style={{ width: 58 }} /></Space>} style={{ width: 360, flexShrink: 0, minHeight: 0, overflow: 'hidden' }} styles={{ body: { padding: 8, overflowY: 'auto', height: 'calc(100% - 38px)' } }}>{operationBody}</Card></div> : <><Card size="small" title="精英宝典操作" extra={<Space size={4}><Text type="secondary">并发</Text><InputNumber size="small" min={1} max={10} value={concurrency} onChange={(value) => setConcurrency(value || 1)} style={{ width: 58 }} /></Space>} style={{ flexShrink: 0, marginBottom: 12 }} styles={{ body: { padding: 8 } }}>{operationBody}</Card><Card size="small" title="账号" extra={<Tag color="blue">已选 {selectedIds.length}/{accounts.length}</Tag>} style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }} styles={{ body: { flex: 1, minHeight: 0, padding: '4px 6px', overflow: 'hidden', display: 'flex', flexDirection: 'column' } }}>{accountsBody}</Card></>}
<Text type="secondary" style={{ fontSize: 12, marginTop: 6 }}>兑换任务 {exchangeCount} 条;勾选账号后可批量执行,账号行支持右键操作。</Text>
{contextMenu && <div style={contextMenuStyle} onClick={(event) => event.stopPropagation()}><Card size="small" title={contextMenu.accountIds.length > 1 ? '批量动作' : '账号动作'} styles={{ body: { padding: 4 } }} style={{ width: 220, boxShadow: '0 4px 12px rgba(0,0,0,0.14)' }}><Space direction="vertical" style={{ width: '100%' }}>{HUYA_QUICK_ACTIONS.map((item) => <Button key={item.key} block size="small" type="text" icon={item.icon} onClick={() => runContextAction(item.key)} disabled={starting} style={{ justifyContent: 'flex-start' }}>{TASK_LABELS[item.key] || item.key}</Button>)}</Space></Card></div>}
<Modal open={qrTask !== null} title={qrTask?.task_type === 'create_recharge_order' ? '开通支付二维码' : '绑定二维码'} footer={null} onCancel={() => setQrTask(null)} centered>{qrTask && <div style={{ textAlign: 'center' }}>{resultText(qrTask, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(qrTask, 'mini_qrcode_image')}`} alt="绑定二维码" style={{ width: 240, height: 240 }} /> : <QRCode value={resultText(qrTask, 'pay_url') || resultText(qrTask, 'bind_redirect_url') || 'https://zt.huya.com/b02faae1/pc/index.html'} size={240} />}<p><Tag color={TASK_COLORS[qrTask.status] || 'default'}>{qrTask.message || qrTask.status}</Tag></p>{qrTask.task_type === 'create_recharge_order' && <Text type="secondary">扫码后订单状态会自动轮询更新</Text>}</div>}</Modal>
<Modal open={qrTask !== null} title="绑定二维码" footer={null} onCancel={() => setQrTask(null)} centered>{qrTask && <div style={{ textAlign: 'center' }}>{resultText(qrTask, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(qrTask, 'mini_qrcode_image')}`} alt="绑定二维码" style={{ width: 240, height: 240 }} /> : <QRCode value={resultText(qrTask, 'bind_redirect_url') || 'https://zt.huya.com/b02faae1/pc/index.html'} size={240} color="#000" bgColor="#fff" />}<p><Tag color={TASK_COLORS[qrTask.status] || 'default'}>{qrTask.message || qrTask.status}</Tag></p></div>}</Modal>
<Modal
open={payOpen}
title={payTasks.length ? `开通支付码(${payDoneTasks.length}/${payTasks.length} 已完成)` : '开通支付码'}
width={880}
centered
onCancel={() => setPayOpen(false)}
footer={<Space><Text type="secondary">支付后会自动确认开通状态;已开通的码自动收起</Text><Button onClick={() => setPayOpen(false)}>关闭</Button><Button onClick={() => { setPayBatchIds([]); setPayOpen(false); }}>清空列表</Button></Space>}
>
{payTasks.length === 0 ? <div style={{ padding: 24, textAlign: 'center' }}><Text type="secondary">正在为选中的账号生成支付码…</Text></div> : <div style={{ maxHeight: '62vh', overflowY: 'auto' }}>
{payPendingTasks.length > 0 && <Space direction="vertical" size={10} style={{ width: '100%' }}>
{payPendingTasks.map((task) => {
const qrValue = payQrValue(task);
return (
<div key={task.id} style={{ display: 'flex', gap: 16, alignItems: 'center', border: '1px solid rgba(128,128,128,.22)', borderRadius: 6, padding: 10, textAlign: 'left' }}>
<div style={{ background: '#fff', padding: 8, borderRadius: 6, lineHeight: 0 }}>{resultText(task, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(task, 'mini_qrcode_image')}`} alt="支付码" style={{ width: 180, height: 180 }} /> : <QRCode value={qrValue} size={180} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" />}</div>
<Space direction="vertical" size={2} style={{ flex: 1, minWidth: 0 }}>
<Text strong ellipsis>{payTaskLabel(task)}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>UID {task.account_uid || '-'}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>{[resultText(task, 'product_name') || '精英宝典', resultText(task, 'amount_text')].filter(Boolean).join(' ')}</Text>
<Tag color={TASK_COLORS[task.status] || 'default'}>{resultText(task, 'payment_status_label') || TASK_STATUS_LABELS[task.status] || task.status}</Tag>
<Text type="secondary" ellipsis title={task.message}>{task.message || '-'}</Text>
{isLoopbackUrl(qrValue) && <Text type="warning" style={{ fontSize: 12 }}>二维码是本机地址(localhost),手机扫不开;请用公网域名打开本页后重新生成</Text>}
<Space size={6}>
<Button size="small" icon={<ZoomInOutlined />} onClick={() => setZoomPayTask(task)}>放大扫码</Button>
<Button size="small" icon={<CopyOutlined />} onClick={() => void copyPayLink(qrValue, '支付链接')}>复制链接</Button>
</Space>
</Space>
</div>
);
})}
</Space>}
{payDoneTasks.length > 0 && <div style={{ marginTop: payPendingTasks.length ? 12 : 0, textAlign: 'left' }}>
<Text type="secondary" style={{ fontSize: 12 }}>已完成(二维码已收起)</Text>
<div style={{ marginTop: 6, display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{payDoneTasks.map((task) => (
<Tag key={task.id} color={task.result?.elite_opened === true ? 'success' : 'blue'}>{payTaskLabel(task)} · {task.result?.elite_opened === true ? '已开通' : resultText(task, 'payment_status_label') || '已支付'}</Tag>
))}
</div>
</div>}
</div>}
</Modal>
<Modal open={zoomPayTask !== null} title={`扫码支付 · ${zoomPayTask ? payTaskLabel(zoomPayTask) : ''}`} footer={null} onCancel={() => setZoomPayTask(null)} width={680} centered>
{zoomPayTask && <div style={{ textAlign: 'center' }}>
<div style={{ display: 'inline-block', background: '#fff', padding: 16, borderRadius: 8, lineHeight: 0 }}><QRCode value={payQrValue(zoomPayTask)} size={520} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" /></div>
<p><Space size={8}><Tag color={TASK_COLORS[zoomPayTask.status] || 'default'}>{resultText(zoomPayTask, 'payment_status_label') || zoomPayTask.status}</Tag><Text type="secondary">{resultText(zoomPayTask, 'amount_text')}</Text></Space></p>
<Text type="secondary" style={{ fontSize: 12, wordBreak: 'break-all' }}>{payQrValue(zoomPayTask)}</Text>
<div style={{ marginTop: 10 }}><Space><Button size="small" icon={<CopyOutlined />} onClick={() => void copyPayLink(payQrValue(zoomPayTask), '支付链接')}>复制支付链接</Button><Button size="small" onClick={() => void copyPayLink(resultText(zoomPayTask, 'pay_url'), '原始支付链接')}>复制原始链接</Button></Space></div>
</div>}
</Modal>
<Modal open={importOpen} title="导入精英宝典账号" onCancel={() => setImportOpen(false)} onOk={() => { void saveAccounts([...new Set([...accounts.map((item) => item.id), ...importSelected])]).then(() => { setImportSelected([]); setImportOpen(false); }).catch((error) => message.error(getErrorMessage(error))); }} okText="导入" cancelText="取消"><Input.Search allowClear placeholder="搜索账号" value={importSearch} onChange={(event) => setImportSearch(event.target.value)} style={{ marginBottom: 8 }} /><Select allowClear placeholder="标签" value={importTag || undefined} onChange={(value) => setImportTag(value || '')} options={importTags.map((tag) => ({ value: tag, label: tag }))} style={{ width: '100%', marginBottom: 8 }} /><Table rowKey="id" size="small" dataSource={pool.filter((item) => !accounts.some((current) => current.id === item.id) && (!importSearch || [item.uid, item.nickname, item.username].some((value) => String(value || '').includes(importSearch))) && (!importTag || item.tag === importTag))} columns={[{ title: '账号', render: (_value, row) => row.nickname || row.username || row.uid }, { title: '标签', dataIndex: 'tag' }]} pagination={{ pageSize: 8 }} rowSelection={{ selectedRowKeys: importSelected, onChange: (keys) => setImportSelected(keys.map(Number)) }} /></Modal>
<Modal open={configOpen} title="精英宝典设置" onCancel={() => setConfigOpen(false)} onOk={() => void saveConfig()} confirmLoading={configSaving} okText="保存" cancelText="取消" width={500}>{configLoading ? <div style={{ padding: 24, textAlign: 'center' }}>加载中...</div> : configDraft && <Space direction="vertical" size={10} style={{ width: '100%' }}>{configField('sid', '活动 SID')}{configField('bind_act_id', '绑定活动 ID')}{configField('outer_act_id', '外部活动 ID')}{configField('room_pid', '直播间 PID')}{configField('pay_channel', '支付渠道')}<Space style={{ width: '100%', justifyContent: 'space-between' }}><Text>空闲轮询间隔(秒)</Text><InputNumber min={5} max={60} value={refreshInterval} onChange={(value) => { const next = Math.min(60, Math.max(5, value || 15)); setRefreshInterval(next); localStorage.setItem('huya_elite_refresh_interval', String(next)); }} style={{ width: 300 }} /></Space></Space>}</Modal>
<HuyaExternalCkImportModal open={ckImportOpen} onClose={() => setCkImportOpen(false)} tags={importTags} scope={SCOPE} onImported={(result) => { localStorage.setItem('huya_elite_workbench_account_ids', JSON.stringify(result.account_ids)); void load(); }} />
</div>;
}
+21 -4
View File
@@ -31,6 +31,7 @@ const FALLBACK_TASK_TYPES: Record<string, string> = {
confirm_bind: '确认绑定',
query_points: '一键查询积分',
query_game_name: '一键查询游戏名',
query_all: '一键查询(角色+宝典+积分)',
query_exchange_records: '一键查询兑换记录',
refresh_goods: '刷新商品列表',
refresh_recharge_goods: '刷新充值商品列表',
@@ -39,6 +40,7 @@ const FALLBACK_TASK_TYPES: Record<string, string> = {
};
const QUICK_ACTIONS = [
{ key: 'query_all', icon: <SearchOutlined /> },
{ key: 'get_bind_qr', icon: <LinkOutlined /> },
{ key: 'confirm_bind', icon: <CheckCircleOutlined /> },
{ key: 'query_points', icon: <SearchOutlined /> },
@@ -676,7 +678,7 @@ export default function HuyaTasksPage() {
const rechargeGoodsOptions = useMemo(() => {
return sortedRechargeGoods.map((item) => ({
value: item.spu_id,
label: `${item.name || item.spu_id}${item.price ? ` / ${formatPriceText(item.price)}` : ''}`,
label: `${item.name || item.spu_id}${item.price ? ` / ${formatPriceText(item.price)}` : ''} / ${item.spu_id}`,
}));
}, [sortedRechargeGoods]);
@@ -1136,9 +1138,24 @@ export default function HuyaTasksPage() {
return <Text type="secondary">-</Text>;
}
const availableScore = value?.available_score;
if (typeof availableScore === 'number') {
return <Tag color="blue">可用积分 {availableScore}</Tag>;
// 一键查询:积分 + 宝典开通 + 角色,一处看全(明细在任务 message 里)
if (record.task_type === 'query_all') {
const tags: Array<{ text: string; color: string }> = [];
if (typeof value?.points === 'number') tags.push({ text: `积分 ${value.points}`, color: 'blue' });
if (typeof value?.elite_opened === 'boolean') {
tags.push({ text: value.elite_opened ? '已开通宝典' : '未开通宝典', color: value.elite_opened ? 'green' : 'default' });
}
if (typeof value?.role_name === 'string' && value.role_name) tags.push({ text: `角色 ${value.role_name}`, color: 'cyan' });
if (tags.length) {
return <Space size={6} wrap>{tags.map((tag) => <Tag key={tag.text} color={tag.color}>{tag.text}</Tag>)}</Space>;
}
}
// 积分结果:新版走积分中心(points),旧任务记录里是活动接口的 available_score
const points = typeof value?.points === 'number' ? value.points : value?.available_score;
if (typeof points === 'number') {
const level = value?.grow_level;
return <Tag color="blue">可用积分 {points}{typeof level === 'number' ? ` · 等级 ${level}` : ''}</Tag>;
}
return value ? <Text code style={{ fontSize: 12 }}>{JSON.stringify(value)}</Text> : <Text type="secondary">-</Text>;