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:
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -95,6 +95,21 @@ const WEIBO_BATCH_RECHARGE_POLL_INTERVAL_MS = 8_000;
|
||||
const WEIBO_BATCH_EXCHANGE_MAX = 50;
|
||||
const WEIBO_BATCH_EXCHANGE_CONCURRENCY = 3;
|
||||
|
||||
// 微博官方页面不展示该字段,2 是抓包实测的成功发放值,其余值语义未确认,因此保留原始状态码。
|
||||
const REWARD_STATUS_LABELS: Record<number, string> = { 2: '已发放' };
|
||||
|
||||
const renderRewardStatus = (value: number | null | undefined) => {
|
||||
if (value == null) return '-';
|
||||
const label = REWARD_STATUS_LABELS[value];
|
||||
if (label)
|
||||
return (
|
||||
<Tag color="success" title={`微博状态码 ${value}`}>
|
||||
{label}
|
||||
</Tag>
|
||||
);
|
||||
return <Tag title={`微博状态码 ${value}`}>状态码 {value}</Tag>;
|
||||
};
|
||||
|
||||
function normalizeImageURL(value: string): string {
|
||||
const imageURL = value.trim();
|
||||
if (!imageURL || imageURL.startsWith('data:image/')) return imageURL;
|
||||
@@ -299,6 +314,7 @@ export default function WeiboAccountsPage({
|
||||
const [batchRechargeZoom, setBatchRechargeZoom] =
|
||||
useState<BatchRechargeEntry | null>(null);
|
||||
const batchRechargeEntriesRef = useRef<BatchRechargeEntry[]>([]);
|
||||
const exchangeInFlightRef = useRef(false);
|
||||
const batchRechargePollingRef = useRef(false);
|
||||
const batchRechargeCheckRef = useRef<
|
||||
(entry: BatchRechargeEntry) => Promise<void>
|
||||
@@ -923,11 +939,16 @@ export default function WeiboAccountsPage({
|
||||
|
||||
const handleExchange = async (goods: WeiboMallListResult['goods'][number]) => {
|
||||
if (!featureAccount) return;
|
||||
if (exchangeInFlightRef.current) {
|
||||
message.info('已有兑换进行中,请稍候');
|
||||
return;
|
||||
}
|
||||
if (!featureAccount.is_enabled) {
|
||||
message.warning('账号已停用,请先启用');
|
||||
return;
|
||||
}
|
||||
setExchangingGoodsId(goods.id);
|
||||
exchangeInFlightRef.current = true;
|
||||
try {
|
||||
const result = await weiboApi.exchangeGoods(
|
||||
featureAccount.id,
|
||||
@@ -948,6 +969,7 @@ export default function WeiboAccountsPage({
|
||||
message.error(getErrorMessage(error));
|
||||
} finally {
|
||||
setExchangingGoodsId(null);
|
||||
exchangeInFlightRef.current = false;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1956,7 +1978,8 @@ export default function WeiboAccountsPage({
|
||||
!featureAccount?.is_enabled ||
|
||||
goods.is_sold_out ||
|
||||
goods.remain_count === 0 ||
|
||||
goods.price > balance;
|
||||
goods.price > balance ||
|
||||
exchangingGoodsId !== null;
|
||||
return (
|
||||
<Popconfirm
|
||||
title={`确认兑换 ${goods.goods_name}?`}
|
||||
@@ -2008,7 +2031,7 @@ export default function WeiboAccountsPage({
|
||||
title: '状态',
|
||||
dataIndex: 'reward_status',
|
||||
width: 100,
|
||||
render: (value: number | null) => value ?? '-',
|
||||
render: renderRewardStatus,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -2054,7 +2077,8 @@ export default function WeiboAccountsPage({
|
||||
workbenchSelectedGoods.is_sold_out ||
|
||||
workbenchSelectedGoods.remain_count === 0 ||
|
||||
workbenchSelectedGoods.price >
|
||||
(mallResult?.weidou_balance ?? featureAccount?.weidou_balance ?? 0);
|
||||
(mallResult?.weidou_balance ?? featureAccount?.weidou_balance ?? 0) ||
|
||||
exchangingGoodsId !== null;
|
||||
const tagOptions = useMemo(
|
||||
() => knownTags.map((tag) => ({ value: tag })),
|
||||
[knownTags],
|
||||
|
||||
Reference in New Issue
Block a user