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
+145 -2
View File
@@ -13,7 +13,9 @@ from core.weibo import (
WeiboAuthError,
WeiboBindError,
WeiboBindQrCode,
WeiboExchangeError,
WeiboExchangeResult,
WeiboExchangeUncertainError,
WeiboHomeSnapshot,
WeiboPaymentStatus,
WeiboRechargeError,
@@ -90,11 +92,28 @@ class StubWeiboClient:
)
scheme_errors: ClassVar[dict[str, str]] = {}
payment_error: ClassVar[WeiboRechargeError | None] = None
exchange_error: ClassVar[Exception | None] = None
calls: ClassVar[list[tuple[str, str]]] = []
def __init__(self, cookie: str = "", **_kwargs):
self.cookie = cookie
def exchange_goods(self, goods_id, *, expected_price, activity=""):
_ = activity
self.calls.append(("exchange", f"{goods_id}"))
if self.exchange_error is not None:
raise self.exchange_error
return WeiboExchangeResult(
goods_id=goods_id,
goods_name="会员1天卡",
price=expected_price,
balance_before=200,
balance_after=50,
remain_before=10,
remain_after=9,
verified=True,
)
def fetch_home(self, activity: str = ""):
self.calls.append(("home", activity))
if "expired" in self.cookie:
@@ -144,6 +163,7 @@ def stub_client(monkeypatch):
StubWeiboClient.calls = []
StubWeiboClient.scheme_errors = {}
StubWeiboClient.payment_error = None
StubWeiboClient.exchange_error = None
StubWeiboClient.snapshot = WeiboHomeSnapshot(
uid="4014000001",
nickname="测试微博",
@@ -1714,7 +1734,7 @@ def test_manual_exchange_requires_confirm_and_serializes_result(
goods_name="微博会员1天卡",
price=100,
balance_before=200,
balance_after=100,
balance_after=50,
remain_before=10,
remain_after=9,
verified=True,
@@ -1738,5 +1758,128 @@ def test_manual_exchange_requires_confirm_and_serializes_result(
).model_dump()
assert result["goods_id"] == 37
assert result["balance_after"] == 100
assert result["balance_after"] == 50
assert result["verified"] is True
def _exchange_account(db, current_user):
account_out = import_cookies(
WeiboCookieImport(text="SCF=a; SUB=b", tag=""),
db=db,
current=current_user,
).accounts[0]
return db.query(WeiboAccount).filter(WeiboAccount.id == account_out.id).one()
def test_exchange_service_rejects_concurrent_same_account(db, current_user):
account = _exchange_account(db, current_user)
with weibo_service.account_exchange_lock(account.id):
with pytest.raises(WeiboExchangeError) as exc_info:
weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
assert "正在兑换中" in str(exc_info.value)
assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == []
def test_exchange_service_releases_lock_after_success(db, current_user):
account = _exchange_account(db, current_user)
first = weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
second = weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
assert first.goods_id == second.goods_id == 37
assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == [
("exchange", "37"),
("exchange", "37"),
]
db.refresh(account)
assert account.weidou_balance == 50
assert account.id not in weibo_service._EXCHANGE_LOCKS
def test_exchange_service_releases_lock_after_failure(db, current_user):
account = _exchange_account(db, current_user)
StubWeiboClient.exchange_error = WeiboAuthError("未登陆")
with pytest.raises(WeiboAuthError, match="未登陆"):
weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
assert account.ck_check_status == "invalid"
assert account.id not in weibo_service._EXCHANGE_LOCKS
StubWeiboClient.exchange_error = None
result = weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
assert result.goods_id == 37
assert [call for call in StubWeiboClient.calls if call[0] == "exchange"] == [
("exchange", "37"),
("exchange", "37"),
]
def test_exchange_balance_writeback_commit_failure_is_uncertain(
monkeypatch, db, current_user
):
"""回写提交失败要降级成“结果未知”,不能变 500,且锁必须释放。"""
account = _exchange_account(db, current_user)
def boom() -> None:
raise RuntimeError("commit boom")
monkeypatch.setattr(db, "commit", boom)
with pytest.raises(WeiboExchangeUncertainError) as exc_info:
weibo_service.exchange_weibo_goods(
db,
account,
goods_id=37,
expected_price=100,
)
assert "余额回写失败" in str(exc_info.value)
assert account.id not in weibo_service._EXCHANGE_LOCKS
def test_exchange_route_returns_409_when_account_busy(db, current_user):
account = _exchange_account(db, current_user)
with (
weibo_service.account_exchange_lock(account.id),
pytest.raises(HTTPException) as exc_info,
):
weibo_router.exchange_goods(
account.id,
WeiboExchangeRequest(goods_id=37, expected_price=100, confirm=True),
db=db,
current=current_user,
)
assert exc_info.value.status_code == 409
assert "正在兑换中" in str(exc_info.value.detail)