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 通过。
This commit is contained in:
yml2213
2026-10-15 19:28:26 +08:00
parent f61284e808
commit 0b9a01ab3f
9 changed files with 850 additions and 44 deletions
+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 ""
@@ -11,6 +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_shop_flow import run_open_flow
HUYA_RECHARGE_ACT_ID = 25135
@@ -527,6 +528,15 @@ 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}] 支付二维码改用支付宝收银台直达地址")
else:
self._push_log(
"warning", f"[{uid}] 未解析到支付宝收银台直达地址,二维码回落到本站短链"
)
result = {
"spu_id": spu_id,
"sku_id": sku_id,
@@ -541,6 +551,14 @@ class RechargeMixin:
"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,
@@ -554,6 +572,8 @@ class RechargeMixin:
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
)
+125 -35
View File
@@ -20,6 +20,16 @@ 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:
@@ -43,6 +53,61 @@ class ShopOrderOutcome:
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(
@@ -165,30 +230,6 @@ def run_open_flow(
if stopped is not None and stopped():
return fail("已停止", detail=detail, supplier_name=supplier_name)
# 7) 购买权限
auth = client.check_user_buy_auth(
uid=uid, guid="", cookie=cookie, spu_id=spu_id, sku_id=sku_id
)
if auth is None or auth.code != 200:
return fail(
getattr(auth, "message", "") or "购买权限校验失败",
detail=detail,
supplier_name=supplier_name,
promotion=promotion_dict,
)
# 8) 下单
order_resp = client.create_order(
uid=uid,
guid="",
cookie=cookie,
pid=pid,
spu_id=spu_id,
sku_id=sku_id,
item_count=count,
game_id="0",
order_type=6,
)
common = {
"detail": detail,
"supplier_name": supplier_name,
@@ -202,22 +243,69 @@ def run_open_flow(
"product_name": product_name,
"pay_channel": pay_channel,
}
if order_resp is None:
return fail("虎牙下单接口无响应", **common)
order_raw = order_resp.to_dict()
common["order_raw"] = order_raw
if order_resp.code != 200 or not order_resp.orderId:
return fail(
order_resp.message or f"虎牙下单失败: {order_resp.code}",
**common,
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_resp.orderId,
order_id=order_id,
pay_type=pay_channel,
pid=pid,
item_count=count,
@@ -235,8 +323,10 @@ def run_open_flow(
amount = int(pay_resp.amount or unit_price * count or 0)
return ShopOrderOutcome(
ok=True,
message="已生成支付二维码",
order_id=int(order_resp.orderId),
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,