Browse Source

feat(lingxing): 令牌续约接口

按官方文档 /api/auth-server/oauth/refresh 实现:
- 表单 appId + refreshToken,multipart/form-data
- 每个 refresh_token 只能使用一次,响应返回新的 refresh_token
- 成功码 "200",失败时 HTTP 仍 200,靠 code 区分

LingxingAdapter 的刷新策略:
1. previous 有 refresh_token → 走续约
2. 续约抛 AuthException → 退回 appId + appSecret 全量换新
3. previous 为空(首次/被 forceRefresh 删除)→ 全量换新

顺带清理:
- LingxingApi 新增 TOKEN_REFRESH
- 删除 LingxingAdapter 中已迁往子平台的 buildOrderListBody / signedRequest
- 删除相应未使用 import

Co-Authored-By: Claude <noreply@anthropic.com>
feature/supplier-lingxing
chenchuchuan 3 weeks ago
parent
commit
782225fe32
  1. 3
      lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java
  2. 51
      lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java
  3. 66
      lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java

3
lingxing/src/main/java/common/ecommerce/lingxing/LingxingApi.java

@ -17,6 +17,9 @@ public enum LingxingApi {
/** 换取令牌;所有子平台共用。 */ /** 换取令牌;所有子平台共用。 */
TOKEN("/api/auth-server/oauth/access-token", 100), TOKEN("/api/auth-server/oauth/access-token", 100),
/** 续约令牌:用 refresh_token 延长有效期,每个 refresh_token 只能用一次。 */
TOKEN_REFRESH("/api/auth-server/oauth/refresh", 100),
// 店铺列表、商品列表的路径尚未核对,不预置占位值; // 店铺列表、商品列表的路径尚未核对,不预置占位值;
// 拿到官方文档后在此追加,一条路径只写一次。 // 拿到官方文档后在此追加,一条路径只写一次。

51
lingxing/src/main/java/common/ecommerce/lingxing/adapter/LingxingAdapter.java

@ -9,8 +9,8 @@ import common.ecommerce.lingxing.platform.LingxingSubPlatforms;
import common.ecommerce.capability.AggregatorCapable; import common.ecommerce.capability.AggregatorCapable;
import common.ecommerce.capability.SalesOrderCapable; import common.ecommerce.capability.SalesOrderCapable;
import common.ecommerce.error.AuthException;
import common.ecommerce.error.ChannelException; import common.ecommerce.error.ChannelException;
import common.ecommerce.http.HttpRequest;
import common.ecommerce.http.HttpTransport; import common.ecommerce.http.HttpTransport;
import common.ecommerce.http.JacksonJsonCodec; import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.http.TokenManager; import common.ecommerce.http.TokenManager;
@ -30,14 +30,9 @@ import common.ecommerce.spi.TokenStore;
import java.time.Clock; import java.time.Clock;
import java.time.Duration; import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId; import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet; import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
/** /**
@ -66,10 +61,23 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab
this.clock = clock; this.clock = clock;
this.mapper = new LingxingOrderMapper(json); this.mapper = new LingxingOrderMapper(json);
final LingxingTokenClient tokenClient = new LingxingTokenClient(transport, json, clock); final LingxingTokenClient tokenClient = new LingxingTokenClient(transport, json, clock);
// 领星 access_token 约 2h,提前 10 分钟续期 // 领星 access_token 约 2h,提前 10 分钟续期。
//
// 有 refresh_token 时优先走续约接口(每个 refresh_token 只能用一次,
// 响应会返回新的 refresh_token,由 TokenManager 覆盖写回);
// 续约失败(refresh_token 过期/被用掉)再退回 appId + appSecret 全量换新。
this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, 600) { this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, 600) {
@Override @Override
protected AccessToken refresh(ChannelSecret secret, AccessToken previous) { protected AccessToken refresh(ChannelSecret secret, AccessToken previous) {
if (previous != null && previous.refreshToken() != null
&& !previous.refreshToken().trim().isEmpty()) {
try {
return tokenClient.refresh(secret.endpointBaseUrl(), secret.appKey(),
previous.refreshToken());
} catch (AuthException e) {
// refresh_token 失效,退回全量换新
}
}
return tokenClient.fetch(secret.endpointBaseUrl(), secret.appKey(), secret.appSecret()); return tokenClient.fetch(secret.endpointBaseUrl(), secret.appKey(), secret.appSecret());
} }
}; };
@ -155,35 +163,6 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab
// ---------------------------------------------------------------- internals // ---------------------------------------------------------------- internals
/** /**
* 多平台订单列表请求体。
*
* <p>字段名以官方文档为准:{@code start_time}/{@code end_time} 是 epoch 秒,
* {@code platform_code} 与 {@code store_id} 都是数组。</p>
*/
private Map<String, Object> buildOrderListBody(ChannelAccount account, Instant from, Instant to,
int offset, int length) {
Map<String, Object> body = new LinkedHashMap<String, Object>();
body.put("offset", offset);
body.put("length", length);
body.put("date_type", "update_time");
body.put("start_time", from.getEpochSecond());
body.put("end_time", to.getEpochSecond());
if (account.platformCode() != null) {
body.put("platform_code", Collections.singletonList(account.platformCode()));
}
if (account.externalStoreId() != null) {
body.put("store_id", Collections.singletonList(account.externalStoreId()));
}
return body;
}
private HttpRequest signedRequest(ChannelContext ctx, String path, Map<String, Object> body, String operation) {
ChannelSecret secret = ctx.secret();
AccessToken token = tokenManager.getOrRefresh(tokenKey(secret), secret);
return requestFactory.post(ctx.endpointBaseUrl(), path, body, secret, token, ctx, operation);
}
/**
* 令牌缓存维度:领星 token 按 app 发放(appId + appSecret 换), * 令牌缓存维度:领星 token 按 app 发放(appId + appSecret 换),
* 同一 app 下的多家店铺共用一个 token。用 appKey 而不是 store_id, * 同一 app 下的多家店铺共用一个 token。用 appKey 而不是 store_id,
* 避免同 app 多店铺重复换 token 白烧配额。 * 避免同 app 多店铺重复换 token 白烧配额。

66
lingxing/src/main/java/common/ecommerce/lingxing/auth/LingxingTokenClient.java

@ -1,6 +1,4 @@
package common.ecommerce.lingxing.auth; package common.ecommerce.lingxing.auth;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.error.AuthException; import common.ecommerce.error.AuthException;
import common.ecommerce.error.ChannelException; import common.ecommerce.error.ChannelException;
@ -9,6 +7,8 @@ import common.ecommerce.http.HttpResponse;
import common.ecommerce.http.HttpTransport; import common.ecommerce.http.HttpTransport;
import common.ecommerce.http.JsonCodec; import common.ecommerce.http.JsonCodec;
import common.ecommerce.http.Responses; import common.ecommerce.http.Responses;
import common.ecommerce.lingxing.LingxingApi;
import common.ecommerce.lingxing.LingxingConstants;
import common.ecommerce.spi.AccessToken; import common.ecommerce.spi.AccessToken;
import java.time.Clock; import java.time.Clock;
@ -17,16 +17,16 @@ import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
/** /**
* 领星令牌获取:{@code POST /api/auth-server/oauth/access-token}。 * 领星令牌接口。两个端点,按官方文档(2026-10 核对):
* *
* <p>按官方文档(2026-10 核对):</p>
* <ul> * <ul>
* <li>请求头 {@code Content-Type: multipart/form-data}</li> * <li><b>换取</b> {@code POST /api/auth-server/oauth/access-token}:表单 {@code appId} / {@code appSecret}</li>
* <li>表单参数 {@code appId} / {@code appSecret}</li> * <li><b>续约</b> {@code POST /api/auth-server/oauth/refresh}:表单 {@code appId} / {@code refreshToken},
* <li>响应 {@code code == "200"} 为成功,{@code data} 含 * <b>每个 refresh_token 只能使用一次</b>,响应里会返回新的 refresh_token</li>
* {@code access_token} / {@code refresh_token} / {@code expires_in}(秒)</li>
* <li>失败时 HTTP 仍是 200,靠 {@code code} 区分,{@code data} 为 null</li>
* </ul> * </ul>
*
* <p>两个接口的共同点:请求头 {@code Content-Type: multipart/form-data};
* 业务成功码为 {@code "200"};失败时 HTTP 仍是 200,靠 {@code code} 区分,{@code data} 为 null。</p>
*/ */
public final class LingxingTokenClient { public final class LingxingTokenClient {
@ -37,6 +37,9 @@ public final class LingxingTokenClient {
private static final String BOUNDARY = "----commonEcommerceLingxingBoundary"; private static final String BOUNDARY = "----commonEcommerceLingxingBoundary";
private static final String MULTIPART_CONTENT_TYPE = "multipart/form-data; boundary=" + BOUNDARY; private static final String MULTIPART_CONTENT_TYPE = "multipart/form-data; boundary=" + BOUNDARY;
private static final String OP_FETCH = "token.fetch";
private static final String OP_REFRESH = "token.refresh";
private final HttpTransport transport; private final HttpTransport transport;
private final JsonCodec json; private final JsonCodec json;
private final Clock clock; private final Clock clock;
@ -47,29 +50,54 @@ public final class LingxingTokenClient {
this.clock = clock; this.clock = clock;
} }
/** 端点由调用方每次传入,与其它接口一致。 */ /** 首次换取令牌:appId + appSecret。端点由调用方每次传入,与其它接口一致。 */
public AccessToken fetch(String baseUrl, String appId, String appSecret) { public AccessToken fetch(String baseUrl, String appId, String appSecret) {
Map<String, String> form = new LinkedHashMap<String, String>(); Map<String, String> form = new LinkedHashMap<String, String>();
form.put("appId", appId); form.put("appId", appId);
form.put("appSecret", appSecret); form.put("appSecret", appSecret);
return request(baseUrl, LingxingApi.TOKEN, form, OP_FETCH);
}
/**
* 续约令牌:appId + refreshToken。
*
* <p>注意每个 refresh_token 只能使用一次——调用方必须用响应里的新 refresh_token
* 覆盖旧的,否则下次续约会失败。</p>
*/
public AccessToken refresh(String baseUrl, String appId, String refreshToken) {
if (refreshToken == null || refreshToken.trim().isEmpty()) {
throw new AuthException(ChannelException.builder()
.message("refreshToken must not be blank")
.operation(OP_REFRESH)
.provider(LingxingConstants.ADAPTER_ID)
.retryable(false));
}
Map<String, String> form = new LinkedHashMap<String, String>();
form.put("appId", appId);
form.put("refreshToken", refreshToken);
return request(baseUrl, LingxingApi.TOKEN_REFRESH, form, OP_REFRESH);
}
// ---------------------------------------------------------------- internals
private AccessToken request(String baseUrl, LingxingApi api, Map<String, String> form, String operation) {
HttpRequest req = HttpRequest.builder() HttpRequest req = HttpRequest.builder()
.method("POST") .method("POST")
.url(trimTrailingSlash(baseUrl) + LingxingApi.TOKEN.path()) .url(trimTrailingSlash(baseUrl) + api.path())
.contentType(MULTIPART_CONTENT_TYPE) .contentType(MULTIPART_CONTENT_TYPE)
.body(multipartBody(form)) .body(multipartBody(form))
.operation("token.refresh") .operation(operation)
.build(); .build();
HttpResponse resp = transport.execute(req); HttpResponse resp = transport.execute(req);
Responses.throwIfNotSuccess(resp, "token.refresh"); Responses.throwIfNotSuccess(resp, operation);
String code = json.stringAt(resp.body(), "code"); String code = json.stringAt(resp.body(), "code");
if (!SUCCESS_CODE.equals(code)) { if (!SUCCESS_CODE.equals(code)) {
throw new AuthException(ChannelException.builder() throw new AuthException(ChannelException.builder()
.message("lingxing token rejected: code=" + code .message("lingxing token rejected: code=" + code
+ ", msg=" + json.stringAt(resp.body(), "msg")) + ", msg=" + json.stringAt(resp.body(), "msg"))
.operation("token.refresh") .operation(operation)
.provider(LingxingConstants.ADAPTER_ID) .provider(LingxingConstants.ADAPTER_ID)
.platformCode(code) .platformCode(code)
.rawResponse(resp.body())); .rawResponse(resp.body()));
@ -79,7 +107,7 @@ public final class LingxingTokenClient {
if (token == null || token.trim().isEmpty()) { if (token == null || token.trim().isEmpty()) {
throw new AuthException(ChannelException.builder() throw new AuthException(ChannelException.builder()
.message("lingxing token response has no data.access_token") .message("lingxing token response has no data.access_token")
.operation("token.refresh") .operation(operation)
.provider(LingxingConstants.ADAPTER_ID) .provider(LingxingConstants.ADAPTER_ID)
.rawResponse(resp.body())); .rawResponse(resp.body()));
} }
@ -87,13 +115,13 @@ public final class LingxingTokenClient {
return AccessToken.builder() return AccessToken.builder()
.value(token) .value(token)
.refreshToken(json.stringAt(resp.body(), "data.refresh_token")) .refreshToken(json.stringAt(resp.body(), "data.refresh_token"))
.expiresAt(Instant.now(clock).plusSeconds(expiresInSeconds(resp.body()))) .expiresAt(Instant.now(clock).plusSeconds(expiresInSeconds(resp.body(), operation)))
.tokenType("Bearer") .tokenType("Bearer")
.build(); .build();
} }
/** {@code expires_in} 单位为秒;缺失或非法时按文档示例值兜底。 */ /** {@code expires_in} 单位为秒;缺失或非法时按文档示例值兜底。 */
private long expiresInSeconds(String body) { private long expiresInSeconds(String body, String operation) {
String raw = json.stringAt(body, "data.expires_in"); String raw = json.stringAt(body, "data.expires_in");
if (raw == null || raw.trim().isEmpty()) { if (raw == null || raw.trim().isEmpty()) {
return 7199L; return 7199L;
@ -103,7 +131,7 @@ public final class LingxingTokenClient {
} catch (NumberFormatException e) { } catch (NumberFormatException e) {
throw new AuthException(ChannelException.builder() throw new AuthException(ChannelException.builder()
.message("lingxing token expires_in is not a number: " + raw) .message("lingxing token expires_in is not a number: " + raw)
.operation("token.refresh") .operation(operation)
.provider(LingxingConstants.ADAPTER_ID) .provider(LingxingConstants.ADAPTER_ID)
.rawResponse(body)); .rawResponse(body));
} }
@ -117,7 +145,7 @@ public final class LingxingTokenClient {
return url.substring(0, end); return url.substring(0, end);
} }
/** multipart/form-data 请求体;字段值不做转义,appId/appSecret 只含安全字符。 */ /** multipart/form-data 请求体;字段值不做转义,appId/appSecret/refreshToken 只含安全字符。 */
private static String multipartBody(Map<String, String> form) { private static String multipartBody(Map<String, String> form) {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> e : form.entrySet()) { for (Map.Entry<String, String> e : form.entrySet()) {

Loading…
Cancel
Save