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
+9 -1
View File
@@ -11,7 +11,12 @@ from sqlalchemy import func, or_
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, defer, joinedload
from core.weibo import WeiboAuthError, WeiboError, WeiboExchangeUncertainError
from core.weibo import (
WeiboAuthError,
WeiboError,
WeiboExchangeError,
WeiboExchangeUncertainError,
)
from ..database import get_db
from ..deps import get_current_user
@@ -1460,6 +1465,9 @@ def exchange_goods(
)
except WeiboExchangeUncertainError as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
except WeiboExchangeError as exc:
# 服务端明确拒绝或本地预检失败:兑换未提交,按 409 返回可直接展示的文案。
raise HTTPException(status_code=409, detail=str(exc)) from exc
except (WeiboError, ValueError) as exc:
raise _manual_http_error(exc) from exc
_record_audit_safely(
+48 -9
View File
@@ -2,6 +2,8 @@
from __future__ import annotations
import threading
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import UTC, datetime
@@ -12,7 +14,9 @@ from core.weibo import (
WeiboAuthError,
WeiboClient,
WeiboError,
WeiboExchangeError,
WeiboExchangeResult,
WeiboExchangeUncertainError,
WeiboHomeSnapshot,
WeiboPaymentStatus,
WeiboRechargeOrder,
@@ -22,6 +26,31 @@ from core.weibo import (
from ..models import User, WeiboAccount, WeiboRechargeRecord, WeiboWorkbenchAccount
from .weibo_image_service import embed_weibo_goods_images
_EXCHANGE_LOCKS: dict[int, threading.Lock] = {}
_EXCHANGE_LOCKS_GUARD = threading.Lock()
@contextmanager
def account_exchange_lock(account_id: int):
"""按账号的非阻塞兑换锁,防同一账号双击/并发导致重复扣微豆。
锁只在本进程内有效(生产 uvicorn 为单 worker),多进程/多实例部署时
不做跨进程保证;拿不到锁时立即报错,不排队等待。
"""
with _EXCHANGE_LOCKS_GUARD:
lock = _EXCHANGE_LOCKS.setdefault(account_id, threading.Lock())
acquired = lock.acquire(blocking=False)
if not acquired:
raise WeiboExchangeError("该账号正在兑换中,请等待当前兑换结束后再试")
try:
yield
finally:
with _EXCHANGE_LOCKS_GUARD:
lock.release()
if _EXCHANGE_LOCKS.get(account_id) is lock:
_EXCHANGE_LOCKS.pop(account_id, None)
@dataclass(frozen=True, slots=True)
class WeiboImportIssue:
@@ -470,20 +499,30 @@ def exchange_weibo_goods(
expected_price: int,
activity: str = "",
) -> WeiboExchangeResult:
"""预检并执行一次微博微豆兑换,然后刷新账号余额。"""
"""预检并执行一次微博微豆兑换,然后刷新账号余额。
同一账号的并发兑换请求会被拒绝(进程内按账号加锁)。
"""
try:
result = WeiboClient(account.cookie or "").exchange_goods(
goods_id,
expected_price=expected_price,
activity=_effective_activity(account, activity),
)
with account_exchange_lock(account.id):
result = WeiboClient(account.cookie or "").exchange_goods(
goods_id,
expected_price=expected_price,
activity=_effective_activity(account, activity),
)
if result.balance_after is not None:
account.weidou_balance = result.balance_after
try:
db.commit()
except Exception as exc: # 余额回写失败不能掩盖“兑换已提交”
db.rollback()
raise WeiboExchangeUncertainError(
"兑换已提交,但余额回写失败,请查兑换记录复核"
) from exc
except (WeiboError, ValueError) as exc:
_mark_manual_failure(db, account, exc)
raise
if result.balance_after is not None:
account.weidou_balance = result.balance_after
db.commit()
return result