fix(weibo): 修复微豆兑换接口并防止重复兑换 (v0.4.31)

抓包确认 /aj/game/exchangegoods 必须 POST + form body,并带
x-xsrf-token/Origin/_failtoast;原实现用 GET,服务端返回 400404
迷路页,接口稳定 502。

- 兑换改为 POST + form,query 与 body 同带 F/goods_id/_t
- 请求失败分类:连接超时=未提交、其他网络错误/5xx/非 JSON=结果未知、
  4xx=未提交、401 类错误码=CK 失效
- 100002 是参数校验错误(实测 GoodsID required),移出鉴权失效集合,
  真实未登录是 400002
- 新增 /aj/mall/detail 预检(价格/余额/库存/兑换按钮),fail-close
- 复核只认余额变化,取消“库存变化即成功”的假阳性;缺字段不再写 0
- 复核请求用 8s 短超时,避免打穿前端 120s
- 同一账号兑换加进程内非阻塞锁,并发请求返回 409;余额回写失败降级为
  结果未知 502
- 兑换记录状态列映射 2=已发放,其余展示原始状态码
- 版本 0.4.29 → 0.4.31
This commit is contained in:
yml
2026-12-03 11:54:49 +08:00
parent 6ad8025a86
commit 1d77ae6eff
10 changed files with 959 additions and 168 deletions
+240 -65
View File
@@ -12,6 +12,7 @@
from __future__ import annotations
import json
import math
import secrets
import time
from dataclasses import dataclass
@@ -37,7 +38,9 @@ WEIBO_DESKTOP_UA = (
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/156.0.0.0 Safari/537.36"
)
WEIBO_AUTH_ERROR_CODES = {100002, 100004, 400000, 400002}
# 实测确认:100002 是参数/校验错误(msg=参数错误,如 GoodsID required),不是登录失效;
# 真实未登录是 400002(msg=未登陆)。因此 100002 不能进入鉴权失效集合。
WEIBO_AUTH_ERROR_CODES = {100004, 400000, 400002}
class WeiboError(RuntimeError):
@@ -232,6 +235,49 @@ def normalize_weibo_image_url(value: Any) -> str:
return text
def _as_int(value: Any) -> int | None:
"""把微博返回的数字字段解析成 int;缺失或无法解析时返回 None。
兑换预检不能用 ``int(x or 0)``:缺失字段被当成 0 会掩盖接口异常,
导致“0 价格/0 余额”这类假数据通过校验。
"""
if isinstance(value, bool):
return None
if isinstance(value, int):
return value
if isinstance(value, float):
# 小数不能被截断成整数,否则 100.9 会绕过 expected_price 校验。
if math.isfinite(value) and value.is_integer():
return int(value)
return None
if not isinstance(value, str):
return None
text = value.strip()
if not text:
return None
try:
return int(text)
except ValueError:
return None
def _is_truthy_clickable(value: Any) -> bool:
"""判断 ``payment_button.clickable`` 是否表示“可点击”。
微博这个字段在不同端/版本上可能是 ``True``、``1`` 或字符串
``"1"``/``"true"``;用 ``is True`` 会把后者误判成不可兑换。
"""
if isinstance(value, bool):
return value
if isinstance(value, int):
return value == 1
if isinstance(value, str):
return value.strip().lower() in {"1", "true"}
return False
def _parse_cookie_pairs(cookie: str) -> dict[str, str]:
pairs: dict[str, str] = {}
for item in cookie.split(";"):
@@ -332,6 +378,7 @@ class WeiboClient:
params: dict[str, Any] | None = None,
data: dict[str, Any] | None = None,
json: dict[str, Any] | None = None,
timeout: float | None = None,
) -> dict[str, Any]:
response: requests.Response | None = None
try:
@@ -342,7 +389,7 @@ class WeiboClient:
params=params,
data=data,
json=json,
timeout=self.timeout,
timeout=self.timeout if timeout is None else timeout,
)
response.raise_for_status()
payload = response.json()
@@ -424,6 +471,7 @@ class WeiboClient:
data: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
base: str = WEIBO_API_BASE,
timeout: float | None = None,
) -> dict[str, Any]:
payload = self._request_json(
method,
@@ -431,6 +479,7 @@ class WeiboClient:
params=params,
data=data,
headers=headers,
timeout=timeout,
)
code = payload.get("code")
if code in WEIBO_AUTH_ERROR_CODES:
@@ -494,13 +543,16 @@ class WeiboClient:
activity=resolved_activity,
)
def list_mall(self, activity: str = "") -> dict[str, Any]:
def list_mall(
self, activity: str = "", *, timeout: float | None = None
) -> dict[str, Any]:
"""查询微豆商城商品列表。"""
payload = self._weibo_api(
"GET",
"/mall/list",
params={"F": activity, "_t": int(time.time() * 1000)},
timeout=timeout,
)
data = payload.get("data") or {}
if not isinstance(data, dict):
@@ -520,6 +572,127 @@ class WeiboClient:
normalized_goods.append(normalized)
return {**data, "list": normalized_goods}
def _xsrf_headers(self) -> dict[str, str]:
"""兑换接口需要带上 Cookie 里的 XSRF-TOKEN 作为 ``x-xsrf-token``。
不用 ``cookies.get("XSRF-TOKEN")``:Jar 同时存在 ``.weibo.com`` 与
``vipclub.e.weibo.com`` 同名 Cookie 时会抛 ``CookieConflictError``。
这里只取与目标域匹配、且 domain 最具体(最长)的那个。
缺失时不硬性拒绝,兼容历史 CK 里没有该 Cookie 的情况。
"""
host = (urlsplit(WEIBO_API_BASE).hostname or "").lower()
best_token = ""
best_domain_len = -1
for cookie in self.session.cookies:
if cookie.name != "XSRF-TOKEN":
continue
token = (cookie.value or "").strip()
if not token:
continue
domain = (cookie.domain or "").strip().lstrip(".").lower()
if not domain:
continue
if not (host == domain or host.endswith("." + domain)):
continue
if len(domain) > best_domain_len:
best_domain_len = len(domain)
best_token = token
if best_token:
return {"x-xsrf-token": best_token}
return {}
def _fetch_goods_detail(self, goods_id: int, activity: str) -> dict[str, Any]:
"""兑换前读取商品详情,用于价格、余额、库存和按钮状态预检。"""
payload = self._weibo_api(
"GET",
"/mall/detail",
params={
"F": activity,
"goods_id": goods_id,
"_t": int(time.time() * 1000),
},
headers={"_failtoast": "true"},
)
data = payload.get("data") or {}
return data if isinstance(data, dict) else {}
def _submit_exchange(self, goods_id: int, activity: str) -> dict[str, Any]:
"""提交一次兑换请求(POST + form)。
真实接口是 ``POST /aj/game/exchangegoods``,Query 与 Body 都带
``F``、``goods_id``、``_t``,并需要 ``x-xsrf-token``、``Origin``、
``Referer`` 和 ``_failtoast``。用 GET 会得到 ``400404`` 迷路页。
失败分类顺序敏感:连接超时可以安全认为未提交,其余网络错误结果未知。
"""
timestamp = int(time.time() * 1000)
params = {"F": activity, "goods_id": goods_id, "_t": timestamp}
headers = {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"Origin": "https://vipclub.e.weibo.com",
"Referer": f"https://vipclub.e.weibo.com/game/mall?F={activity}",
"_failtoast": "true",
**self._xsrf_headers(),
}
try:
response = self.session.post(
f"{WEIBO_API_BASE}/game/exchangegoods",
params=params,
data=params,
headers=headers,
timeout=self.timeout,
)
except requests.exceptions.ConnectTimeout as exc:
raise WeiboExchangeError("连接微博超时,兑换未提交,可稍后重试") from exc
except requests.RequestException as exc:
raise WeiboExchangeUncertainError(
"兑换请求已发出,但网络中断导致结果未知;请先查兑换记录,不要立即重试"
) from exc
if response.status_code >= 500:
raise WeiboExchangeUncertainError(
f"微博兑换接口返回 HTTP {response.status_code},兑换结果未知;"
"请先查兑换记录,不要立即重试"
)
if response.status_code >= 400:
raise WeiboExchangeError(
f"兑换未提交:微博兑换接口返回 HTTP {response.status_code}"
)
try:
payload = response.json()
except (requests.exceptions.JSONDecodeError, ValueError) as exc:
text = unescape(str(getattr(response, "text", "") or ""))
if "retcode=6102" in text or "/sso/login.php" in text:
raise WeiboAuthError(
"微博支付/活动域登录态已失效(retcode=6102),"
"请重新登录微博后重新导入 CK"
) from exc
raise WeiboExchangeUncertainError(
"兑换请求已发出,但微博返回非 JSON,兑换结果未知;"
"请先查兑换记录,不要立即重试"
) from exc
if not isinstance(payload, dict):
raise WeiboExchangeUncertainError(
"兑换请求已发出,但微博返回结构异常,兑换结果未知;"
"请先查兑换记录,不要立即重试"
)
code = payload.get("code")
# code 必须是 int(bool 是 int 子类,需单独排除)。缺失/类型异常说明微博
# 返回结构不可信,无法判定是否已扣微豆,只能按"结果未知"处理。
if isinstance(code, bool) or not isinstance(code, int):
raise WeiboExchangeUncertainError(
"兑换请求已发出,但微博返回结构异常,兑换结果未知;"
"请先查兑换记录,不要立即重试"
)
if code in WEIBO_AUTH_ERROR_CODES:
raise WeiboAuthError(str(payload.get("msg") or "微博 CK 已失效"))
if code != 100000:
raise WeiboExchangeError(str(payload.get("msg") or f"兑换失败 code={code}"))
return payload
def exchange_goods(
self,
goods_id: int,
@@ -527,91 +700,93 @@ class WeiboClient:
expected_price: int,
activity: str = "",
) -> WeiboExchangeResult:
"""手动兑换商品:预检后只提交一次,成功后尽力复核。"""
"""手动兑换商品:详情预检后只提交一次,成功后尽力复核。"""
before = self.list_mall(activity)
goods_list = before.get("list") or []
goods = next(
(
item
for item in goods_list
if isinstance(item, dict) and int(item.get("id") or 0) == goods_id
),
None,
)
if goods is None:
raise WeiboExchangeError("商品不存在或已下架")
price = int(goods.get("price") or 0)
balance_before = int(before.get("weidou_balance") or 0)
remain_before = (
int(goods["remain_count"])
if goods.get("remain_count") is not None
else None
)
try:
detail = self._fetch_goods_detail(goods_id, activity)
except WeiboAuthError:
raise
except WeiboError as exc:
raise WeiboExchangeError(
f"兑换前无法确认商品状态,已取消本次兑换: {exc}"
) from exc
raw_goods_info = detail.get("goods_info")
goods_info = raw_goods_info if isinstance(raw_goods_info, dict) else {}
raw_button = detail.get("payment_button")
payment_button = raw_button if isinstance(raw_button, dict) else {}
price = _as_int(goods_info.get("price"))
balance_before = _as_int(detail.get("weidou_balance"))
remain_before = _as_int(goods_info.get("remain_count"))
if price is None or balance_before is None or remain_before is None:
raise WeiboExchangeError("微博未返回商品价格/微豆余额/库存,已取消兑换")
if not payment_button:
raise WeiboExchangeError(
"微博未返回兑换按钮状态,已取消兑换(接口结构可能变化)"
)
if str(payment_button.get("type")).strip() != "exchange":
raise WeiboExchangeError(
"微博未返回可用的兑换按钮类型,已取消兑换(接口结构可能变化)"
)
if not _is_truthy_clickable(payment_button.get("clickable")):
button_text = str(payment_button.get("text") or "").strip()
if button_text and button_text != "立即兑换":
raise WeiboExchangeError(button_text)
raise WeiboExchangeError(
"微博当前不允许兑换该商品(可能已达单人/单日上限或库存不足)"
)
if expected_price > 0 and price != expected_price:
raise WeiboExchangeError(
f"商品价格已变化:页面 {expected_price},当前 {price}"
)
if goods.get("is_sold_out") or remain_before == 0:
if remain_before == 0:
raise WeiboExchangeError("商品库存不足")
if balance_before < price:
raise WeiboExchangeError(
f"微豆余额不足:当前 {balance_before},需要 {price}"
)
try:
payload = self._weibo_api(
"GET",
"/game/exchangegoods",
params={
"F": activity,
"goods_id": goods_id,
"_t": int(time.time() * 1000),
},
headers={
"User-Agent": WEIBO_DESKTOP_UA,
"Referer": f"https://vipclub.e.weibo.com/game/mall?F={activity}",
},
)
except WeiboTransportError as exc:
raise WeiboExchangeUncertainError(
"兑换请求已发出,但网络中断导致结果未知;请先查兑换记录,不要立即重试"
) from exc
if payload.get("code") != 100000:
raise WeiboExchangeError(
str(payload.get("msg") or f"兑换失败 code={payload.get('code')}")
)
self._submit_exchange(goods_id, activity)
balance_after: int | None = None
remain_after: int | None = None
verified = False
verify_error = ""
try:
after = self.list_mall(activity)
balance_after = int(after.get("weidou_balance") or 0)
refreshed = next(
(
item
for item in (after.get("list") or [])
if isinstance(item, dict) and int(item.get("id") or 0) == goods_id
),
None,
)
if refreshed and refreshed.get("remain_count") is not None:
remain_after = int(refreshed["remain_count"])
verified = balance_after != balance_before or (
remain_after is not None
and remain_before is not None
and remain_after != remain_before
)
# 余额入账可能有延迟:最多复核 3 次,仅在余额未变化时重试。
for attempt in range(3):
after = self.list_mall(activity, timeout=min(self.timeout, 8.0))
after_balance = _as_int(after.get("weidou_balance"))
refreshed = next(
(
item
for item in (after.get("list") or [])
if isinstance(item, dict)
and _as_int(item.get("id")) == goods_id
),
None,
)
remain_after = (
_as_int(refreshed.get("remain_count"))
if isinstance(refreshed, dict)
else None
)
if after_balance is not None and after_balance != balance_before:
balance_after = after_balance
break
if attempt < 2:
time.sleep(0.4)
verified = balance_after is not None and balance_after != balance_before
if not verified:
verify_error = "兑换成功,但余额和库存暂未变化,请查兑换记录复核"
# 库存变化只作附带信息,不能单独证明兑换成功。
verify_error = "兑换已提交,但微豆余额暂未变化,请查兑换记录复核"
except (WeiboError, ValueError, TypeError) as exc:
verify_error = f"兑换已提交,但复核失败: {exc}"
return WeiboExchangeResult(
goods_id=goods_id,
goods_name=str(goods.get("goods_name") or ""),
goods_name=str(goods_info.get("goods_name") or ""),
price=price,
balance_before=balance_before,
balance_after=balance_after,