feat: 补充渠道token过期处理逻辑

This commit is contained in:
2026-08-15 17:02:16 +08:00
parent 0418b40aea
commit 685b7d8370
12 changed files with 656 additions and 110 deletions
@@ -0,0 +1,215 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.support.PddOAuthTokenExchange;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* 拼多多授权凭证可用性:access 将过期时自动 refresh;真正失效以 refresh_token 为准。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddAuthTokenService {
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
/** access 提前刷新窗口 */
private static final long ACCESS_SKEW_SECONDS = 120L;
/** refresh 本地过期判定窗口 */
private static final long REFRESH_SKEW_SECONDS = 60L;
/** 无 refresh_token_expires_in 时默认 30 天 */
private static final long DEFAULT_REFRESH_TTL_SECONDS = 30L * 24 * 3600;
private static final String LOCK_PREFIX = "pdd:auth:refresh:lock:";
private final PddAuthMapper pddAuthMapper;
private final PddOAuthTokenExchange tokenExchange;
private final StringRedisTemplate stringRedisTemplate;
private final ObjectMapper objectMapper;
/**
* 确保返回的 auth 带有可用 access_token;必要时自动 refresh。
*/
public PddAuthPO ensureUsable(PddAuthPO auth) {
if (auth == null || auth.getId() == null) {
throw new PddAuthFailureException("拼多多授权不存在,请重新授权");
}
if (auth.getStatus() == null || auth.getStatus() != 1) {
throw new PddAuthFailureException("拼多多授权无效或已失效,请重新授权");
}
if (!StringUtils.hasText(auth.getAccessToken())) {
throw new PddAuthFailureException("拼多多 access_token 缺失,请重新授权");
}
if (!StringUtils.hasText(auth.getRefreshToken())) {
throw new PddAuthFailureException("拼多多 refresh_token 缺失,请重新授权");
}
if (isRefreshTokenExpired(auth)) {
throw new PddAuthFailureException("拼多多 refresh_token 已过期,请重新授权");
}
if (!isAccessTokenNearExpiry(auth)) {
return auth;
}
return refreshWithLock(auth.getId());
}
public PddAuthPO ensureUsableById(Long authId) {
if (authId == null) {
throw new PddAuthFailureException("拼多多授权不存在,请重新授权");
}
PddAuthPO auth = pddAuthMapper.selectById(authId);
return ensureUsable(auth);
}
/**
* 将换票结果写回 channel_pdd_auth。
*/
public void applyTokenBundle(PddAuthPO auth, PddOAuthTokenExchange.TokenBundle bundle) {
if (auth == null || bundle == null) {
return;
}
LocalDateTime now = LocalDateTime.now(ZONE);
auth.setAccessToken(bundle.getAccessToken());
if (StringUtils.hasText(bundle.getRefreshToken())) {
auth.setRefreshToken(bundle.getRefreshToken());
}
auth.setExpiresAt(resolveExpiresAt(now, bundle.getExpiresAtEpoch(), bundle.getExpiresIn(), 24L * 3600));
auth.setRefreshTokenExpiresAt(resolveExpiresAt(
now,
bundle.getRefreshTokenExpiresAtEpoch(),
bundle.getRefreshTokenExpiresIn(),
DEFAULT_REFRESH_TTL_SECONDS));
if (bundle.getScope() != null) {
try {
auth.setScope(objectMapper.writeValueAsString(bundle.getScope()));
} catch (Exception ignored) {
// keep old scope
}
}
if (StringUtils.hasText(bundle.getRawJson())) {
auth.setRawResponse(bundle.getRawJson());
}
if (StringUtils.hasText(bundle.getOwnerId())) {
auth.setOwnerId(bundle.getOwnerId());
}
auth.setStatus(1);
}
static boolean isAccessTokenNearExpiry(PddAuthPO auth) {
if (auth == null || auth.getExpiresAt() == null) {
// 无过期时间则主动刷一次,避免盲打
return true;
}
LocalDateTime deadline = auth.getExpiresAt().minusSeconds(ACCESS_SKEW_SECONDS);
return !LocalDateTime.now(ZONE).isBefore(deadline);
}
/**
* 真正失效看 refresh_token。
* 兼容历史脏数据:若 refresh 过期时间不晚于 access(曾误用同一 TTL),则忽略本地 refresh 过期,交由平台判定。
*/
static boolean isRefreshTokenExpired(PddAuthPO auth) {
if (auth == null || auth.getRefreshTokenExpiresAt() == null) {
return false;
}
if (auth.getExpiresAt() != null
&& !auth.getRefreshTokenExpiresAt().isAfter(auth.getExpiresAt().plusHours(1))) {
return false;
}
LocalDateTime deadline = auth.getRefreshTokenExpiresAt().minusSeconds(REFRESH_SKEW_SECONDS);
return !LocalDateTime.now(ZONE).isBefore(deadline);
}
private PddAuthPO refreshWithLock(Long authId) {
String lockKey = LOCK_PREFIX + authId;
String token = UUID.randomUUID().toString();
boolean locked = Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfAbsent(lockKey, token, Duration.ofSeconds(30)));
try {
if (!locked) {
waitBriefly();
PddAuthPO latest = pddAuthMapper.selectById(authId);
if (latest != null && latest.getStatus() != null && latest.getStatus() == 1
&& !isAccessTokenNearExpiry(latest)
&& StringUtils.hasText(latest.getAccessToken())) {
return latest;
}
// 等锁失败则再抢一次;抢不到则直接刷新(短窗重复刷新可接受)
locked = Boolean.TRUE.equals(stringRedisTemplate.opsForValue()
.setIfAbsent(lockKey, token, Duration.ofSeconds(30)));
}
return doRefresh(authId);
} finally {
if (locked) {
String current = stringRedisTemplate.opsForValue().get(lockKey);
if (token.equals(current)) {
stringRedisTemplate.delete(lockKey);
}
}
}
}
private PddAuthPO doRefresh(Long authId) {
PddAuthPO auth = pddAuthMapper.selectById(authId);
if (auth == null || auth.getStatus() == null || auth.getStatus() != 1) {
throw new PddAuthFailureException("拼多多授权无效或已失效,请重新授权");
}
if (!isAccessTokenNearExpiry(auth)) {
return auth;
}
if (!StringUtils.hasText(auth.getRefreshToken())) {
throw new PddAuthFailureException("拼多多 refresh_token 缺失,请重新授权");
}
if (isRefreshTokenExpired(auth)) {
throw new PddAuthFailureException("拼多多 refresh_token 已过期,请重新授权");
}
try {
log.info("刷新拼多多 access_token authId={} ownerId={}", authId, auth.getOwnerId());
PddOAuthTokenExchange.TokenBundle bundle = tokenExchange.refresh(auth.getRefreshToken());
applyTokenBundle(auth, bundle);
pddAuthMapper.updateById(auth);
return auth;
} catch (PddAuthFailureException e) {
throw e;
} catch (Exception e) {
log.error("刷新拼多多 access_token 异常 authId={}", authId, e);
throw new PddAuthFailureException("刷新拼多多 access_token 失败: " + e.getMessage());
}
}
static LocalDateTime resolveExpiresAt(LocalDateTime now,
Long epochSeconds,
Integer expiresIn,
long defaultTtlSeconds) {
if (epochSeconds != null && epochSeconds > 0) {
// 平台 expires_at 一般为秒
long epoch = epochSeconds;
if (epoch > 10_000_000_000L) {
epoch = epoch / 1000L;
}
return LocalDateTime.ofInstant(Instant.ofEpochSecond(epoch), ZONE);
}
long ttl = expiresIn != null && expiresIn > 0 ? expiresIn.longValue() : defaultTtlSeconds;
return now.plusSeconds(ttl);
}
private static void waitBriefly() {
try {
TimeUnit.MILLISECONDS.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
@@ -4,8 +4,6 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.http.PopAccessTokenClient;
import com.pdd.pop.sdk.http.token.AccessTokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@@ -19,7 +17,9 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.vo.PddAuthorizeUrlVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopClientFactory;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.support.PddOAuthTokenExchange;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.mall.PddMallApiSnapshot;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.mall.PddMallPopApiClient;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
@@ -29,9 +29,7 @@ import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@@ -48,7 +46,8 @@ public class PddAuthServiceImpl implements PddAuthService {
private static final String PLATFORM_CODE_PDD = PlatformCode.PDD.getCode();
private final PddOAuthProperties properties;
private final PddPopClientFactory popClientFactory;
private final PddOAuthTokenExchange tokenExchange;
private final PddAuthTokenService authTokenService;
private final PddMallPopApiClient mallPopApiClient;
private final StringRedisTemplate stringRedisTemplate;
private final CurrentUserContext currentUserContext;
@@ -58,7 +57,8 @@ public class PddAuthServiceImpl implements PddAuthService {
private final ObjectMapper objectMapper;
public PddAuthServiceImpl(PddOAuthProperties properties,
PddPopClientFactory popClientFactory,
PddOAuthTokenExchange tokenExchange,
PddAuthTokenService authTokenService,
PddMallPopApiClient mallPopApiClient,
StringRedisTemplate stringRedisTemplate,
CurrentUserContext currentUserContext,
@@ -67,7 +67,8 @@ public class PddAuthServiceImpl implements PddAuthService {
ShopMapper shopMapper,
ObjectMapper objectMapper) {
this.properties = properties;
this.popClientFactory = popClientFactory;
this.tokenExchange = tokenExchange;
this.authTokenService = authTokenService;
this.mallPopApiClient = mallPopApiClient;
this.stringRedisTemplate = stringRedisTemplate;
this.currentUserContext = currentUserContext;
@@ -155,32 +156,29 @@ public class PddAuthServiceImpl implements PddAuthService {
return buildResultHtml(false, "授权状态数据不完整,请重新发起授权");
}
AccessTokenResponse tokenResponse = exchangeCode(code);
if (tokenResponse == null || !StringUtils.hasText(tokenResponse.getAccessToken())) {
return buildResultHtml(false, "换取 access_token 失败");
PddOAuthTokenExchange.TokenBundle tokenBundle;
try {
tokenBundle = tokenExchange.exchangeCode(code);
} catch (PddAuthFailureException e) {
return buildResultHtml(false, e.getMessage());
}
if (tokenResponse.getErrorResponse() != null) {
String msg = tokenResponse.getErrorResponse().getErrorMsg();
log.warn("拼多多换票失败: {}", msg);
return buildResultHtml(false, "换取 access_token 失败" + (StringUtils.hasText(msg) ? ":" + msg : ""));
}
if (!StringUtils.hasText(tokenResponse.getOwnerId())) {
if (!StringUtils.hasText(tokenBundle.getOwnerId())) {
return buildResultHtml(false, "授权响应缺少店铺 owner_id");
}
PddAuthPO auth = upsertAuth(companyId, tokenResponse);
Long tentativeMallId = parseLongOrNull(tokenResponse.getOwnerId());
PddAuthPO auth = upsertAuth(companyId, tokenBundle);
Long tentativeMallId = parseLongOrNull(tokenBundle.getOwnerId());
if (tentativeMallId == null) {
return buildResultHtml(false, "无法解析拼多多店铺 owner_id");
}
PddMallApiSnapshot mallInfo = mallPopApiClient.getMallInfoOrNull(
tentativeMallId, tokenResponse.getAccessToken());
tentativeMallId, tokenBundle.getAccessToken());
Long mallId = resolveMallId(tentativeMallId, mallInfo);
if (mallId == null) {
return buildResultHtml(false, "无法解析拼多多店铺 mall_id");
}
upsertPddShop(companyId, auth.getId(), mallId, mallInfo, tokenResponse.getOwnerName());
upsertPddShop(companyId, auth.getId(), mallId, mallInfo, tokenBundle.getOwnerName());
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getCompanyId, companyId)
.eq(PddShopPO::getMallId, mallId)
@@ -192,7 +190,7 @@ public class PddAuthServiceImpl implements PddAuthService {
String shopName = firstNonBlank(
mallInfo != null ? mallInfo.getMallName() : null,
tokenResponse.getOwnerName(),
tokenBundle.getOwnerName(),
"PDD-" + mallId);
return buildResultHtml(true, "授权成功,已绑定店铺「" + shopName + "」(mall_id=" + mallId + ")");
} catch (BusinessException e) {
@@ -218,30 +216,16 @@ public class PddAuthServiceImpl implements PddAuthService {
}
/**
* 使用授权码向拼多多换取 access_token。
* 使用授权码向拼多多换取 token(含 refresh 过期信息)。
*/
private AccessTokenResponse exchangeCode(String code) throws Exception {
PopAccessTokenClient client = popClientFactory.createAccessTokenClient();
try {
return client.generate(code);
} finally {
try {
client.destroy();
} catch (Exception ignored) {
// ignore
}
}
private PddOAuthTokenExchange.TokenBundle exchangeCode(String code) throws Exception {
return tokenExchange.exchangeCode(code);
}
/**
* 按 company_id + owner_id 新增或覆盖写入 channel_pdd_auth(重复授权会使旧 token 失效)。
*/
private PddAuthPO upsertAuth(Long companyId, AccessTokenResponse token) {
LocalDateTime now = LocalDateTime.now();
LocalDateTime expiresAt = plusSeconds(now, token.getExpiresIn());
// AccessTokenResponse 无 refresh 过期秒数时,与 access 同 TTL 兜底
LocalDateTime refreshExpiresAt = plusSeconds(now, token.getExpiresIn());
private PddAuthPO upsertAuth(Long companyId, PddOAuthTokenExchange.TokenBundle token) {
LambdaQueryWrapper<PddAuthPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(PddAuthPO::getCompanyId, companyId)
.eq(PddAuthPO::getOwnerId, token.getOwnerId());
@@ -249,14 +233,10 @@ public class PddAuthServiceImpl implements PddAuthService {
PddAuthPO auth = existing != null ? existing : new PddAuthPO();
auth.setCompanyId(companyId);
auth.setOwnerId(token.getOwnerId());
auth.setAccessToken(token.getAccessToken());
auth.setRefreshToken(token.getRefreshToken());
auth.setExpiresAt(expiresAt);
auth.setRefreshTokenExpiresAt(refreshExpiresAt);
auth.setScope(writeJson(token.getScope()));
auth.setRawResponse(writeJson(token));
auth.setStatus(1);
authTokenService.applyTokenBundle(auth, token);
if (!StringUtils.hasText(auth.getOwnerId())) {
auth.setOwnerId(token.getOwnerId());
}
if (existing == null) {
pddAuthMapper.insert(auth);
@@ -422,33 +402,6 @@ public class PddAuthServiceImpl implements PddAuthService {
""".formatted(title, color, title, safeMessage);
}
/**
* 以当前时刻为基准加上 expires_in 秒,得到过期时间;非法值时默认 24 小时。
*/
private static LocalDateTime plusSeconds(LocalDateTime base, Integer seconds) {
if (seconds == null || seconds <= 0) {
return base.plusHours(24);
}
return LocalDateTime.ofInstant(
Instant.now().plusSeconds(seconds),
ZoneId.systemDefault());
}
/**
* 将对象序列化为 JSON 字符串;失败时返回 null。
*/
private String writeJson(Object value) {
if (value == null) {
return null;
}
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
log.warn("序列化 JSON 失败: {}", e.getMessage());
return null;
}
}
/**
* 将 Redis/JSON 中的数值或字符串安全转为 Long。
*/
@@ -0,0 +1,132 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.support;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pdd.pop.sdk.http.PopBaseHttpResponse;
import com.pdd.pop.sdk.http.PopClient;
import com.pdd.pop.sdk.http.token.AuthTokenCreateRequest;
import com.pdd.pop.sdk.http.token.AuthTokenCreateResponse;
import com.pdd.pop.sdk.http.token.AuthTokenRefreshRequest;
import com.pdd.pop.sdk.http.token.AuthTokenRefreshResponse;
import lombok.Builder;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopClientFactory;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.support.PddPopInvokeSupport;
import java.util.List;
/**
* 拼多多 OAuth 换票:code 换 token / refresh_token 续期。
* 保留 refresh_token_expires_*(SDK AccessTokenResponse 会丢这些字段)。
*/
@Slf4j
@Component
public class PddOAuthTokenExchange {
private final PddPopClientFactory popClientFactory;
private final ObjectMapper objectMapper;
public PddOAuthTokenExchange(PddPopClientFactory popClientFactory, ObjectMapper objectMapper) {
this.popClientFactory = popClientFactory;
this.objectMapper = objectMapper;
}
public TokenBundle exchangeCode(String code) throws Exception {
AuthTokenCreateRequest request = new AuthTokenCreateRequest();
request.setCode(code);
PopClient client = popClientFactory.getHttpClient();
AuthTokenCreateResponse response = client.syncInvoke(request);
assertNoError(response, "pdd.pop.auth.token.create");
AuthTokenCreateResponse.PopAuthTokenCreateResponse body = response.getPopAuthTokenCreateResponse();
if (body == null || !StringUtils.hasText(body.getAccessToken())) {
throw new PddAuthFailureException("换取 access_token 失败:响应为空");
}
return TokenBundle.builder()
.accessToken(body.getAccessToken())
.refreshToken(body.getRefreshToken())
.expiresIn(body.getExpiresIn())
.expiresAtEpoch(body.getExpiresAt())
.refreshTokenExpiresIn(body.getRefreshTokenExpiresIn())
.refreshTokenExpiresAtEpoch(body.getRefreshTokenExpiresAt())
.ownerId(body.getOwnerId())
.ownerName(body.getOwnerName())
.scope(body.getScope())
.rawJson(writeJson(body))
.build();
}
public TokenBundle refresh(String refreshToken) throws Exception {
if (!StringUtils.hasText(refreshToken)) {
throw new PddAuthFailureException("缺少 refresh_token,请重新授权");
}
AuthTokenRefreshRequest request = new AuthTokenRefreshRequest();
request.setRefreshToken(refreshToken);
PopClient client = popClientFactory.getHttpClient();
AuthTokenRefreshResponse response = client.syncInvoke(request);
assertNoError(response, "pdd.pop.auth.token.refresh");
AuthTokenRefreshResponse.PopAuthTokenRefreshResponse body = response.getPopAuthTokenRefreshResponse();
if (body == null || !StringUtils.hasText(body.getAccessToken())) {
throw new PddAuthFailureException("刷新 access_token 失败:响应为空");
}
return TokenBundle.builder()
.accessToken(body.getAccessToken())
.refreshToken(body.getRefreshToken())
.expiresIn(body.getExpiresIn())
.expiresAtEpoch(body.getExpiresAt())
.refreshTokenExpiresIn(body.getRefreshTokenExpiresIn())
.refreshTokenExpiresAtEpoch(body.getRefreshTokenExpiresAt())
.ownerId(body.getOwnerId())
.ownerName(body.getOwnerName())
.scope(body.getScope())
.rawJson(writeJson(body))
.build();
}
private void assertNoError(PopBaseHttpResponse response, String apiType) {
if (response == null) {
throw new PddAuthFailureException(apiType + " 无响应");
}
if (response.getErrorResponse() == null) {
return;
}
PopBaseHttpResponse.ErrorResponse err = response.getErrorResponse();
String msg = err.getErrorMsg();
String subMsg = err.getSubMsg();
String code = err.getErrorCode() == null ? null : String.valueOf(err.getErrorCode());
String subCode = err.getSubCode();
String detail = StringUtils.hasText(msg) ? msg : (StringUtils.hasText(subMsg) ? subMsg : code);
if (PddPopInvokeSupport.isAuthFailure(msg, subMsg, code, subCode)
|| (detail != null && (detail.contains("refresh") || detail.contains("刷新")))) {
throw new PddAuthFailureException(apiType + " 授权失效: " + detail);
}
throw new PddAuthFailureException(apiType + " 失败: " + detail);
}
private String writeJson(Object value) {
try {
return objectMapper.writeValueAsString(value);
} catch (Exception e) {
log.warn("序列化 token 响应失败: {}", e.getMessage());
return null;
}
}
@Getter
@Builder
public static class TokenBundle {
private final String accessToken;
private final String refreshToken;
private final Integer expiresIn;
/** 平台秒级时间戳(若有) */
private final Long expiresAtEpoch;
private final Integer refreshTokenExpiresIn;
private final Long refreshTokenExpiresAtEpoch;
private final String ownerId;
private final String ownerName;
private final List<String> scope;
private final String rawJson;
}
}
@@ -12,8 +12,8 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.common.utils.BeanCopyUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.dto.CreatePddGoodsDTO;
@@ -49,18 +49,18 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
private final PddGoodsSkuMapper pddGoodsSkuMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthMapper pddAuthMapper;
private final PddAuthTokenService authTokenService;
private final PddGoodsPopApiClient goodsPopApiClient;
private final CurrentUserContext currentUserContext;
public PddGoodsServiceImpl(PddGoodsSkuMapper pddGoodsSkuMapper,
PddShopMapper pddShopMapper,
PddAuthMapper pddAuthMapper,
PddAuthTokenService authTokenService,
PddGoodsPopApiClient goodsPopApiClient,
CurrentUserContext currentUserContext) {
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
this.pddShopMapper = pddShopMapper;
this.pddAuthMapper = pddAuthMapper;
this.authTokenService = authTokenService;
this.goodsPopApiClient = goodsPopApiClient;
this.currentUserContext = currentUserContext;
}
@@ -212,11 +212,7 @@ public class PddGoodsServiceImpl extends ServiceImpl<PddGoodsMapper, PddGoodsPO>
if (pddShop.getPddAuthId() == null) {
throw new BusinessException("该渠道店铺尚未绑定授权,请先完成授权");
}
PddAuthPO auth = pddAuthMapper.selectById(pddShop.getPddAuthId());
if (auth == null || auth.getStatus() == null || auth.getStatus() != 1
|| !StringUtils.hasText(auth.getAccessToken())) {
throw new BusinessException("拼多多授权无效或已失效,请重新授权");
}
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
Long mallId = pddShop.getMallId();
String accessToken = auth.getAccessToken();
@@ -7,6 +7,7 @@ import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderFullSyncTaskExecutor;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
@Slf4j
@Component
@@ -26,6 +27,12 @@ public class PddOrderSyncFullConsumer {
}
log.info("收到全量同步消息 taskId={} shopId={} {}~{}",
message.getTaskId(), message.getShopId(), message.getDateFrom(), message.getDateTo());
fullSyncTaskExecutor.execute(message);
try {
fullSyncTaskExecutor.execute(message);
} catch (PddAuthFailureException e) {
// 日任务与父任务已 FAILED,剩余 PENDING 已中止;确认消费避免重投
log.warn("全量同步因授权失效终止 taskId={} shopId={}: {}",
message.getTaskId(), message.getShopId(), e.getMessage());
}
}
}
@@ -7,6 +7,7 @@ import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncIncMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service.PddOrderSyncService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
@Slf4j
@Component
@@ -24,6 +25,11 @@ public class PddOrderSyncIncConsumer {
return;
}
log.info("收到增量同步消息 shopId={} messageId={}", message.getShopId(), message.getMessageId());
pddOrderSyncService.syncIncrementalInternal(message.getCompanyId(), message.getShopId());
try {
pddOrderSyncService.syncIncrementalInternal(message.getCompanyId(), message.getShopId());
} catch (PddAuthFailureException e) {
// 已关闭增量并失效授权;确认消费,避免无限重投
log.warn("增量同步因授权失效终止 shopId={}: {}", message.getShopId(), e.getMessage());
}
}
}
@@ -12,6 +12,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderF
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.messaging.PddSyncFullMessage;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskDayPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import java.time.LocalDate;
import java.time.LocalDateTime;
@@ -145,7 +146,20 @@ public class PddOrderFullSyncTaskExecutor {
}
return;
}
if (isParentAlreadyTerminalMessage(e.getMessage())) {
// 并行日发现父任务已 FAILED:本日记失败但不重复累加父任务
dayMapper.update(null, new LambdaUpdateWrapper<PddOrderFullSyncTaskDayPO>()
.eq(PddOrderFullSyncTaskDayPO::getId, dayRow.getId())
.set(PddOrderFullSyncTaskDayPO::getStatus, PddOrderFullSyncTaskDayPO.STATUS_FAILED)
.set(PddOrderFullSyncTaskDayPO::getLastError, truncate(e.getMessage(), 512))
.set(PddOrderFullSyncTaskDayPO::getFinishTime, LocalDateTime.now()));
return;
}
boolean authFail = e instanceof PddAuthFailureException;
failDayAndParent(taskId, dayRow.getId(), day, e);
if (authFail) {
abortRemainingPendingDays(taskId, truncate(e.getMessage(), 500));
}
throw e;
} catch (Exception e) {
failDayAndParent(taskId, dayRow.getId(), day, e);
@@ -241,10 +255,30 @@ public class PddOrderFullSyncTaskExecutor {
progressPublisher.publish(task);
}
private void abortRemainingPendingDays(Long taskId, String err) {
String message = err != null ? err : "授权失效,任务中止";
int n = dayMapper.update(null, new LambdaUpdateWrapper<PddOrderFullSyncTaskDayPO>()
.eq(PddOrderFullSyncTaskDayPO::getTaskId, taskId)
.eq(PddOrderFullSyncTaskDayPO::getStatus, PddOrderFullSyncTaskDayPO.STATUS_PENDING)
.set(PddOrderFullSyncTaskDayPO::getStatus, PddOrderFullSyncTaskDayPO.STATUS_FAILED)
.set(PddOrderFullSyncTaskDayPO::getLastError, truncate(message, 512))
.set(PddOrderFullSyncTaskDayPO::getFinishTime, LocalDateTime.now()));
if (n > 0) {
log.warn("授权失效,中止剩余待同步日 taskId={} days={}", taskId, n);
taskMapper.update(null, new LambdaUpdateWrapper<PddOrderFullSyncTaskPO>()
.eq(PddOrderFullSyncTaskPO::getId, taskId)
.setSql("failed_days = IFNULL(failed_days, 0) + " + n));
}
}
private static boolean isCancelledMessage(String message) {
return message != null && message.contains("已取消");
}
private static boolean isParentAlreadyTerminalMessage(String message) {
return message != null && message.contains("已失败");
}
private static String truncate(String s, int max) {
if (s == null) {
return null;
@@ -0,0 +1,97 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.mapper.PddOrderIncSyncMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
/**
* 同步侧授权失效统一处置:失效 auth、关闭增量开关、游标置 PAUSED。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class PddOrderSyncAuthFailureHandler {
private final ShopMapper shopMapper;
private final PddAuthMapper pddAuthMapper;
private final PddShopMapper pddShopMapper;
private final PddOrderIncSyncMapper incSyncMapper;
@Transactional(rollbackFor = Exception.class)
public void handle(Long companyId, Long shopId, Long authId, String error) {
String msg = truncate(error, 900);
log.warn("拼多多同步授权失效处置 companyId={} shopId={} authId={} err={}",
companyId, shopId, authId, msg);
Long resolvedAuthId = authId != null ? authId : resolveAuthId(companyId, shopId);
if (resolvedAuthId != null) {
pddAuthMapper.update(null, new LambdaUpdateWrapper<PddAuthPO>()
.eq(PddAuthPO::getId, resolvedAuthId)
.ne(PddAuthPO::getStatus, 0)
.set(PddAuthPO::getStatus, 0));
}
if (shopId != null) {
shopMapper.update(null, new LambdaUpdateWrapper<ShopPO>()
.eq(ShopPO::getId, shopId)
.eq(companyId != null, ShopPO::getCompanyId, companyId)
.set(ShopPO::getOrderIncSyncEnabled, 0));
PddOrderIncSyncPO state = incSyncMapper.selectOne(new LambdaQueryWrapper<PddOrderIncSyncPO>()
.eq(PddOrderIncSyncPO::getShopId, shopId)
.last("LIMIT 1"));
if (state != null) {
state.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
state.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
if (resolvedAuthId != null) {
state.setPddAuthId(resolvedAuthId);
}
incSyncMapper.updateById(state);
} else if (companyId != null) {
PddOrderIncSyncPO neu = new PddOrderIncSyncPO();
neu.setCompanyId(companyId);
neu.setShopId(shopId);
neu.setPddAuthId(resolvedAuthId);
neu.setStatus(PddOrderIncSyncPO.STATUS_PAUSED);
neu.setLastError(msg != null ? msg : "拼多多授权失效,请重新授权");
incSyncMapper.insert(neu);
}
}
}
private Long resolveAuthId(Long companyId, Long shopId) {
if (shopId == null) {
return null;
}
ShopPO shop = shopMapper.selectById(shopId);
if (shop == null || shop.getExternalShopId() == null) {
return null;
}
if (companyId != null && !companyId.equals(shop.getCompanyId())) {
return null;
}
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
.eq(PddShopPO::getId, shop.getExternalShopId())
.last("LIMIT 1"));
return pddShop != null ? pddShop.getPddAuthId() : null;
}
private static String truncate(String error, int max) {
if (!StringUtils.hasText(error)) {
return error;
}
return error.length() > max ? error.substring(0, max) : error;
}
}
@@ -2,11 +2,11 @@ package top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.mapper.PddAuthMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.model.po.PddAuthPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.auth.service.PddAuthTokenService;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.PddOrderSyncShopContext;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.mapper.PddShopMapper;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.shop.model.po.PddShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
@@ -20,16 +20,16 @@ public class PddOrderSyncContextResolver {
private final CurrentUserContext currentUserContext;
private final ShopMapper shopMapper;
private final PddShopMapper pddShopMapper;
private final PddAuthMapper pddAuthMapper;
private final PddAuthTokenService authTokenService;
public PddOrderSyncContextResolver(CurrentUserContext currentUserContext,
ShopMapper shopMapper,
PddShopMapper pddShopMapper,
PddAuthMapper pddAuthMapper) {
PddAuthTokenService authTokenService) {
this.currentUserContext = currentUserContext;
this.shopMapper = shopMapper;
this.pddShopMapper = pddShopMapper;
this.pddAuthMapper = pddAuthMapper;
this.authTokenService = authTokenService;
}
public PddOrderSyncShopContext resolveForCurrentCompany(Long shopId) {
@@ -49,7 +49,7 @@ public class PddOrderSyncContextResolver {
throw new BusinessException("仅支持拼多多平台店铺同步订单");
}
if (shop.getExternalShopId() == null) {
throw new BusinessException("店铺尚未绑定拼多多外部店,请先完成授权");
throw new PddAuthFailureException("店铺尚未绑定拼多多外部店,请先完成授权");
}
PddShopPO pddShop = pddShopMapper.selectOne(new LambdaQueryWrapper<PddShopPO>()
@@ -57,13 +57,10 @@ public class PddOrderSyncContextResolver {
.eq(PddShopPO::getCompanyId, companyId)
.last("LIMIT 1"));
if (pddShop == null || pddShop.getPddAuthId() == null) {
throw new BusinessException("未找到拼多多店铺授权绑定,请重新授权");
}
PddAuthPO auth = pddAuthMapper.selectById(pddShop.getPddAuthId());
if (auth == null || auth.getStatus() == null || auth.getStatus() != 1
|| !StringUtils.hasText(auth.getAccessToken())) {
throw new BusinessException("拼多多授权无效或已失效,请重新授权");
throw new PddAuthFailureException("未找到拼多多店铺授权绑定,请重新授权");
}
// access 将过期则自动 refresh;真正失效看 refresh_token
PddAuthPO auth = authTokenService.ensureUsableById(pddShop.getPddAuthId());
return PddOrderSyncShopContext.builder()
.internalShop(shop)
@@ -18,6 +18,7 @@ import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.dto.PddOrd
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderFullSyncTaskPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.po.PddOrderIncSyncPO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.order.sync.model.vo.PddOrderSyncResultVO;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.order.PddOrderPopApiClient;
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
@@ -54,6 +55,7 @@ public class PddOrderSyncService {
private final ShopMapper shopMapper;
private final List<PddOrderAfterSyncListener> afterSyncListeners;
private final PddOrderConvertPublisher convertPublisher;
private final PddOrderSyncAuthFailureHandler authFailureHandler;
public PddOrderSyncService(PddOrderSyncContextResolver contextResolver,
PddOrderPopApiClient apiClient,
@@ -64,7 +66,8 @@ public class PddOrderSyncService {
StringRedisTemplate stringRedisTemplate,
ShopMapper shopMapper,
List<PddOrderAfterSyncListener> afterSyncListeners,
PddOrderConvertPublisher convertPublisher) {
PddOrderConvertPublisher convertPublisher,
PddOrderSyncAuthFailureHandler authFailureHandler) {
this.contextResolver = contextResolver;
this.apiClient = apiClient;
this.upsertService = upsertService;
@@ -75,6 +78,7 @@ public class PddOrderSyncService {
this.shopMapper = shopMapper;
this.afterSyncListeners = afterSyncListeners != null ? afterSyncListeners : List.of();
this.convertPublisher = convertPublisher;
this.authFailureHandler = authFailureHandler;
}
public PddOrderSyncResultVO syncByConfirmDate(PddOrderSyncDayDTO dto) {
@@ -112,12 +116,24 @@ public class PddOrderSyncService {
}
public PddOrderSyncResultVO syncIncremental(Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolveForCurrentCompany(shopId);
PddOrderSyncShopContext ctx;
try {
ctx = contextResolver.resolveForCurrentCompany(shopId);
} catch (PddAuthFailureException e) {
onAuthFailure(null, shopId, null, e);
throw e;
}
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
}
public PddOrderSyncResultVO syncIncrementalInternal(Long companyId, Long shopId) {
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
PddOrderSyncShopContext ctx;
try {
ctx = contextResolver.resolve(companyId, shopId);
} catch (PddAuthFailureException e) {
onAuthFailure(companyId, shopId, null, e);
throw e;
}
return withIncLock(ctx.getShopId(), () -> doIncremental(ctx));
}
@@ -175,8 +191,15 @@ public class PddOrderSyncService {
}
public PddOrderSyncResultVO syncByConfirmDateForTask(Long companyId, Long shopId, LocalDate day, Long taskId) {
PddOrderSyncShopContext ctx = contextResolver.resolve(companyId, shopId);
return withFullDayLock(ctx.getShopId(), day, () -> doSyncConfirmRange(ctx, day, day, "day", taskId));
PddOrderSyncShopContext ctx;
try {
ctx = contextResolver.resolve(companyId, shopId);
} catch (PddAuthFailureException e) {
onAuthFailure(companyId, shopId, null, e);
throw e;
}
return withFullDayLock(ctx.getShopId(), day,
() -> doSyncConfirmRange(ctx, day, day, "day", taskId));
}
private PddOrderSyncResultVO doSyncConfirmRange(PddOrderSyncShopContext ctx,
@@ -235,6 +258,10 @@ public class PddOrderSyncService {
}
} catch (PddPopRateLimitedException e) {
errors.add(e.getMessage());
} catch (PddAuthFailureException e) {
errors.add(e.getMessage());
onAuthFailure(ctx, e);
throw e;
} catch (BusinessException e) {
errors.add(e.getMessage());
throw e;
@@ -258,9 +285,16 @@ public class PddOrderSyncService {
return;
}
PddOrderFullSyncTaskPO task = fullSyncTaskMapper.selectById(taskId);
if (task != null && PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(task.getStatus())) {
if (task == null) {
return;
}
if (PddOrderFullSyncTaskPO.STATUS_CANCELLED.equals(task.getStatus())) {
throw new BusinessException("全量同步任务已取消");
}
// 并行日:父任务已因鉴权等原因 FAILED 时尽快停跑,避免继续打已失效 token
if (PddOrderFullSyncTaskPO.STATUS_FAILED.equals(task.getStatus())) {
throw new BusinessException("全量同步任务已失败");
}
}
private PddOrderSyncResultVO doIncremental(PddOrderSyncShopContext ctx) {
@@ -326,6 +360,10 @@ public class PddOrderSyncService {
} catch (PddPopRateLimitedException e) {
errors.add(e.getMessage());
noteIncRateLimit(ctx, e.getMessage());
} catch (PddAuthFailureException e) {
errors.add(e.getMessage());
onAuthFailure(ctx, e);
throw e;
} catch (BusinessException e) {
errors.add(e.getMessage());
markIncError(ctx, e.getMessage());
@@ -386,6 +424,19 @@ public class PddOrderSyncService {
}
}
private void onAuthFailure(PddOrderSyncShopContext ctx, PddAuthFailureException e) {
Long authId = ctx.getAuth() != null ? ctx.getAuth().getId() : null;
onAuthFailure(ctx.getCompanyId(), ctx.getShopId(), authId, e);
}
private void onAuthFailure(Long companyId, Long shopId, Long authId, PddAuthFailureException e) {
try {
authFailureHandler.handle(companyId, shopId, authId, e.getMessage());
} catch (Exception ex) {
log.warn("授权失效处置失败 shopId={}: {}", shopId, ex.getMessage());
}
}
private void noteIncRateLimit(PddOrderSyncShopContext ctx, String error) {
try {
PddOrderIncSyncPO state = getOrCreateIncState(ctx);
@@ -0,0 +1,16 @@
package top.xyquan.ecomdmbbackend.modules.channel.pdd.pop;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
/**
* 拼多多 access_token / 授权失效(本地过期或平台鉴权错误)。
* 同步侧应:关闭增量开关、暂停游标、失效授权;全量任务失败并中止剩余日。
*/
public class PddAuthFailureException extends BusinessException {
public static final String CODE = "PDD_AUTH_FAILURE";
public PddAuthFailureException(String message) {
super(CODE, message);
}
}
@@ -6,6 +6,7 @@ import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddAuthFailureException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopClientFactory;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.PddPopRateLimitedException;
import top.xyquan.ecomdmbbackend.modules.channel.pdd.pop.config.PddPopProperties;
@@ -63,21 +64,50 @@ public class PddPopInvokeSupport {
throw last != null ? last : new PddPopRateLimitedException(apiType + " 限流重试失败");
}
/** 校验 POP 响应;频控抛 {@link PddPopRateLimitedException},其它业务错误抛 {@link BusinessException}。 */
/** 校验 POP 响应;鉴权失败 / 频控 / 其它业务错误分别抛对应异常。 */
public void assertNoError(PopBaseHttpResponse response, String apiType) {
if (response == null) {
throw new BusinessException("拼多多接口无响应: " + apiType);
}
if (response.getErrorResponse() != null) {
String msg = response.getErrorResponse().getErrorMsg();
String code = String.valueOf(response.getErrorResponse().getErrorCode());
if (isRateLimitMessage(msg, code)) {
throw new PddPopRateLimitedException(apiType + " 触发平台限流: " + msg);
PopBaseHttpResponse.ErrorResponse err = response.getErrorResponse();
String msg = err.getErrorMsg();
String subMsg = err.getSubMsg();
String code = err.getErrorCode() == null ? null : String.valueOf(err.getErrorCode());
String subCode = err.getSubCode();
String detail = firstNonBlank(msg, subMsg, code);
if (isAuthFailure(msg, subMsg, code, subCode)) {
throw new PddAuthFailureException(apiType + " 授权失效: " + detail);
}
throw new BusinessException(apiType + " 调用失败: " + (StringUtils.hasText(msg) ? msg : code));
if (isRateLimitMessage(msg, code) || isRateLimitMessage(subMsg, subCode)) {
throw new PddPopRateLimitedException(apiType + " 触发平台限流: " + detail);
}
throw new BusinessException(apiType + " 调用失败: " + detail);
}
}
/**
* 识别 access_token / 授权失效类错误。
* 常见:error_code=10019(access_token 过期),以及文案含 token/授权/过期 等。
*/
public static boolean isAuthFailure(String msg, String subMsg, String code, String subCode) {
if ("10019".equals(code) || "10019".equals(subCode)) {
return true;
}
// 部分场景平台用 50001 + 文案提示 token
String blob = ((msg == null ? "" : msg) + " " + (subMsg == null ? "" : subMsg)
+ " " + (code == null ? "" : code) + " " + (subCode == null ? "" : subCode)).toLowerCase();
if (blob.contains("access_token") || blob.contains("access token")
|| blob.contains("token已过期") || blob.contains("token过期")
|| blob.contains("token expired") || blob.contains("invalid session")
|| blob.contains("session expired")) {
return true;
}
return blob.contains("授权已过期") || blob.contains("授权失效") || blob.contains("授权无效")
|| blob.contains("未授权") || blob.contains("重新授权")
|| (blob.contains("授权") && (blob.contains("过期") || blob.contains("失效")));
}
public static boolean isRateLimitMessage(String msg, String code) {
String m = (msg == null ? "" : msg) + " " + (code == null ? "" : code);
String lower = m.toLowerCase();
@@ -85,6 +115,18 @@ public class PddPopInvokeSupport {
|| m.contains("限流") || m.contains("频率") || m.contains("过于频繁");
}
private static String firstNonBlank(String... parts) {
if (parts == null) {
return "";
}
for (String p : parts) {
if (StringUtils.hasText(p)) {
return p;
}
}
return "";
}
private static void sleepQuietly(long ms) {
if (ms <= 0) {
return;