Compare commits
6
Commits
0b9a01ab3f
...
99e8643d83
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
99e8643d83 | ||
|
|
9a0d59825c | ||
|
|
86ca2ed021 | ||
|
|
c89df9ae5b | ||
|
|
82294aba80 | ||
|
|
bf1e2e9361 |
@@ -1,6 +1,6 @@
|
||||
# 直播账号运营后台
|
||||
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.3.0)。
|
||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.0)。
|
||||
|
||||
## 能做什么
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[project]
|
||||
name = "live-hub-py"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
description = "直播账号运营 Web 后台"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12,<3.13"
|
||||
|
||||
@@ -16,7 +16,7 @@ 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_pay_link import PayTargets, pay_qr_path
|
||||
from web.backend.services.huya_runner import HuyaBatchRunner
|
||||
|
||||
UID = 1199668595203
|
||||
@@ -382,11 +382,12 @@ def test_create_recharge_order_confirms_elite_open_after_payment(db, monkeypatch
|
||||
"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"
|
||||
"web.backend.services.huya_runner_recharge.resolve_pay_targets",
|
||||
lambda _pay_url, **_kwargs: PayTargets(
|
||||
cashier_url="https://excashier.alipay.com/standard/auth.htm?payOrderId=x.25",
|
||||
qr_code="https://qr.alipay.com/upx03110ghym9vm37sx7255c",
|
||||
),
|
||||
)
|
||||
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
|
||||
@@ -410,7 +411,9 @@ def test_create_recharge_order_confirms_elite_open_after_payment(db, monkeypatch
|
||||
assert result["post_payment_points"] == 280
|
||||
# 二维码内容给前端两条短地址(原始支付地址 1626 字符,扫码扫不动)
|
||||
assert result["pay_qr_path"] == pay_qr_path(587)
|
||||
# 优先用支付宝收银台直达地址(公网域名,localhost 下客户也扫得开)
|
||||
# 优先用收银台页面里的扫码内容(支付宝 App 扫码即付款)
|
||||
assert result["pay_qr_code"] == "https://qr.alipay.com/upx03110ghym9vm37sx7255c"
|
||||
# 收银台直达地址作为兜底保留(PC 打开就是这个页面)
|
||||
assert result["pay_cashier_url"].startswith("https://excashier.alipay.com/")
|
||||
assert account.elite_opened is True
|
||||
assert account.elite_expire_time == 1798732799
|
||||
@@ -418,6 +421,100 @@ def test_create_recharge_order_confirms_elite_open_after_payment(db, monkeypatch
|
||||
assert account.status == "recharge_paid"
|
||||
|
||||
|
||||
def test_create_recharge_order_uses_requested_count(db, monkeypatch):
|
||||
"""开通数量:payload.count 按份数下单(前端「数量」输入框),结果与文案都带 xN。"""
|
||||
|
||||
captured: dict = {}
|
||||
outcome = SimpleNamespace(
|
||||
ok=True,
|
||||
message="",
|
||||
detail={"spu_id": "hy-5872824", "sku_id": 7756812, "name": "精英徽章"},
|
||||
sku_id=7756812,
|
||||
product_name="精英徽章",
|
||||
unit_price=100,
|
||||
order_raw={"order_id": 11399998},
|
||||
pay_raw={"pay_order_id": "pay-2"},
|
||||
amount=300,
|
||||
order_id=11399998,
|
||||
app_order_id="app-2",
|
||||
pay_order_id="pay-2",
|
||||
pay_url="https://example.com/pay",
|
||||
supplier_name="和平精英官方小店",
|
||||
promotion={},
|
||||
promotion_info="",
|
||||
reused_order={},
|
||||
)
|
||||
|
||||
def fake_open_flow(_client, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return outcome
|
||||
|
||||
shop_client = _StubClient(redeem=_redeem(REDEEM_OPENED_HEX))
|
||||
runner = HuyaBatchRunner(
|
||||
db=None,
|
||||
batch_id="t",
|
||||
task_type="create_recharge_order",
|
||||
payload={
|
||||
"spu_id": "hy-5872824",
|
||||
"sku_id": 7756812,
|
||||
"product_name": "精英徽章",
|
||||
"count": 3,
|
||||
},
|
||||
)
|
||||
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
|
||||
)
|
||||
# 不真等支付:这一步只验证数量有没有进下单请求
|
||||
monkeypatch.setattr(
|
||||
runner,
|
||||
"_wait_recharge_payment",
|
||||
lambda **kwargs: ("timeout", None),
|
||||
raising=False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.huya_runner_recharge.run_open_flow", fake_open_flow
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"web.backend.services.huya_runner_recharge.resolve_pay_targets",
|
||||
lambda _pay_url, **_kwargs: PayTargets(
|
||||
cashier_url="", qr_code="https://qr.alipay.com/upx03110ghym9vm37sx7255c"
|
||||
),
|
||||
)
|
||||
account = HuyaAccount(uid=str(UID), cookie=COOKIE)
|
||||
db.add(account)
|
||||
db.commit()
|
||||
|
||||
runner._execute_create_recharge_order(
|
||||
db,
|
||||
SimpleNamespace(id=588),
|
||||
account,
|
||||
{"uid": UID, "cookie": COOKIE},
|
||||
{"room_pid": "1199650619883", "pay_channel": "Zfb", "sid": "2203"},
|
||||
)
|
||||
|
||||
assert captured["count"] == 3
|
||||
_status, message, result = marks[-1]
|
||||
assert result["count"] == 3
|
||||
assert result["amount"] == 300
|
||||
assert "x3" in message
|
||||
assert account.status == "recharge_order_created"
|
||||
|
||||
|
||||
def test_query_all_combines_points_elite_and_role(monkeypatch):
|
||||
shop_client = _StubClient(
|
||||
redeem=_redeem(REDEEM_OPENED_HEX), order_pages=[[PAID_ELITE_ORDER]]
|
||||
@@ -511,9 +608,63 @@ def test_query_all_fails_when_points_center_unreachable(monkeypatch):
|
||||
None, None, account, {"uid": UID, "cookie": COOKIE}, {"bind_act_id": "9271"}
|
||||
)
|
||||
|
||||
status, message, _result = marks[-1]
|
||||
status, message, result = marks[-1]
|
||||
assert status == "failed"
|
||||
assert "积分中心接口无响应" in message
|
||||
# 两条通道都没回包:CK 失效标记跟着失败结果一起落库(前端整行标红)
|
||||
assert result["ck_expired"] is True
|
||||
assert account.status == "ck_expired"
|
||||
|
||||
|
||||
def test_query_all_flags_ck_expired_when_role_lookup_has_no_response(monkeypatch):
|
||||
"""角色接口整包没有回包 = 这个 CK 已经不认了(真机:外部导入的过期 CK 就这表现)。
|
||||
|
||||
真机日志(logs/app-2026-10-15.log,hy_297838517)里
|
||||
``webActUI.checkUserBindGameAccount`` 的响应只有 ``newdata keys: ['']``(没有 tRsp),
|
||||
``_resolve_bind_status`` 因此返回 None;积分中心走另一条通道却还能返回 200,
|
||||
所以不能凭「积分查到了」就当成功,必须打 ck_expired 让页面标红。
|
||||
"""
|
||||
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]
|
||||
# 宝典/积分查到了,任务本身不算失败(结果照样展示),但 CK 失效标记必须带上
|
||||
assert status == "success"
|
||||
assert result["ck_expired"] is True
|
||||
assert result["ck_expired_reason"] == "角色信息接口无响应"
|
||||
assert account.status == "ck_expired"
|
||||
assert "角色信息接口无响应" in message
|
||||
assert "疑似 CK 已失效" in message
|
||||
|
||||
|
||||
def test_query_all_keeps_business_error_out_of_ck_expired(monkeypatch):
|
||||
"""接口有回包、只是业务码非 200(例如活动已下线)不算 CK 失效,避免整批误标红。"""
|
||||
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: (_FakeBindStatus(status=601, msg="活动已下线"), {}),
|
||||
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 result.get("ck_expired") is None
|
||||
assert account.status == "all_queried"
|
||||
assert "活动已下线" in message
|
||||
|
||||
|
||||
def test_shop_client_falls_back_to_http_when_wss_init_fails(monkeypatch):
|
||||
|
||||
@@ -21,10 +21,13 @@ 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,
|
||||
PayTargets,
|
||||
extract_pay_qr_code,
|
||||
is_alipay_url,
|
||||
pay_qr_path,
|
||||
pay_token,
|
||||
resolve_pay_entry_url,
|
||||
resolve_pay_targets,
|
||||
verify_pay_token,
|
||||
)
|
||||
|
||||
@@ -39,6 +42,17 @@ CASHIER_URL = (
|
||||
"https://excashier.alipay.com/standard/auth.htm"
|
||||
"?payOrderId=6cb86f1d259642ac843522b85dab8a52.25"
|
||||
)
|
||||
# 收银台页面里真正的扫码内容(真机页面原样片段)
|
||||
QR_CODE_LITERAL = "https://qr.alipay.com/upx03110ghym9vm37sx7255c"
|
||||
CASHIER_HTML = (
|
||||
'<input name="timeoutUrl" type="hidden" value="" id="J_timeoutUrl"/>\n'
|
||||
f'<input name="qrCode" type="hidden" value="{QR_CODE_LITERAL}" id="J_qrCode"/>\n'
|
||||
'<input name="qrImgUrl" type="hidden" '
|
||||
'value="https://mobilecodec.alipay.com/show.htm?code=upx03110ghym9vm37sx7255c" '
|
||||
'id="J_qrImgUrl"/>\n'
|
||||
f'<input name="qrRenewalURL" type="hidden" value="{CASHIER_URL}" id="J_qrRenewalURL"/>\n'
|
||||
'<input type="hidden" name="qrcodeWidth" id="J_qrcodeWidth" value="150"/>'
|
||||
)
|
||||
|
||||
|
||||
def _create_pay_task(db, pay_url: str) -> HuyaTask:
|
||||
@@ -111,24 +125,27 @@ def test_pay_redirect_route_rejects_task_without_pay_url(db):
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
"""假的 requests 响应:只需要 ``url`` 和 ``close()``。"""
|
||||
"""假的 requests 响应:只需要 ``url`` / ``text`` / ``close()``。"""
|
||||
|
||||
def __init__(self, url: str):
|
||||
def __init__(self, url: str, text: str = ""):
|
||||
self.url = url
|
||||
self.text = text
|
||||
self.closed = False
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _patch_get(monkeypatch, *, final_url: str | None = None, error=None):
|
||||
def _patch_get(
|
||||
monkeypatch, *, final_url: str | None = None, body: str = "", 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 "")
|
||||
return _FakeResponse(final_url or "", body)
|
||||
|
||||
monkeypatch.setattr(huya_pay_link.requests, "get", fake_get)
|
||||
return calls
|
||||
@@ -167,13 +184,58 @@ def test_resolve_pay_entry_url_is_shorter_than_raw_url(monkeypatch):
|
||||
|
||||
resolved = resolve_pay_entry_url(ALIPAY_LONG_URL)
|
||||
|
||||
# 收银台直达地址约 74 字符 → 二维码模块数远低于原始地址
|
||||
# 收银台直达地址约 93 字符 → 二维码模块数远低于原始地址
|
||||
assert len(resolved) < 120
|
||||
assert len(resolved) < len(ALIPAY_LONG_URL)
|
||||
|
||||
|
||||
def test_extract_pay_qr_code_from_cashier_html():
|
||||
"""收银台页面里的 J_qrCode 才是手机该扫的内容(真机抓到的原样片段)。"""
|
||||
assert extract_pay_qr_code(CASHIER_HTML) == QR_CODE_LITERAL
|
||||
|
||||
|
||||
def test_extract_pay_qr_code_ignores_other_alipay_urls():
|
||||
"""只有 qr.alipay.com 才算扫码内容:qrImgUrl(mobilecodec)不算。"""
|
||||
html = (
|
||||
'<input name="qrImgUrl" type="hidden" '
|
||||
'value="https://mobilecodec.alipay.com/show.htm?code=upx03110ghym9vm37sx7255c" '
|
||||
'id="J_qrImgUrl"/>'
|
||||
)
|
||||
|
||||
assert extract_pay_qr_code(html) == ""
|
||||
assert extract_pay_qr_code("") == ""
|
||||
|
||||
|
||||
def test_resolve_pay_targets_returns_cashier_and_qr_code(monkeypatch):
|
||||
_patch_get(monkeypatch, final_url=CASHIER_URL, body=CASHIER_HTML)
|
||||
|
||||
targets = resolve_pay_targets(ALIPAY_LONG_URL)
|
||||
|
||||
assert targets.cashier_url == CASHIER_URL
|
||||
assert targets.qr_code == QR_CODE_LITERAL
|
||||
|
||||
|
||||
def test_resolve_pay_targets_keeps_cashier_when_qr_code_missing(monkeypatch):
|
||||
"""拿不到 J_qrCode(比如停在中间页)时只回落到收银台地址。"""
|
||||
_patch_get(monkeypatch, final_url=CASHIER_URL, body="<html>no qr here</html>")
|
||||
|
||||
targets = resolve_pay_targets(ALIPAY_LONG_URL)
|
||||
|
||||
assert targets.cashier_url == CASHIER_URL
|
||||
assert targets.qr_code == ""
|
||||
|
||||
|
||||
def test_resolve_pay_targets_empty_on_error(monkeypatch):
|
||||
_patch_get(monkeypatch, error=RuntimeError("boom"))
|
||||
|
||||
targets = resolve_pay_targets(ALIPAY_LONG_URL)
|
||||
|
||||
assert targets == PayTargets()
|
||||
|
||||
|
||||
def test_is_alipay_url_matches_only_alipay_domains():
|
||||
assert is_alipay_url(CASHIER_URL) is True
|
||||
assert is_alipay_url(QR_CODE_LITERAL) 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
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
补充:它失败只记 warning,不再让整次刷新失败。
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
from core.huya.activity_structs import GetActTaskDetailResp
|
||||
from core.huya.frame_decoder import decode_struct_bytes
|
||||
from core.huya.taf_protocol import TafInputStream, TafType
|
||||
@@ -19,14 +22,12 @@ CONFIG = {"room_pid": str(ROOM_PID)}
|
||||
|
||||
# 真机 webActUI.getActTaskDetail(act 25135) 响应字节(status=601 / msg=活动已下线)
|
||||
ACT_TASK_OFFLINE_HEX = "0a010259160fe6b4bbe58aa8e5b7b2e4b88be7babf0b"
|
||||
# 积分中心页面上的开通商品(getGoodsInfoV5 真机验证 code=200)
|
||||
# 开通商品候选:必须 getGoodsInfoV5 与 listPayChannelV5 都 200(2026-10-15 真机核对)
|
||||
BUILTIN_SPU_LITERALS = [
|
||||
"hy-8328015",
|
||||
"hy-8327356",
|
||||
"hy-5872824",
|
||||
"hy-5879346",
|
||||
"hy-5874269",
|
||||
"hy-5874270",
|
||||
"hy-8343549",
|
||||
"hy-8343551",
|
||||
]
|
||||
|
||||
|
||||
@@ -65,10 +66,18 @@ class _FakeGoodsInfo:
|
||||
|
||||
|
||||
class _StubShopClient:
|
||||
def __init__(self, task: _FakeActTaskDetail | None, goods: bool = True):
|
||||
def __init__(
|
||||
self,
|
||||
task: _FakeActTaskDetail | None,
|
||||
goods: bool = True,
|
||||
unbuyable: set[str] | None = None,
|
||||
):
|
||||
self.task = task
|
||||
self.goods = goods
|
||||
#: 这些 spu 能看不能买(真机:积分中心那批礼物 spu,listPayChannelV5 → 401)
|
||||
self.unbuyable = unbuyable or set()
|
||||
self.goods_calls: list[str] = []
|
||||
self.channel_calls: list[str] = []
|
||||
|
||||
def get_act_task_detail(self, uid: int, cookie: str, act_id: int):
|
||||
return self.task
|
||||
@@ -84,6 +93,17 @@ class _StubShopClient:
|
||||
price=3000,
|
||||
)
|
||||
|
||||
def list_pay_channels(self, **kwargs):
|
||||
spu_id = kwargs["spu_id"]
|
||||
self.channel_calls.append(spu_id)
|
||||
if spu_id in self.unbuyable:
|
||||
return SimpleNamespace(
|
||||
code=401,
|
||||
message="您的设备环境暂不支持购买该商品",
|
||||
channels=[],
|
||||
)
|
||||
return SimpleNamespace(code=200, message="", channels=["Zfb", "Weixin"])
|
||||
|
||||
|
||||
def _runner(monkeypatch, client) -> tuple[HuyaBatchRunner, list, list]:
|
||||
runner = HuyaBatchRunner(
|
||||
@@ -140,8 +160,8 @@ def test_refresh_recharge_goods_survives_offline_activity(db, monkeypatch):
|
||||
|
||||
status, message, result = marks[-1]
|
||||
assert status == "success"
|
||||
assert message == "已刷新开通商品 6 个"
|
||||
assert result["goods_count"] == 6
|
||||
assert message == f"已刷新开通商品 {len(BUILTIN_SPU_LITERALS)} 个"
|
||||
assert result["goods_count"] == len(BUILTIN_SPU_LITERALS)
|
||||
assert result["task_detail_error"] == "活动已下线"
|
||||
assert client.goods_calls == BUILTIN_SPU_LITERALS
|
||||
assert [item["spu_id"] for item in result["goods"]] == BUILTIN_SPU_LITERALS
|
||||
@@ -157,6 +177,41 @@ def test_refresh_recharge_goods_survives_offline_activity(db, monkeypatch):
|
||||
assert all(row.sku_id for row in rows)
|
||||
|
||||
|
||||
def test_refresh_recharge_goods_drops_products_that_cannot_be_bought(db, monkeypatch):
|
||||
"""能看不能买的商品(listPayChannelV5 401)不进商品列表,避免下单时才报渠道错误。
|
||||
|
||||
真机 2026-10-15:hy-5872824「精英徽章」getGoodsInfoV5=200 + ¥1,但
|
||||
listPayChannelV5=401「您的设备环境暂不支持购买该商品」;真正能买的是 hy-8343549。
|
||||
"""
|
||||
client = _StubShopClient(
|
||||
_FakeActTaskDetail(601, "活动已下线"), unbuyable={"hy-8343549"}
|
||||
)
|
||||
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 [item["spu_id"] for item in result["goods"]] == [
|
||||
spu for spu in BUILTIN_SPU_LITERALS if spu != "hy-8343549"
|
||||
]
|
||||
assert result["failed_count"] == 1
|
||||
assert result["failed"][0]["spu_id"] == "hy-8343549"
|
||||
assert result["failed"][0]["message"] == "您的设备环境暂不支持购买该商品"
|
||||
assert "失败 1 个" in message
|
||||
rows = (
|
||||
db.query(HuyaRechargeGoodsSnapshot)
|
||||
.filter(HuyaRechargeGoodsSnapshot.account_id == account.id)
|
||||
.all()
|
||||
)
|
||||
assert "hy-8343549" not in {row.spu_id for row in rows}
|
||||
|
||||
|
||||
def test_refresh_recharge_goods_still_merges_activity_candidates(db, monkeypatch):
|
||||
task = _FakeActTaskDetail(
|
||||
200,
|
||||
@@ -240,6 +295,123 @@ def test_refresh_recharge_goods_drops_stale_rows_of_other_sids(db, monkeypatch):
|
||||
assert len({row.spu_id for row in rows}) == len(rows)
|
||||
|
||||
|
||||
def test_refresh_recharge_goods_purges_dead_products_everywhere(db, monkeypatch):
|
||||
"""刷新顺手清掉别处的死商品行:别的账号遗留的旧礼物 spu + 7-04 的全局默认行。
|
||||
|
||||
真机 2026-10-15:账号 65/66 还留着修复前的礼物 spu 行,和最新一套并集后面板里
|
||||
出现 7 个选项,选到礼物 spu 下单就报「当前支付渠道不可用」。
|
||||
"""
|
||||
client = _StubShopClient(_FakeActTaskDetail(601, "活动已下线"))
|
||||
runner, marks, _logs = _runner(monkeypatch, client)
|
||||
other = HuyaAccount(uid="1199665170009", cookie="c9")
|
||||
account = HuyaAccount(uid="1199665170519", cookie="yyuid=1199665170519", tag="")
|
||||
db.add_all([other, account])
|
||||
db.commit()
|
||||
old_time = datetime(2026, 10, 15, 7, 55, 17, tzinfo=UTC)
|
||||
db.add_all(
|
||||
[
|
||||
# 别的账号遗留的礼物 spu(能看不能买)→ 必须清掉
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=other.id,
|
||||
sid=2203,
|
||||
spu_id="hy-5872824",
|
||||
sku_id="dead",
|
||||
name="精英徽章",
|
||||
updated_at=old_time,
|
||||
),
|
||||
# 别的账号里仍在候选内的商品 → 保留
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=other.id,
|
||||
sid=2203,
|
||||
spu_id="hy-8343549",
|
||||
sku_id="keep",
|
||||
name="精英徽章",
|
||||
updated_at=old_time,
|
||||
),
|
||||
# 2026-07-04 的全局默认行 → 清掉
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=None,
|
||||
sid=0,
|
||||
spu_id="hy-5879340",
|
||||
sku_id="seed",
|
||||
name="精英宝典",
|
||||
updated_at=old_time,
|
||||
),
|
||||
]
|
||||
)
|
||||
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).all()
|
||||
spus = {row.spu_id for row in rows}
|
||||
assert "hy-5872824" not in spus # 别的账号的死商品被清
|
||||
assert "hy-5879340" not in spus # 全局默认行被清
|
||||
assert "hy-8343549" in spus # 候选内的商品行保留
|
||||
assert {row.spu_id for row in rows if row.account_id == account.id} == set(
|
||||
BUILTIN_SPU_LITERALS
|
||||
)
|
||||
|
||||
|
||||
def test_list_recharge_goods_returns_only_latest_refresh_set(db):
|
||||
"""列表只认「最近一次刷新」那一套:别的账号旧刷新留下的死商品不能并集进来。"""
|
||||
from web.backend.routers.huya import list_recharge_goods
|
||||
|
||||
old_acc = HuyaAccount(uid="1199665170001", cookie="c1")
|
||||
new_acc = HuyaAccount(uid="1199665170002", cookie="c2")
|
||||
db.add_all([old_acc, new_acc])
|
||||
db.commit()
|
||||
old_time = datetime(2026, 10, 15, 7, 55, 17, tzinfo=UTC)
|
||||
new_time = datetime(2026, 10, 15, 12, 52, 0, tzinfo=UTC)
|
||||
db.add_all(
|
||||
[
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=old_acc.id,
|
||||
sid=2203,
|
||||
spu_id="hy-5872824",
|
||||
sku_id="old",
|
||||
name="精英徽章",
|
||||
updated_at=old_time,
|
||||
),
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=old_acc.id,
|
||||
sid=2203,
|
||||
spu_id="hy-5879346",
|
||||
sku_id="old",
|
||||
name="精英令",
|
||||
updated_at=old_time,
|
||||
),
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=new_acc.id,
|
||||
sid=2203,
|
||||
spu_id="hy-8343549",
|
||||
sku_id="new",
|
||||
name="精英徽章",
|
||||
updated_at=new_time,
|
||||
),
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
account_id=new_acc.id,
|
||||
sid=2203,
|
||||
spu_id="hy-8343551",
|
||||
sku_id="new",
|
||||
name="精英令",
|
||||
updated_at=new_time,
|
||||
),
|
||||
]
|
||||
)
|
||||
db.commit()
|
||||
|
||||
rows = list_recharge_goods(db=db, current=None)
|
||||
|
||||
assert sorted(row.spu_id for row in rows) == [
|
||||
"hy-8343549",
|
||||
"hy-8343551",
|
||||
]
|
||||
|
||||
|
||||
def test_list_recharge_goods_hides_global_seed_rows_and_dedupes(db):
|
||||
"""列表只返回账号级快照:隐藏全局默认行,同一 spu 只留最新一行。"""
|
||||
from web.backend.routers.huya import list_recharge_goods
|
||||
|
||||
@@ -70,12 +70,18 @@ class _Client:
|
||||
orders=None,
|
||||
auth_code: int = 200,
|
||||
auth_message: str = "",
|
||||
channel_code: int = 200,
|
||||
channel_message: str = "",
|
||||
channels=("Zfb",),
|
||||
):
|
||||
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.channel_code = channel_code
|
||||
self.channel_message = channel_message
|
||||
self.channels = list(channels)
|
||||
self.pay_order_ids: list[int] = []
|
||||
self.order_list_calls = 0
|
||||
self.create_calls = 0
|
||||
@@ -97,7 +103,9 @@ class _Client:
|
||||
return resp
|
||||
|
||||
def list_pay_channels(self, **kwargs):
|
||||
return SimpleNamespace(code=200, message="", channels=["Zfb"])
|
||||
return SimpleNamespace(
|
||||
code=self.channel_code, message=self.channel_message, channels=self.channels
|
||||
)
|
||||
|
||||
def check_hy_protocol(self, **kwargs):
|
||||
return SimpleNamespace(code=200, message="")
|
||||
@@ -245,6 +253,40 @@ def test_auth_no_response_fails_without_touching_orders():
|
||||
assert client.order_list_calls == 0
|
||||
|
||||
|
||||
def test_unbuyable_goods_surfaces_channel_message():
|
||||
"""能看不能买的商品(listPayChannelV5 401):把服务端原话透出来。
|
||||
|
||||
真机 2026-10-15:hy-5872824「精英徽章」是积分中心的礼物 spu,getGoodsInfoV5
|
||||
返回 200 + ¥1,但支付渠道接口返回 401「您的设备环境暂不支持购买该商品」。
|
||||
以前一律报「当前支付渠道不可用」,看不出是商品不能买。
|
||||
"""
|
||||
client = _Client(
|
||||
create_code=200,
|
||||
channel_code=401,
|
||||
channel_message="您的设备环境暂不支持购买该商品",
|
||||
channels=(),
|
||||
)
|
||||
|
||||
outcome = _run(client)
|
||||
|
||||
assert outcome.ok is False
|
||||
assert outcome.message == "您的设备环境暂不支持购买该商品"
|
||||
# 渠道校验没过就不该下单、更不该起支付
|
||||
assert client.create_calls == 0
|
||||
assert client.pay_order_ids == []
|
||||
|
||||
|
||||
def test_unavailable_pay_channel_lists_what_is_available():
|
||||
client = _Client(create_code=200, channels=("Weixin",))
|
||||
|
||||
outcome = _run(client) # 默认走 Zfb
|
||||
|
||||
assert outcome.ok is False
|
||||
assert "当前支付渠道不可用" in outcome.message
|
||||
assert "Weixin" in outcome.message
|
||||
assert client.create_calls == 0
|
||||
|
||||
|
||||
def test_paid_order_is_not_reused():
|
||||
client = _Client(
|
||||
create_code=703, create_message=BUY_LIMIT_MESSAGE, orders=[PAID_ELITE_ORDER]
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import pytest
|
||||
|
||||
from tests.support.db import get_test_engine, make_test_session
|
||||
from web.backend.models import HuyaAccount, HuyaWorkbench, HuyaWorkbenchAccount, User
|
||||
from web.backend.models import (
|
||||
HuyaAccount,
|
||||
HuyaTask,
|
||||
HuyaWorkbench,
|
||||
HuyaWorkbenchAccount,
|
||||
User,
|
||||
)
|
||||
from web.backend.routers.huya import (
|
||||
delete_account,
|
||||
list_huya_account_ids,
|
||||
@@ -108,6 +114,47 @@ class TestHuyaWorkbenchScope:
|
||||
)
|
||||
assert searched["account_ids"] == [no_cookie.id]
|
||||
|
||||
def test_recharge_order_tasks_created_for_every_account(self):
|
||||
"""多选账号生成支付码:每个账号一个任务(一个账号一张码,各自监听支付)。
|
||||
|
||||
商品快照类任务(refresh_*)仍然是全局的,多选也只建一个。
|
||||
"""
|
||||
other = HuyaAccount(uid="300", yyuid="300", cookie="yyuid=300; udb_uid=300")
|
||||
self.session.add(other)
|
||||
self.session.commit()
|
||||
account_ids = [self.account.id, other.id]
|
||||
|
||||
batch_id, count = create_planned_tasks(
|
||||
self.session,
|
||||
account_ids,
|
||||
"create_recharge_order",
|
||||
self.user.id,
|
||||
payload={"spu_id": "hy-8328015"},
|
||||
handbook_scope="elite",
|
||||
)
|
||||
|
||||
assert count == 2
|
||||
tasks = self.session.query(HuyaTask).filter(HuyaTask.batch_id == batch_id).all()
|
||||
assert len(tasks) == 2
|
||||
# 每个选中的账号都拿到一个码,而不是只有第一个
|
||||
assert sorted(task.account_id for task in tasks) == sorted(account_ids)
|
||||
assert {task.task_type for task in tasks} == {"create_recharge_order"}
|
||||
|
||||
snapshot_batch, snapshot_count = create_planned_tasks(
|
||||
self.session,
|
||||
account_ids,
|
||||
"refresh_recharge_goods",
|
||||
self.user.id,
|
||||
handbook_scope="elite",
|
||||
)
|
||||
assert snapshot_count == 1
|
||||
assert (
|
||||
self.session.query(HuyaTask)
|
||||
.filter(HuyaTask.batch_id == snapshot_batch)
|
||||
.count()
|
||||
== 1
|
||||
)
|
||||
|
||||
def test_account_delete_cleans_workbench_membership(self):
|
||||
self.session.add(
|
||||
HuyaWorkbenchAccount(
|
||||
|
||||
@@ -320,7 +320,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "live-hub-py"
|
||||
version = "0.3.0"
|
||||
version = "0.4.0"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "alembic" },
|
||||
|
||||
@@ -134,19 +134,29 @@ def list_recharge_goods(
|
||||
):
|
||||
"""查看已缓存的虎牙充值商品快照。
|
||||
|
||||
只返回账号级快照(account_id 非空):库里还有一批 2026-07-04 写入的全局默认行
|
||||
(account_id 为空、sid=0,含旧版精英宝典/精英令/精英徽章),它们已不是当前在售
|
||||
商品,未刷新过的账号显示空列表、点一次「刷新开通商品」即可。同一 spu_id 只保留
|
||||
最新一行,避免下拉框出现同名重复项。
|
||||
商品目录是**全局同一套**(每个账号刷出来的是同样的商品),但表里是按账号存的行,
|
||||
所以这里只返回「最近一次刷新」那一整套:
|
||||
- 账号级旧刷新留下的行(真机 2026-10-15:账号 65/66 的旧礼物 spu)会和最新一套
|
||||
并集成 7 个选项,面板里就能选到「能看不能买」的商品;
|
||||
- 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())
|
||||
.order_by(
|
||||
HuyaRechargeGoodsSnapshot.updated_at.desc(),
|
||||
HuyaRechargeGoodsSnapshot.id.desc(),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not rows:
|
||||
return []
|
||||
newest = rows[0].updated_at
|
||||
latest: dict[str, HuyaRechargeGoodsSnapshot] = {}
|
||||
for row in rows:
|
||||
if row.updated_at != newest:
|
||||
continue
|
||||
latest.setdefault(row.spu_id, row)
|
||||
return list(latest.values())
|
||||
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
"""开通支付码的**二维码内容**:让手机一定扫得动、打得开。
|
||||
"""开通支付码的**二维码内容**:让手机一定扫得动、打得开、且能直接付款。
|
||||
|
||||
问题(生产实测 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 不行)。
|
||||
1. **支付宝扫码支付码** `https://qr.alipay.com/<code>`(首选,约 40 字符):
|
||||
就是收银台页面里 `J_qrCode` 那个隐藏字段。支付宝 App 扫它直接进付款;普通
|
||||
相机/浏览器扫它是支付宝的手机页面(会拉起支付宝 App)。
|
||||
2. **收银台直达地址** `https://excashier.alipay.com/standard/auth.htm?payOrderId=...`
|
||||
(约 93 字符,见 `resolve_pay_targets`)。⚠️ 这是**PC 版**收银台页面
|
||||
(`qrcodeWidth=150`,左上角一个小二维码):真机反馈有些安卓机扫完是用浏览器
|
||||
打开的,就停在这张 PC 页上不触发付款,所以只作为拿不到 qrCode 时的兜底。
|
||||
3. **本站短链** `/api/huya/pay/<task_id>?k=<hmac>`(约 38 字符):手机打开后由
|
||||
后端 302 跳到网关地址。要求「本页域名」手机能访问到(localhost 不行)。
|
||||
扫码的是没登录的手机,所以路由只校验 HMAC 签名(用 JWT 密钥派生,不额外存库)。
|
||||
"""
|
||||
|
||||
@@ -20,6 +23,8 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import requests
|
||||
@@ -29,12 +34,26 @@ from ..security import SECRET_KEY_TYPED
|
||||
TOKEN_LENGTH = 16
|
||||
PAY_PATH_PREFIX = "/api/huya/pay"
|
||||
|
||||
#: 解析收银台直达地址时冒充浏览器(支付宝对无 UA 的请求会走风控页)。
|
||||
#: 解析收银台页面时冒充浏览器(支付宝对无 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"
|
||||
)
|
||||
|
||||
#: 收银台页面里真正的扫码内容(`<input name="qrCode" ... id="J_qrCode">`)。
|
||||
QR_CODE_HOST = "qr.alipay.com"
|
||||
_QR_CODE_RE = re.compile(r"https://qr\.alipay\.com/[A-Za-z0-9]+")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PayTargets:
|
||||
"""支付码可用的两个地址(取不到就是空串)。"""
|
||||
|
||||
#: 收银台直达地址(PC 打开就是这个页面,也是「复制链接」给电脑用的地址)
|
||||
cashier_url: str = ""
|
||||
#: 收银台页面里真正的扫码内容 https://qr.alipay.com/xxx(手机扫码用这个)
|
||||
qr_code: str = ""
|
||||
|
||||
|
||||
def pay_token(task_id: int) -> str:
|
||||
"""按任务号派生短链签名(16 位十六进制,48 bit 抗枚举)。"""
|
||||
@@ -59,25 +78,42 @@ def pay_qr_path(task_id: int) -> str:
|
||||
|
||||
|
||||
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 字符,公网可达)。
|
||||
def extract_pay_qr_code(html: str) -> str:
|
||||
"""从收银台页面里取真正的扫码内容 `https://qr.alipay.com/xxx`。
|
||||
|
||||
真机取到的页面里有(`id="J_qrCode"` 那个隐藏 input):
|
||||
|
||||
<input name="qrCode" type="hidden" value="https://qr.alipay.com/upx03110ghym9vm37sx7255c" id="J_qrCode"/>
|
||||
|
||||
取不到就返回空串(调用方回落到收银台地址 / 本站短链)。
|
||||
"""
|
||||
match = _QR_CODE_RE.search(html or "")
|
||||
if match is None:
|
||||
return ""
|
||||
code = match.group(0)
|
||||
return code if is_alipay_url(code) else ""
|
||||
|
||||
|
||||
def resolve_pay_targets(pay_url: str, *, timeout: float = 6.0) -> PayTargets:
|
||||
"""跟随支付宝网关的 302,取**收银台页面**和页面里**真正的扫码内容**。
|
||||
|
||||
真机实测(2026-10-15):`openapi.alipay.com/gateway.do?...` 会 302 到
|
||||
`unitradeprod.alipay.com/appAssign.htm?...` 再 302 到
|
||||
`https://excashier.alipay.com/standard/auth.htm?payOrderId=<id>`。
|
||||
这个地址编二维码又小又好扫,且不依赖本服务的域名能不能被手机访问。
|
||||
`https://excashier.alipay.com/standard/auth.htm?payOrderId=<id>`(约 93 字符),
|
||||
页面里再带一个 `https://qr.alipay.com/<code>`(约 40 字符)——后者才是
|
||||
「扫码支付」该放进二维码的内容(见模块头说明)。
|
||||
|
||||
解析失败、超时、或最终落到非支付宝域名都返回空串 —— 调用方回落到本站短链,
|
||||
绝不能让解析失败影响支付码本身。
|
||||
解析失败、超时、最终落到非支付宝域名,都返回空 `PayTargets`:调用方回落到
|
||||
本站短链,绝不能让解析失败影响支付码本身。
|
||||
"""
|
||||
url = str(pay_url or "").strip()
|
||||
if not url.startswith(("http://", "https://")):
|
||||
return ""
|
||||
return PayTargets()
|
||||
try:
|
||||
response = requests.get(
|
||||
url,
|
||||
@@ -87,10 +123,22 @@ def resolve_pay_entry_url(pay_url: str, *, timeout: float = 6.0) -> str:
|
||||
)
|
||||
try:
|
||||
final_url = str(getattr(response, "url", "") or "").strip()
|
||||
html = (
|
||||
str(getattr(response, "text", "") or "")
|
||||
if is_alipay_url(final_url)
|
||||
else ""
|
||||
)
|
||||
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 ""
|
||||
return PayTargets()
|
||||
if not is_alipay_url(final_url):
|
||||
return PayTargets()
|
||||
return PayTargets(cashier_url=final_url, qr_code=extract_pay_qr_code(html))
|
||||
|
||||
|
||||
def resolve_pay_entry_url(pay_url: str, *, timeout: float = 6.0) -> str:
|
||||
"""只要收银台直达地址(约 93 字符);解析不到返回空串。"""
|
||||
return resolve_pay_targets(pay_url, timeout=timeout).cashier_url
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
* 开通时间 —— ``revenueWebUI.queryUserOrderList`` 里已支付的宝典订单,取最近一次支付时间。
|
||||
* 有效期 —— 商城订单(orderDetailV5)与积分中心都**不返回**到期时间,所以留空,
|
||||
界面上「有就显示」。
|
||||
* CK 失效 —— 「一键查询」里角色走活动通道(``webActUI.checkUserBindGameAccount``),
|
||||
真机(2026-10-15,外部导入的过期 CK)表现为**整个请求没有 tRsp 回包**
|
||||
(日志里 ``响应 newdata keys: ['']``),于是 ``_resolve_bind_status`` 返回 None。
|
||||
这种情况按「CK 已失效」处理:任务 result 打 ``ck_expired`` 标记、账号状态置
|
||||
``ck_expired``,前端把该行标红提示重新登录/重新导入 Cookie。
|
||||
积分中心走另一条通道(baseinfo 里的 cookie 校验更松),过期 CK 仍可能返回 200,
|
||||
所以不能拿积分能不能查来判 CK 有效性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -335,6 +342,9 @@ class EliteMixin:
|
||||
self.payload.get("bind_act_id") or config_info.get("bind_act_id")
|
||||
)
|
||||
role_name = ""
|
||||
# 角色查不到 = 这个 CK 已经不认了(模块头里有真机依据),整行要标红提醒
|
||||
ck_expired = False
|
||||
ck_expired_reason = ""
|
||||
if not b_act_id_int:
|
||||
failures.append("未配置绑定 bActId")
|
||||
else:
|
||||
@@ -346,7 +356,9 @@ class EliteMixin:
|
||||
b_act_id_int=b_act_id_int,
|
||||
)
|
||||
if bind_status is None:
|
||||
failures.append("角色信息接口无响应")
|
||||
ck_expired = True
|
||||
ck_expired_reason = "角色信息接口无响应"
|
||||
failures.append(ck_expired_reason)
|
||||
elif bind_status.status != 200:
|
||||
failures.append(
|
||||
bind_status.msg or f"角色信息查询失败: {bind_status.status}"
|
||||
@@ -372,9 +384,14 @@ class EliteMixin:
|
||||
message_parts.append("未绑定角色")
|
||||
|
||||
account.points = points if points is not None else account.points
|
||||
account.status = "all_queried"
|
||||
# CK 失效时账号状态单独标出来(前端「状态」列据此显示红色「CK 失效」)
|
||||
account.status = "ck_expired" if ck_expired else "all_queried"
|
||||
account.updated_at = datetime.now(UTC)
|
||||
result["failures"] = failures
|
||||
if ck_expired:
|
||||
result["ck_expired"] = True
|
||||
result["ck_expired_reason"] = ck_expired_reason
|
||||
ck_hint = ";疑似 CK 已失效,请重新登录或重新导入 Cookie" if ck_expired else ""
|
||||
|
||||
fetched_anything = points is not None or role_name or opened is not None
|
||||
if not fetched_anything:
|
||||
@@ -382,7 +399,7 @@ class EliteMixin:
|
||||
worker_db,
|
||||
task,
|
||||
"failed",
|
||||
";".join(failures) or "一键查询全部失败",
|
||||
(";".join(failures) or "一键查询全部失败") + ck_hint,
|
||||
result,
|
||||
)
|
||||
return
|
||||
@@ -390,4 +407,4 @@ class EliteMixin:
|
||||
message = "|".join(message_parts) or "一键查询完成"
|
||||
if failures:
|
||||
message += f";部分失败: {';'.join(failures)}"
|
||||
self._mark_task(worker_db, task, "success", message, result)
|
||||
self._mark_task(worker_db, task, "success", message + ck_hint, result)
|
||||
|
||||
@@ -11,7 +11,7 @@ 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_pay_link import pay_qr_path, resolve_pay_targets
|
||||
from .huya_shop_flow import run_open_flow
|
||||
|
||||
HUYA_RECHARGE_ACT_ID = 25135
|
||||
@@ -20,12 +20,22 @@ HUYA_RECHARGE_ACT_ID = 25135
|
||||
HUYA_RECHARGE_APP_SCENE = SHOP_APP_SCENE
|
||||
HUYA_PAYMENT_POLL_SECONDS = 180
|
||||
HUYA_PAYMENT_POLL_INTERVAL = 3
|
||||
# 内置开通商品候选 = 积分中心页面(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积分)
|
||||
# 内置开通商品候选。**必须同时满足** getGoodsInfoV5=200(能看到)与
|
||||
# listPayChannelV5=200(能买到)——真机(2026-10-15,hy_300546644 / uid 1199667339402):
|
||||
#
|
||||
# 可购买(两个接口都 200,支付渠道 ["Zfb","Weixin"]):
|
||||
# hy-8328015 精英宝典 ¥30(sku 7756811,2026-10-13 抓包下单商品)
|
||||
# hy-8327356 精英币 ¥0.1(sku 7759407)
|
||||
# hy-8343549 精英徽章 ¥1 (sku 7750721,10.15「精英徽章两个」抓包下单商品)
|
||||
# hy-8343551 精英令 ¥10(sku 7750723)
|
||||
# 不可购买(getGoodsInfoV5 仍返回 200 + 价格,但 listPayChannelV5 返回
|
||||
# 401「您的设备环境暂不支持购买该商品」)——这是积分中心「赠送指定礼物得积分」
|
||||
# 那一排的礼物 spu,只能送礼物拿积分,不能当商品下单:
|
||||
# hy-5872824 精英徽章 ¥1、hy-5879346 精英令 ¥10、
|
||||
# hy-5874269 精英令*10 ¥100、hy-5874270 精英令*100 ¥1000
|
||||
# (这就是之前多选数量下单报「当前支付渠道不可用」的原因:面板里选的是礼物 spu。
|
||||
# 精英令*10/*100 暂未找到可购买的 spu,等抓到对应页面再补。)
|
||||
#
|
||||
# 旧版精英宝典 hy-5879340 页面上已不再使用,从候选里去掉。
|
||||
# 旧活动接口 webActUI.getActTaskDetail(act 25135) 已下线(601 活动已下线),
|
||||
# 商品来源不能再依赖它,只能作为可选补充。
|
||||
@@ -45,33 +55,19 @@ HUYA_RECHARGE_BUILTIN_PRODUCTS = [
|
||||
"sort": 1,
|
||||
},
|
||||
{
|
||||
"spu_id": "hy-5872824",
|
||||
"spu_id": "hy-8343549",
|
||||
"name": "精英徽章",
|
||||
"task_name": "购买精英徽章",
|
||||
"description": "送10积分",
|
||||
"description": "得10积分丨可兑指定返场皮肤道具",
|
||||
"sort": 2,
|
||||
},
|
||||
{
|
||||
"spu_id": "hy-5879346",
|
||||
"spu_id": "hy-8343551",
|
||||
"name": "精英令",
|
||||
"task_name": "购买精英令",
|
||||
"description": "送100积分",
|
||||
"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
|
||||
|
||||
@@ -374,6 +370,31 @@ class RechargeMixin:
|
||||
)
|
||||
continue
|
||||
|
||||
# 商品详情 200 只代表「能看到」:积分中心那批礼物 spu(hy-5872824 等)在这里
|
||||
# 也能返回价格,但 listPayChannelV5 会返回 401
|
||||
# 「您的设备环境暂不支持购买该商品」,选它下单必然失败。用支付渠道当
|
||||
# 「能买到」的闸门,只留真正可下单的商品(真机 2026-10-15)。
|
||||
channels = client.list_pay_channels(
|
||||
uid=uid,
|
||||
guid="",
|
||||
cookie=cookie,
|
||||
spu_id=spu_id,
|
||||
sku_id=0,
|
||||
)
|
||||
if channels is None:
|
||||
failed.append({"spu_id": spu_id, "message": "支付渠道接口无响应"})
|
||||
continue
|
||||
if channels.code != 200 or not getattr(channels, "channels", None):
|
||||
failed.append(
|
||||
{
|
||||
"spu_id": spu_id,
|
||||
"message": channels.message
|
||||
or f"该商品当前不可购买(支付渠道 {channels.code})",
|
||||
"detail": detail,
|
||||
}
|
||||
)
|
||||
continue
|
||||
|
||||
item = {
|
||||
**candidate,
|
||||
**detail,
|
||||
@@ -390,11 +411,24 @@ class RechargeMixin:
|
||||
}
|
||||
goods.append(item)
|
||||
|
||||
# 清掉该账号的全部旧商品行(不限 sid):否则跨 sid 的旧行会和本次结果
|
||||
# 在列表接口里叠成同一商品的重复项(如 精英宝典 x2)。
|
||||
# 商品目录是全局同一套,顺手把历史遗留的「能看不能买」行也清掉:
|
||||
# ① 本账号的全部旧商品行(不限 sid:跨 sid 的旧行会和本次结果叠成重复项);
|
||||
# ② 其它账号里已经不在候选里的 spu(真机 2026-10-15:账号 65/66 还留着修复前的
|
||||
# 礼物 spu hy-5872824 等,会和最新一套并集成 7 个选项出现在面板里);
|
||||
# ③ 2026-07-04 的全局默认行(account_id 为空,早已不是在售商品)。
|
||||
kept_spus = {item["spu_id"] for item in goods}
|
||||
worker_db.query(HuyaRechargeGoodsSnapshot).filter(
|
||||
HuyaRechargeGoodsSnapshot.account_id == account.id,
|
||||
).delete(synchronize_session=False)
|
||||
worker_db.query(HuyaRechargeGoodsSnapshot).filter(
|
||||
HuyaRechargeGoodsSnapshot.account_id.is_(None),
|
||||
).delete(synchronize_session=False)
|
||||
if kept_spus:
|
||||
worker_db.query(HuyaRechargeGoodsSnapshot).filter(
|
||||
HuyaRechargeGoodsSnapshot.account_id.is_not(None),
|
||||
HuyaRechargeGoodsSnapshot.account_id != account.id,
|
||||
HuyaRechargeGoodsSnapshot.spu_id.notin_(kept_spus),
|
||||
).delete(synchronize_session=False)
|
||||
for item in goods:
|
||||
worker_db.add(
|
||||
HuyaRechargeGoodsSnapshot(
|
||||
@@ -528,14 +562,21 @@ class RechargeMixin:
|
||||
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}] 支付二维码改用支付宝收银台直达地址")
|
||||
# 二维码内容优先级(见 huya_pay_link 模块头):
|
||||
# ① 支付宝扫码支付码 https://qr.alipay.com/xxx —— 手机扫码直接进付款;
|
||||
# ② 收银台直达地址(PC 版页面,拿不到 ① 时才用,有些安卓机扫开只看到小二维码);
|
||||
# ③ 本站短链(要求本页域名手机能访问)。
|
||||
pay_targets = resolve_pay_targets(outcome.pay_url)
|
||||
if pay_targets.qr_code:
|
||||
self._push_log("info", f"[{uid}] 支付二维码使用支付宝扫码支付码")
|
||||
elif pay_targets.cashier_url:
|
||||
self._push_log(
|
||||
"warning",
|
||||
f"[{uid}] 未取到支付宝扫码支付码,二维码回落到收银台地址(部分手机扫开不触发付款)",
|
||||
)
|
||||
else:
|
||||
self._push_log(
|
||||
"warning", f"[{uid}] 未解析到支付宝收银台直达地址,二维码回落到本站短链"
|
||||
"warning", f"[{uid}] 未解析到支付宝收银台地址,二维码回落到本站短链"
|
||||
)
|
||||
result = {
|
||||
"spu_id": spu_id,
|
||||
@@ -552,9 +593,11 @@ class RechargeMixin:
|
||||
"pay_order_id": outcome.pay_order_id,
|
||||
"pay_url": outcome.pay_url,
|
||||
# 支付地址 1600+ 字符,直接编成二维码扫不动(真机反馈);给前端两条更短的路径:
|
||||
# pay_cashier_url = 支付宝收银台直达地址(公网域名,任意手机可打开);
|
||||
# pay_qr_code = 收银台页面里的 https://qr.alipay.com/xxx(约 40 字符,扫码即付款);
|
||||
# pay_cashier_url = 收银台直达地址(PC 版页面);
|
||||
# pay_qr_path = 本站短链 /api/huya/pay/<task_id>?k=...(需本页域名手机可达)。
|
||||
"pay_cashier_url": pay_cashier_url,
|
||||
"pay_qr_code": pay_targets.qr_code,
|
||||
"pay_cashier_url": pay_targets.cashier_url,
|
||||
"pay_qr_path": pay_qr_path(task.id) if task is not None else "",
|
||||
# 复用未支付旧单时为那张单的原始信息(限购商品:旧单没付完就下不了新单)
|
||||
"reused_unpaid_order": bool(outcome.reused_order),
|
||||
|
||||
@@ -523,12 +523,10 @@ def create_planned_tasks(
|
||||
batch_id = uuid.uuid4().hex[:12]
|
||||
payload = payload or {}
|
||||
accounts = db.query(HuyaAccount).filter(HuyaAccount.id.in_(account_ids)).all()
|
||||
if (
|
||||
task_type
|
||||
in {"refresh_goods", "refresh_recharge_goods", "create_recharge_order"}
|
||||
and accounts
|
||||
):
|
||||
# 全局快照和单笔支付二维码使用一个选中的 CK 即可;兑换商品需要保留多账号批量任务。
|
||||
if task_type in {"refresh_goods", "refresh_recharge_goods"} and accounts:
|
||||
# 商品快照是全局的(不分账号),一个选中的 CK 就够了。
|
||||
# 注意:create_recharge_order 不能截断 —— 一个账号一张支付码,
|
||||
# 多选时要同时生成多个码各自监听支付(前端弹窗并排展示)。
|
||||
accounts = accounts[:1]
|
||||
for account in accounts:
|
||||
db.add(
|
||||
|
||||
@@ -168,17 +168,27 @@ def run_open_flow(
|
||||
emit(f"[{uid}] 小店:{supplier_name or '未知'}(supplierId={supplier_id})")
|
||||
|
||||
# 3) 支付渠道
|
||||
#
|
||||
# 真机 2026-10-15:积分中心那批「礼物」spu(hy-5872824 精英徽章、hy-5879346
|
||||
# 精英令…)在这里返回 401「您的设备环境暂不支持购买该商品」,而商品详情接口
|
||||
# 仍是 200 + 价格 —— 「详情拿得到」不代表「能买」。失败时把服务端原话透出来,
|
||||
# 不要再糊一句「当前支付渠道不可用」让人以为是渠道配置问题。
|
||||
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
|
||||
):
|
||||
if channels is None:
|
||||
return fail("支付渠道接口无响应", detail=detail, supplier_name=supplier_name)
|
||||
if channels.code != 200:
|
||||
return fail(
|
||||
"当前支付渠道不可用",
|
||||
channels.message or f"该商品当前不可购买(支付渠道 {channels.code})",
|
||||
detail=detail,
|
||||
supplier_name=supplier_name,
|
||||
)
|
||||
available_channels = set(getattr(channels, "channels", []) or [])
|
||||
if pay_channel not in available_channels:
|
||||
channel_text = "/".join(sorted(available_channels)) or "无"
|
||||
return fail(
|
||||
f"当前支付渠道不可用(可用:{channel_text})",
|
||||
detail=detail,
|
||||
supplier_name=supplier_name,
|
||||
)
|
||||
|
||||
@@ -22,6 +22,13 @@ const SCOPE = 'elite' as const;
|
||||
const ACT_ID = 25135;
|
||||
const DEFAULT_SID = '2203';
|
||||
const LAYOUT_KEY = 'huya_elite_layout_mode';
|
||||
// 开通/充值:记住上次选的商品与数量(浏览器本地,换台机器不影响)
|
||||
const RECHARGE_SPU_KEY = 'huya_elite_recharge_spu';
|
||||
const RECHARGE_COUNT_KEY = 'huya_elite_recharge_count';
|
||||
const ELITE_SPU_KEY = 'huya_elite_elite_spu';
|
||||
// 与后端 ELITE_HANDBOOK_SPU_IDS 对齐:精英宝典单独一块,不和其他开通商品混在一个下拉里
|
||||
const ELITE_HANDBOOK_SPU_IDS = ['hy-8328015', 'hy-5879340', 'hy-3845257', 'hy-2947756'];
|
||||
const ELITE_HANDBOOK_NAME_KEYWORD = '精英宝典';
|
||||
|
||||
const TASK_LABELS: Record<string, string> = {
|
||||
query_act_tasks: '读取宝典任务', get_bind_qr: '获取绑定二维码', query_game_name: '查询游戏角色',
|
||||
@@ -54,6 +61,37 @@ function savedInterval(): number {
|
||||
return Number.isInteger(value) && value >= 5 && value <= 60 ? value : 15;
|
||||
}
|
||||
|
||||
/** 上次选的开通商品(列表里已不存在时会自动回落到第一个)。 */
|
||||
function savedRechargeSpu(): string {
|
||||
return localStorage.getItem(RECHARGE_SPU_KEY) || '';
|
||||
}
|
||||
|
||||
/** 上次填的开通数量(后端 clamp 1~999)。 */
|
||||
function savedRechargeCount(): number {
|
||||
const value = Number(localStorage.getItem(RECHARGE_COUNT_KEY));
|
||||
return Number.isInteger(value) && value >= 1 && value <= 999 ? value : 1;
|
||||
}
|
||||
|
||||
/** 上次选的精英宝典商品(就一个时基本用不上)。 */
|
||||
function savedEliteSpu(): string {
|
||||
return localStorage.getItem(ELITE_SPU_KEY) || '';
|
||||
}
|
||||
|
||||
/** 精英宝典(含换过 SKU 的历史 spu)走单独入口,其余商品走「其他开通商品」。 */
|
||||
function isEliteHandbookGood(item: HuyaRechargeGoodsItem): boolean {
|
||||
return ELITE_HANDBOOK_SPU_IDS.includes(item.spu_id) || (item.name || '').includes(ELITE_HANDBOOK_NAME_KEYWORD);
|
||||
}
|
||||
|
||||
/** 开通商品顺序:跟虎牙页面一致的 raw_order,其次按 id。 */
|
||||
function byRechargeOrder(a: HuyaRechargeGoodsItem, b: HuyaRechargeGoodsItem): number {
|
||||
return Number(a.raw?.raw_order ?? 0) - Number(b.raw?.raw_order ?? 0) || a.id - b.id;
|
||||
}
|
||||
|
||||
/** 开通商品的下拉/展示文案:名称 / 单价 / spu。 */
|
||||
function rechargeGoodsLabel(item: HuyaRechargeGoodsItem): string {
|
||||
return `${item.name || item.spu_id} / ${item.price ? `${(item.price / 100).toFixed(2)}元` : '价格动态'} / ${item.spu_id}`;
|
||||
}
|
||||
|
||||
function resultText(task: HuyaTaskItem | undefined, key: string): string {
|
||||
const value = task?.result?.[key];
|
||||
return value == null ? '' : String(value);
|
||||
@@ -79,14 +117,17 @@ function qrDoneLabel(task: HuyaTaskItem): string | null {
|
||||
}
|
||||
|
||||
/**
|
||||
* 二维码里放**短地址**:支付宝网关地址 1600+ 字符,直接编成二维码有 140+ 个模块,
|
||||
* 手机根本扫不上(生产实测)。优先级:
|
||||
* 1. `pay_cashier_url` —— 支付宝收银台直达地址(约 74 字符、公网域名,任意手机可扫码支付);
|
||||
* 2. `pay_qr_path` —— 本站短链 `/api/huya/pay/<id>?k=<签名>`,手机打开后 302 跳到真实支付地址,
|
||||
* 但要求当前页面域名手机能访问到(localhost 不行);
|
||||
* 3. `pay_url` —— 原始网关地址,兜底。
|
||||
* 二维码里放什么(优先级,见后端 huya_pay_link 模块头):
|
||||
* 1. `pay_qr_code` —— 收银台页面里真正的扫码内容 `https://qr.alipay.com/xxx`(约 40 字符),
|
||||
* 支付宝 App 扫它直接进付款,手机相机扫它也会拉起支付宝;
|
||||
* 2. `pay_cashier_url` —— 收银台直达地址,但那是 **PC 版**页面(真机反馈:有的安卓机
|
||||
* 扫开只看到左上角一个小二维码,不触发付款),只在拿不到 ① 时兜底;
|
||||
* 3. `pay_qr_path` —— 本站短链 `/api/huya/pay/<id>?k=<签名>`,要求本页域名手机能访问(localhost 不行);
|
||||
* 4. `pay_url` —— 原始网关地址 1600+ 字符,二维码太密扫不动,最后兜底。
|
||||
*/
|
||||
function payQrValue(task: HuyaTaskItem): string {
|
||||
const qrCode = resultText(task, 'pay_qr_code');
|
||||
if (qrCode) return qrCode;
|
||||
const cashier = resultText(task, 'pay_cashier_url');
|
||||
if (cashier) return cashier;
|
||||
const path = resultText(task, 'pay_qr_path');
|
||||
@@ -98,6 +139,16 @@ function isLoopbackUrl(url: string): boolean {
|
||||
return /^https?:\/\/(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(:|\/|$)/i.test(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* CK 失效:一键查询里角色走活动通道,外部导入的 CK 过期后这个接口直接没有回包,
|
||||
* 后端会打 `result.ck_expired` 标记并把账号状态置为 `ck_expired`(见
|
||||
* backend/services/huya_runner_elite.py 模块头)。这种行必须红色提醒重新登录/重新导入,
|
||||
* 不能因为积分、宝典查到了就显示绿色「成功」。
|
||||
*/
|
||||
function ckExpired(task: HuyaTaskItem | undefined, row: HuyaAccountItem): boolean {
|
||||
return task?.result?.ck_expired === true || row.status === 'ck_expired';
|
||||
}
|
||||
|
||||
function latestTask(tasks: HuyaTaskItem[], accountId: number): HuyaTaskItem | undefined {
|
||||
return tasks.filter((task) => task.account_id === accountId).sort((a, b) => b.id - a.id)[0];
|
||||
}
|
||||
@@ -119,7 +170,11 @@ export default function HuyaElitePage() {
|
||||
const [goods, setGoods] = useState<HuyaGoodsItem[]>([]);
|
||||
const [selectedGoodsId, setSelectedGoodsId] = useState('');
|
||||
const [rechargeGoods, setRechargeGoods] = useState<HuyaRechargeGoodsItem[]>([]);
|
||||
const [selectedRechargeSpu, setSelectedRechargeSpu] = useState('');
|
||||
const [selectedRechargeSpu, setSelectedRechargeSpu] = useState(savedRechargeSpu);
|
||||
// 精英宝典单独一块:和自己的商品选择分开记
|
||||
const [selectedEliteSpu, setSelectedEliteSpu] = useState(savedEliteSpu);
|
||||
// 开通/充值数量:一个账号按这个份数下单(后端 payload.count,1~999),记住上次填的值
|
||||
const [rechargeCount, setRechargeCount] = useState(savedRechargeCount);
|
||||
const [search, setSearch] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [starting, setStarting] = useState(false);
|
||||
@@ -206,20 +261,62 @@ export default function HuyaElitePage() {
|
||||
setSelectedIds((prev) => prev.filter((id) => saved.account_ids.includes(id)));
|
||||
};
|
||||
|
||||
const startTask = async (taskType: string, accountIds: number[] = selectedIds) => {
|
||||
// 开通商品分组:精英宝典(限购主商品,单独一块)与其他商品(币/徽章/令…,带数量那一块)
|
||||
const rechargeGoodsSorted = [...rechargeGoods].sort(byRechargeOrder);
|
||||
const eliteRechargeGoods = rechargeGoodsSorted.filter(isEliteHandbookGood);
|
||||
const otherRechargeGoods = rechargeGoodsSorted.filter((item) => !isEliteHandbookGood(item));
|
||||
const selectedEliteGoods = eliteRechargeGoods.find((item) => item.spu_id === selectedEliteSpu) || eliteRechargeGoods[0];
|
||||
const rechargeEliteLimit = Math.max(1, Math.min(999, selectedEliteGoods?.buy_limit || 999));
|
||||
|
||||
// 其他开通商品的数量:上限取商品的 buy_limit(限购商品只能 1 份),
|
||||
// 下单时作为后端 payload.count(1~999,走 createOrder 的 item_count)。
|
||||
const selectedRechargeGoods = otherRechargeGoods.find((item) => item.spu_id === selectedRechargeSpu);
|
||||
const rechargeBuyLimit = Math.max(1, Math.min(999, selectedRechargeGoods?.buy_limit || 999));
|
||||
const rechargeCountValue = Math.max(1, Math.min(rechargeCount, rechargeBuyLimit));
|
||||
const rechargeAmountText = selectedRechargeGoods?.price
|
||||
? `单价 ¥${(selectedRechargeGoods.price / 100).toFixed(2)} × ${rechargeCountValue}`
|
||||
: '';
|
||||
|
||||
// 换商品:按新商品的限购把数量压回合法范围,并把这次选择写进浏览器,下次进来还是它
|
||||
const selectRechargeGoods = (spu: string) => {
|
||||
const limit = Math.max(1, Math.min(999, otherRechargeGoods.find((item) => item.spu_id === spu)?.buy_limit || 999));
|
||||
const nextCount = Math.max(1, Math.min(rechargeCount, limit));
|
||||
setSelectedRechargeSpu(spu);
|
||||
setRechargeCount(nextCount);
|
||||
localStorage.setItem(RECHARGE_SPU_KEY, spu);
|
||||
localStorage.setItem(RECHARGE_COUNT_KEY, String(nextCount));
|
||||
};
|
||||
const selectEliteGoods = (spu: string) => {
|
||||
setSelectedEliteSpu(spu);
|
||||
localStorage.setItem(ELITE_SPU_KEY, spu);
|
||||
};
|
||||
const changeRechargeCount = (value: number | null) => {
|
||||
const next = Math.max(1, Math.min(rechargeBuyLimit, Number(value) || 1));
|
||||
setRechargeCount(next);
|
||||
localStorage.setItem(RECHARGE_COUNT_KEY, String(next));
|
||||
};
|
||||
|
||||
const startTask = async (taskType: string, accountIds: number[] = selectedIds, rechargeOverride?: { spu: string; count: number }) => {
|
||||
if (!accountIds.length) { message.warning('请先勾选账号'); return; }
|
||||
if (taskType === 'exchange_goods' && !selectedGoodsId) { message.warning('请先选择兑换商品'); return; }
|
||||
if (taskType === 'create_recharge_order' && !selectedRechargeSpu) { message.warning('请先选择宝典商品'); return; }
|
||||
if (taskType === 'create_recharge_order' && !rechargeOverride && !selectedRechargeSpu) { message.warning('请先选择开通商品'); return; }
|
||||
setStarting(true);
|
||||
try {
|
||||
const payload = taskType === 'exchange_goods'
|
||||
? { sid: Number(config?.sid || DEFAULT_SID), product_id: Number(selectedGoodsId), act_id: ACT_ID }
|
||||
: taskType === 'query_act_tasks' ? { act_id: ACT_ID }
|
||||
: taskType === 'create_recharge_order' ? (() => {
|
||||
const selected = rechargeGoods.find((item) => item.spu_id === selectedRechargeSpu);
|
||||
return { spu_id: selectedRechargeSpu, sku_id: Number(selected?.sku_id || 0), product_name: selected?.name || '精英宝典' };
|
||||
// 精英宝典那块用 override 传自己的 spu(限购 1 份);其他商品用下拉选的 spu + 数量
|
||||
const spu = rechargeOverride?.spu || selectedRechargeSpu;
|
||||
const count = rechargeOverride?.count ?? rechargeCountValue;
|
||||
const selected = rechargeGoods.find((item) => item.spu_id === spu);
|
||||
return { spu_id: spu, sku_id: Number(selected?.sku_id || 0), product_name: selected?.name || '精英宝典', count };
|
||||
})() : {};
|
||||
const created = await huyaApi.createTasks({ account_ids: accountIds, task_type: taskType, handbook_scope: SCOPE, concurrency, payload });
|
||||
// 支付码要「同时弹出多个二维码」:并发必须 >= 账号数,否则排在后面的码要等前面的码付完/超时才开始生成
|
||||
const batchConcurrency = taskType === 'create_recharge_order'
|
||||
? Math.min(10, Math.max(concurrency, accountIds.length))
|
||||
: concurrency;
|
||||
const created = await huyaApi.createTasks({ account_ids: accountIds, task_type: taskType, handbook_scope: SCOPE, concurrency: batchConcurrency, payload });
|
||||
setActiveBatches((prev) => [...new Set([...prev, created.batch_id])]);
|
||||
if (taskType === 'create_recharge_order') {
|
||||
// 多选账号时每个账号一个支付码:收进同一列表,弹窗里一起展示
|
||||
@@ -232,7 +329,8 @@ export default function HuyaElitePage() {
|
||||
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' && 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(); },
|
||||
@@ -291,14 +389,24 @@ export default function HuyaElitePage() {
|
||||
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)}元` : '价格动态'} / ${item.spu_id}` })).sort((a, b) => Number(a.raw?.raw_order ?? 0) - Number(b.raw?.raw_order ?? 0) || a.id - b.id), [rechargeGoods]);
|
||||
// 默认选中列表里的第一个商品;已选商品从列表消失时同步回落到第一个
|
||||
// 精英宝典:通常只有一个商品;换过 SKU 或已下线时回落到当前的第一个(并记住回落结果)
|
||||
useEffect(() => {
|
||||
if (!filteredRechargeGoods.length) return;
|
||||
if (!filteredRechargeGoods.some((item) => item.spu_id === selectedRechargeSpu)) {
|
||||
setSelectedRechargeSpu(filteredRechargeGoods[0].spu_id);
|
||||
const list = [...rechargeGoods].sort(byRechargeOrder).filter(isEliteHandbookGood);
|
||||
if (!list.length) return;
|
||||
if (!list.some((item) => item.spu_id === selectedEliteSpu)) {
|
||||
setSelectedEliteSpu(list[0].spu_id);
|
||||
localStorage.setItem(ELITE_SPU_KEY, list[0].spu_id);
|
||||
}
|
||||
}, [filteredRechargeGoods, selectedRechargeSpu]);
|
||||
}, [rechargeGoods, selectedEliteSpu]);
|
||||
// 其他开通商品:已选商品从列表消失时回落到第一个(并记住回落结果)
|
||||
useEffect(() => {
|
||||
const list = [...rechargeGoods].sort(byRechargeOrder).filter((item) => !isEliteHandbookGood(item));
|
||||
if (!list.length) return;
|
||||
if (!list.some((item) => item.spu_id === selectedRechargeSpu)) {
|
||||
setSelectedRechargeSpu(list[0].spu_id);
|
||||
localStorage.setItem(RECHARGE_SPU_KEY, list[0].spu_id);
|
||||
}
|
||||
}, [rechargeGoods, selectedRechargeSpu]);
|
||||
const exchangeCount = tasks.filter((task) => task.task_type === 'exchange_goods').length;
|
||||
// 开通支付码:同一批次里每个账号一个码,未支付的排前面;已支付/已开通的只留一行状态
|
||||
const payTasks = useMemo(() => {
|
||||
@@ -309,6 +417,15 @@ export default function HuyaElitePage() {
|
||||
}, [tasks, payBatchIds]);
|
||||
const payPendingTasks = payTasks.filter(needsScanPay);
|
||||
const payDoneTasks = payTasks.filter((task) => !needsScanPay(task));
|
||||
// 多选账号时一次生成多个码:个别账号失败(限购、CK 失效…)要单独点名,否则少一个码看不出原因
|
||||
const payFailedTasks = useMemo(() => tasks.filter((task) => task.task_type === 'create_recharge_order'
|
||||
&& payBatchIds.includes(task.batch_id)
|
||||
&& ['failed', 'error', 'stopped'].includes(task.status)), [tasks, payBatchIds]);
|
||||
// 还在排队/生成中的码(并发不够时,后面的码要等前面的码付完或超时才轮到)
|
||||
const payQueuedCount = useMemo(() => tasks.filter((task) => task.task_type === 'create_recharge_order'
|
||||
&& payBatchIds.includes(task.batch_id)
|
||||
&& ['planned', 'pending', 'running'].includes(task.status)
|
||||
&& !resultText(task, 'pay_url')).length, [tasks, payBatchIds]);
|
||||
|
||||
const openPayTasks = (batchId?: string) => {
|
||||
if (batchId) setPayBatchIds((prev) => (prev.includes(batchId) ? prev : [...prev, batchId]));
|
||||
@@ -326,12 +443,12 @@ export default function HuyaElitePage() {
|
||||
{ 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) => { const expired = ckExpired(latestTask(tasks, row.id), row); return <Space direction="vertical" align="center" size={0} style={{ width: '100%' }}><Text ellipsis title={row.game_name || row.game_channel}>{row.game_name || <Text type={expired ? 'danger' : 'secondary'}>{expired ? '角色未查到' : '未查询'}</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: '25%', align: 'center', ellipsis: true, render: (_value, row) => { const task = latestTask(tasks, row.id); const expired = ckExpired(task, row); 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={expired ? 'danger' : '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>; } },
|
||||
{ title: '状态', width: '7%', align: 'center', render: (_value, row) => { const task = latestTask(tasks, row.id); if (ckExpired(task, row)) return <Tooltip title={`${resultText(task, 'ck_expired_reason') || '角色信息查不到'} —— 请重新登录或重新导入 Cookie`}><Tag color="error">CK 失效</Tag></Tooltip>; const status = task?.status || row.status || ''; return <Tag color={TASK_COLORS[status] || 'default'}>{TASK_STATUS_LABELS[status] || status || '待操作'}</Tag>; } },
|
||||
];
|
||||
|
||||
const operationBody = (
|
||||
@@ -340,8 +457,8 @@ export default function HuyaElitePage() {
|
||||
<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>
|
||||
<div className="huya-operation-section"><div className="huya-operation-title"><ShoppingOutlined /><span>开通商品</span></div><Select size="small" showSearch optionFilterProp="label" value={selectedRechargeSpu || undefined} onChange={setSelectedRechargeSpu} options={filteredRechargeGoods.map((item) => ({ value: item.spu_id, label: item.label }))} placeholder="先刷新开通商品" style={{ width: '100%' }} /><Button block size="small" icon={<ReloadOutlined />} onClick={() => void startTask('refresh_recharge_goods')} disabled={starting || !selectedIds.length} style={{ marginTop: 6 }}>刷新开通商品</Button></div>
|
||||
<div className="huya-operation-section"><div className="huya-operation-title"><GiftOutlined /><span>开通宝典</span></div>{eliteRechargeGoods.length > 1 ? <Select size="small" showSearch optionFilterProp="label" value={selectedEliteGoods?.spu_id} onChange={selectEliteGoods} options={eliteRechargeGoods.map((item) => ({ value: item.spu_id, label: rechargeGoodsLabel(item) }))} style={{ width: '100%' }} /> : <Text style={{ fontSize: 12 }} ellipsis>{selectedEliteGoods ? `${rechargeGoodsLabel(selectedEliteGoods)}${rechargeEliteLimit < 999 ? ` · 限购 ${rechargeEliteLimit} 份` : ''}` : '列表里还没有精英宝典,请先刷新开通商品'}</Text>}<Button block size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => { if (selectedEliteGoods) void startTask('create_recharge_order', selectedIds, { spu: selectedEliteGoods.spu_id, count: 1 }); }} disabled={starting || !selectedIds.length || !selectedEliteGoods} style={{ marginTop: 6 }}>确认开通宝典并生成支付码</Button></div>
|
||||
<div className="huya-operation-section"><div className="huya-operation-title"><ShoppingOutlined /><span>其他开通商品</span></div><Select size="small" showSearch optionFilterProp="label" value={selectedRechargeSpu || undefined} onChange={selectRechargeGoods} options={otherRechargeGoods.map((item) => ({ value: item.spu_id, label: rechargeGoodsLabel(item) }))} placeholder="先刷新开通商品" style={{ width: '100%' }} /><div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 6 }}><Text type="secondary" style={{ fontSize: 12 }}>数量</Text><InputNumber size="small" min={1} max={rechargeBuyLimit} value={rechargeCountValue} onChange={changeRechargeCount} style={{ width: 80 }} /><Text type="secondary" style={{ fontSize: 12 }}>{rechargeAmountText}{rechargeBuyLimit < 999 ? ` · 限购 ${rechargeBuyLimit} 份` : ''}</Text></div><Button block size="small" type="primary" icon={<QrcodeOutlined />} onClick={() => void startTask('create_recharge_order')} disabled={starting || !selectedIds.length || !selectedRechargeSpu} style={{ marginTop: 6 }}>{rechargeCountValue > 1 ? `确认充值并生成支付码 ×${rechargeCountValue}` : '确认充值并生成支付码'}</Button><Button block size="small" icon={<ReloadOutlined />} onClick={() => void startTask('refresh_recharge_goods')} disabled={starting || !selectedIds.length} style={{ marginTop: 6 }}>刷新开通商品</Button></div>
|
||||
<RealtimeLogPanel logs={logs.logs} connected={logs.connected} title="实时日志" emptyText="暂无任务日志" height={150} collapsible defaultVisible={false} />
|
||||
</Space>
|
||||
);
|
||||
@@ -366,35 +483,37 @@ export default function HuyaElitePage() {
|
||||
<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}
|
||||
title={payTasks.length ? `开通支付码(${payPendingTasks.length} 个待扫码 · 已完成 ${payDoneTasks.length}/${payTasks.length})` : '开通支付码'}
|
||||
width={920}
|
||||
centered
|
||||
onCancel={() => setPayOpen(false)}
|
||||
footer={<Space><Text type="secondary">支付后会自动确认开通状态;已开通的码自动收起</Text><Button onClick={() => setPayOpen(false)}>关闭</Button><Button onClick={() => { setPayBatchIds([]); setPayOpen(false); }}>清空列表</Button></Space>}
|
||||
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%' }}>
|
||||
{payQueuedCount > 0 && <div style={{ marginBottom: 10, textAlign: 'left' }}><Text type="secondary" style={{ fontSize: 12 }}>还有 {payQueuedCount} 个账号在排队生成支付码(并发不够时会等已出的码付完/超时,可调大右侧「并发」)</Text></div>}
|
||||
{payPendingTasks.length > 0 && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(230px, 1fr))', gap: 12 }}>
|
||||
{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 key={task.id} style={{ border: '1px solid rgba(128,128,128,.22)', borderRadius: 6, padding: 10, textAlign: 'center' }}>
|
||||
<div style={{ background: '#fff', padding: 6, borderRadius: 6, lineHeight: 0, display: 'inline-block' }}>{resultText(task, 'mini_qrcode_image') ? <img src={`data:image/png;base64,${resultText(task, 'mini_qrcode_image')}`} alt="支付码" style={{ width: 150, height: 150, objectFit: 'contain' }} /> : <QRCode value={qrValue} size={150} type="svg" errorLevel="L" bordered={false} color="#000" bgColor="#fff" />}</div>
|
||||
<div><Text strong ellipsis>{payTaskLabel(task)}</Text></div>
|
||||
<Text type="secondary" style={{ fontSize: 12 }}>UID {task.account_uid || '-'}</Text>
|
||||
<div><Text type="secondary" style={{ fontSize: 12 }}>{[resultText(task, 'product_name') || '精英宝典', Number(resultText(task, 'count')) > 1 ? `×${resultText(task, 'count')}` : '', resultText(task, 'amount_text')].filter(Boolean).join(' ')}</Text></div>
|
||||
<div style={{ marginTop: 4 }}><Tag color={TASK_COLORS[task.status] || 'default'}>{resultText(task, 'payment_status_label') || TASK_STATUS_LABELS[task.status] || task.status}</Tag></div>
|
||||
<Text type="secondary" style={{ fontSize: 12 }} ellipsis title={task.message}>{task.message || '-'}</Text>
|
||||
{isLoopbackUrl(qrValue) && <div><Text type="warning" style={{ fontSize: 12 }}>二维码是本机地址(localhost),手机扫不开</Text></div>}
|
||||
<div style={{ marginTop: 6 }}><Space size={6}><Button size="small" icon={<ZoomInOutlined />} onClick={() => setZoomPayTask(task)}>放大扫码</Button><Button size="small" icon={<CopyOutlined />} onClick={() => void copyPayLink(qrValue, '支付链接')}>复制链接</Button></Space></div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Space>}
|
||||
</div>}
|
||||
{payFailedTasks.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 }}>
|
||||
{payFailedTasks.map((task) => <Tag key={task.id} color="error" title={task.message}>{payTaskLabel(task)} · {task.message || '生成失败'}</Tag>)}
|
||||
</div>
|
||||
</div>}
|
||||
{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 }}>
|
||||
|
||||
@@ -94,6 +94,7 @@ const ACCOUNT_STATUS_LABELS: Record<string, string> = {
|
||||
bind_confirmed: '已绑定',
|
||||
goods_exchanged: '已兑换',
|
||||
recharge_order_created: '待支付',
|
||||
ck_expired: 'CK 失效',
|
||||
};
|
||||
|
||||
const ACCOUNT_STATUS_COLORS: Record<string, string> = {
|
||||
@@ -112,6 +113,7 @@ const ACCOUNT_STATUS_COLORS: Record<string, string> = {
|
||||
bind_confirmed: 'success',
|
||||
goods_exchanged: 'success',
|
||||
recharge_order_created: 'processing',
|
||||
ck_expired: 'error',
|
||||
};
|
||||
|
||||
const HUYA_WORKBENCH_ACCOUNT_IDS_KEY = 'huya_task_workbench_account_ids';
|
||||
|
||||
Reference in New Issue
Block a user