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
+437 -69
View File
@@ -672,48 +672,83 @@ def test_get_payment_status():
assert session.calls[0][2]["data"]["pay_id"] == "pay-1"
def test_exchange_goods_executes_once_and_verifies_balance_and_stock():
before = {
GOODS_ID = 37
def _detail_payload(
*,
price: Any = 100,
balance: Any = 200,
remain: Any = 10,
clickable: Any = True,
button_text: str = "立即兑换",
button_type: Any = "exchange",
) -> dict:
return {
"code": 100000,
"msg": "success",
"data": {
"weidou_balance": 200,
"list": [
{
"id": 37,
"goods_name": "微博会员1天卡",
"price": 100,
"remain_count": 10,
"is_sold_out": False,
}
],
"goods_info": {
"id": GOODS_ID,
"goods_name": "微博会员1天卡",
"price": price,
"remain_count": remain,
"goods_desc": "兑换后立即生效",
},
"payment_button": {
"text": button_text,
"clickable": clickable,
"type": button_type,
},
"weidou_balance": balance,
"nickname": "测试微博",
"game_nickname": "测试角色",
},
}
after = {
"code": 100000,
"data": {
"weidou_balance": 100,
"list": [
{
"id": 37,
"goods_name": "微博会员1天卡",
"price": 100,
"remain_count": 9,
"is_sold_out": False,
}
],
},
def _mall_list_payload(
*,
balance: Any = 200,
remain: Any = 10,
drop_balance: bool = False,
) -> dict:
data: dict[str, Any] = {
"list": [
{
"id": GOODS_ID,
"goods_name": "微博会员1天卡",
"price": 100,
"remain_count": remain,
"is_sold_out": False,
}
],
}
if not drop_balance:
data["weidou_balance"] = balance
return {"code": 100000, "msg": "success", "data": data}
def _exchange_calls(session: FakeSession) -> list:
return [call for call in session.calls if call[1].endswith("/game/exchangegoods")]
def _detail_calls(session: FakeSession) -> list:
return [call for call in session.calls if call[1].endswith("/mall/detail")]
def test_exchange_goods_posts_form_with_xsrf_and_verifies_balance():
session = FakeSession(
[
before,
_detail_payload(),
{"code": 100000, "msg": "success", "data": None},
after,
_mall_list_payload(balance=100, remain=9),
]
)
client = WeiboClient("SUB=valid", session=session)
client = WeiboClient("SUB=valid; XSRF-TOKEN=xsrf-token-1", session=session)
result = client.exchange_goods(
37,
GOODS_ID,
expected_price=100,
activity="bowen_tjg",
)
@@ -724,63 +759,396 @@ def test_exchange_goods_executes_once_and_verifies_balance_and_stock():
assert result.remain_before == 10
assert result.remain_after == 9
assert result.verified is True
exchange_calls = [
call for call in session.calls if call[1].endswith("/game/exchangegoods")
]
assert result.verify_error == ""
exchange_calls = _exchange_calls(session)
assert len(exchange_calls) == 1
assert exchange_calls[0][2]["params"]["goods_id"] == 37
method, url, kwargs = exchange_calls[0]
assert method == "POST"
assert url.endswith("/game/exchangegoods")
assert kwargs["params"]["goods_id"] == GOODS_ID
assert kwargs["params"]["F"] == "bowen_tjg"
assert "_t" in kwargs["params"]
assert kwargs["data"]["goods_id"] == GOODS_ID
assert kwargs["data"]["F"] == "bowen_tjg"
headers = {key.lower(): value for key, value in kwargs["headers"].items()}
assert headers["x-xsrf-token"] == "xsrf-token-1"
assert headers["content-type"].startswith("application/x-www-form-urlencoded")
assert headers["origin"] == "https://vipclub.e.weibo.com"
assert headers["_failtoast"] == "true"
detail_calls = _detail_calls(session)
assert len(detail_calls) == 1
assert session.calls.index(detail_calls[0]) < session.calls.index(exchange_calls[0])
def test_exchange_goods_rejects_insufficient_balance_before_write():
def test_exchange_goods_cancels_when_payment_button_not_clickable():
session = FakeSession(
[
{
"code": 100000,
"data": {
"weidou_balance": 99,
"list": [
{
"id": 37,
"goods_name": "微博会员1天卡",
"price": 100,
"remain_count": 10,
"is_sold_out": False,
}
],
},
}
_detail_payload(clickable=False, button_text="已达兑换上限"),
_mall_list_payload(),
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="已达兑换上限"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert _exchange_calls(session) == []
def test_exchange_goods_cancels_when_detail_preflight_fails():
session = FakeSession([{"code": 100500, "msg": "商品不存在"}])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="已取消"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert _exchange_calls(session) == []
def test_exchange_goods_rejects_insufficient_balance_before_write():
session = FakeSession([_detail_payload(balance=99)])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="余额不足"):
client.exchange_goods(37, expected_price=100)
client.exchange_goods(GOODS_ID, expected_price=100)
assert not any(call[1].endswith("/game/exchangegoods") for call in session.calls)
assert _exchange_calls(session) == []
def test_exchange_goods_marks_transport_failure_as_uncertain():
def test_exchange_goods_marks_connection_error_as_uncertain():
session = FakeSession(
[
{
"code": 100000,
"data": {
"weidou_balance": 200,
"list": [
{
"id": 37,
"goods_name": "微博会员1天卡",
"price": 100,
"remain_count": 10,
"is_sold_out": False,
}
],
},
},
_detail_payload(),
requests.ConnectionError("connection reset"),
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeUncertainError, match="结果未知"):
client.exchange_goods(37, expected_price=100)
client.exchange_goods(GOODS_ID, expected_price=100)
def test_exchange_goods_treats_100002_as_explicit_rejection():
session = FakeSession(
[
_detail_payload(),
{"code": 100002, "msg": "参数错误"},
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="参数错误") as exc_info:
client.exchange_goods(GOODS_ID, expected_price=100)
assert not isinstance(exc_info.value, WeiboAuthError)
def test_exchange_goods_treats_400002_as_auth_failure():
session = FakeSession(
[
_detail_payload(),
{"code": 400002, "msg": "未登陆"},
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboAuthError, match="未登陆"):
client.exchange_goods(GOODS_ID, expected_price=100)
def test_exchange_goods_does_not_verify_on_stock_change_only():
session = FakeSession(
[
_detail_payload(),
{"code": 100000, "msg": "success", "data": None},
_mall_list_payload(balance=200, remain=9),
_mall_list_payload(balance=200, remain=8),
_mall_list_payload(balance=200, remain=7),
]
)
client = WeiboClient("SUB=valid", session=session)
result = client.exchange_goods(GOODS_ID, expected_price=100)
assert result.verified is False
assert result.verify_error
assert result.balance_after is None
assert result.remain_after == 7
def test_exchange_goods_keeps_balance_after_none_when_balance_missing():
session = FakeSession(
[
_detail_payload(),
{"code": 100000, "msg": "success", "data": None},
_mall_list_payload(drop_balance=True),
_mall_list_payload(drop_balance=True),
_mall_list_payload(drop_balance=True),
]
)
client = WeiboClient("SUB=valid", session=session)
result = client.exchange_goods(GOODS_ID, expected_price=100)
assert result.balance_after is None
assert result.verified is False
assert result.verify_error
def test_exchange_goods_marks_connect_timeout_as_not_submitted():
session = FakeSession(
[
_detail_payload(),
requests.exceptions.ConnectTimeout("connect timeout"),
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="未提交") as exc_info:
client.exchange_goods(GOODS_ID, expected_price=100)
assert not isinstance(exc_info.value, WeiboExchangeUncertainError)
def test_exchange_goods_passes_auth_error_through_on_detail_preflight():
session = FakeSession([{"code": 400002, "msg": "未登陆"}])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboAuthError, match="未登陆") as exc_info:
client.exchange_goods(GOODS_ID, expected_price=100)
assert not isinstance(exc_info.value, WeiboExchangeError)
def test_exchange_goods_treats_403_as_rejected_without_verify():
session = FakeSession(
[
_detail_payload(),
FakeResponse({"code": 1}, status_code=403),
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="403"):
client.exchange_goods(GOODS_ID, expected_price=100)
# 只应发生 detail + 提交两次请求,403 之后不再复核。
assert len(session.calls) == 2
assert len(_detail_calls(session)) == 1
assert len(_exchange_calls(session)) == 1
def test_exchange_goods_treats_500_as_uncertain():
session = FakeSession(
[
_detail_payload(),
FakeResponse({"code": 1}, status_code=500),
]
)
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeUncertainError, match="结果未知"):
client.exchange_goods(GOODS_ID, expected_price=100)
@pytest.mark.parametrize("clickable", [1, "1", "true", "True", True])
def test_exchange_goods_accepts_truthy_clickable(clickable):
session = FakeSession(
[
_detail_payload(clickable=clickable),
{"code": 100000, "msg": "success", "data": None},
_mall_list_payload(balance=100, remain=9),
]
)
client = WeiboClient("SUB=valid", session=session)
result = client.exchange_goods(GOODS_ID, expected_price=100)
assert result.verified is True
assert len(_exchange_calls(session)) == 1
@pytest.mark.parametrize("clickable", ["0", 0, False, None])
def test_exchange_goods_rejects_falsy_clickable(clickable):
session = FakeSession([_detail_payload(clickable=clickable)])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="不允许兑换"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert _exchange_calls(session) == []
def test_exchange_goods_cancels_when_payment_button_missing():
payload = _detail_payload()
del payload["data"]["payment_button"]
session = FakeSession([payload])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="未返回兑换按钮状态"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert _exchange_calls(session) == []
def test_exchange_goods_verify_uses_shorter_timeout():
session = FakeSession(
[
_detail_payload(),
{"code": 100000, "msg": "success", "data": None},
_mall_list_payload(balance=100, remain=9),
]
)
client = WeiboClient("SUB=valid", session=session)
client.exchange_goods(GOODS_ID, expected_price=100)
mall_calls = [call for call in session.calls if call[1].endswith("/mall/list")]
assert mall_calls
for _method, _url, kwargs in mall_calls:
assert kwargs["timeout"] == 8.0
for _method, _url, kwargs in _detail_calls(session) + _exchange_calls(session):
assert kwargs["timeout"] == client.timeout
@pytest.mark.parametrize(
"payload",
[
{},
{"msg": "success"},
{"code": None},
{"code": ["100000"]},
{"code": {"value": 100000}},
{"code": "100000"},
{"code": True},
{"code": False},
],
ids=[
"empty",
"missing-code",
"none-code",
"list-code",
"dict-code",
"str-code",
"true-code",
"false-code",
],
)
def test_submit_exchange_treats_missing_or_bad_code_as_uncertain(payload):
session = FakeSession([_detail_payload(), payload])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeUncertainError, match="结果未知"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert len(_exchange_calls(session)) == 1
def test_exchange_goods_cancels_when_remain_count_missing():
payload = _detail_payload()
del payload["data"]["goods_info"]["remain_count"]
session = FakeSession([payload])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="已取消兑换") as exc_info:
client.exchange_goods(GOODS_ID, expected_price=100)
assert not isinstance(exc_info.value, WeiboExchangeUncertainError)
assert _exchange_calls(session) == []
@pytest.mark.parametrize(
"button_type",
["recharge", None, "", "exchangegoods"],
ids=["recharge", "missing", "empty", "other"],
)
def test_exchange_goods_cancels_when_payment_button_type_unusable(button_type):
payload = _detail_payload(button_type=button_type)
if button_type is None:
del payload["data"]["payment_button"]["type"]
session = FakeSession([payload])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="兑换按钮类型") as exc_info:
client.exchange_goods(GOODS_ID, expected_price=100)
assert not isinstance(exc_info.value, WeiboExchangeUncertainError)
assert _exchange_calls(session) == []
def test_exchange_goods_accepts_payment_button_type_with_padding():
session = FakeSession(
[
_detail_payload(button_type=" exchange "),
{"code": 100000, "msg": "success", "data": None},
_mall_list_payload(balance=100, remain=9),
]
)
client = WeiboClient("SUB=valid", session=session)
result = client.exchange_goods(GOODS_ID, expected_price=100)
assert result.verified is True
assert len(_exchange_calls(session)) == 1
def test_exchange_goods_cancels_when_price_is_fractional():
session = FakeSession([_detail_payload(price=100.9)])
client = WeiboClient("SUB=valid", session=session)
with pytest.raises(WeiboExchangeError, match="已取消兑换"):
client.exchange_goods(GOODS_ID, expected_price=100)
assert _exchange_calls(session) == []
@pytest.mark.parametrize(
("value", "expected"),
[
(100.9, None),
(float("inf"), None),
(float("nan"), None),
(100.0, 100),
(100, 100),
(True, None),
("100", 100),
(" 100 ", 100),
("100.5", None),
("100.0", None),
("", None),
(None, None),
([100], None),
],
)
def test_as_int_rejects_fractional_and_exotic_values(value, expected):
from core.weibo.client import _as_int
assert _as_int(value) == expected
def test_xsrf_headers_prefers_most_specific_domain_cookie():
session = FakeSession([])
session.cookies.set("XSRF-TOKEN", "wide-domain", domain=".weibo.com")
session.cookies.set("XSRF-TOKEN", "narrow-domain", domain="vipclub.e.weibo.com")
session.cookies.set("XSRF-TOKEN", "other-domain", domain=".example.com")
client = WeiboClient("SUB=valid", session=session)
assert client._xsrf_headers() == {"x-xsrf-token": "narrow-domain"}
def test_xsrf_headers_accepts_parent_domain_cookie_only():
session = FakeSession([])
session.cookies.set("XSRF-TOKEN", "wide-domain", domain=".weibo.com")
session.cookies.set("XSRF-TOKEN", "other-domain", domain=".example.com")
client = WeiboClient("SUB=valid", session=session)
assert client._xsrf_headers() == {"x-xsrf-token": "wide-domain"}
def test_xsrf_headers_returns_empty_when_cookie_missing():
session = FakeSession([])
client = WeiboClient("SUB=valid", session=session)
assert client._xsrf_headers() == {}