Browse Source
- GET /api.login?appkey=&secret= 换取客户级 token,token 放 query 参数, 不是 Authorization 头 - token_expire_time 按北京时间 yyyy-MM-dd HH:mm:ss 解析为 UTC expiresAt; 字段缺失按文档 2 小时兜底,格式非法直接失败 - TokenManager 按 appkey 缓存(同客户多仓共用一个 token),提前 10 分钟续期; 信仓无 refresh 接口,到期即重新登录 - XincangEnvelope 统一校验顶层 errno 与 rst.code,HTTP 401/403/429/5xx 照常分类, trace_id 落到 platformRequestId - 本期不声明任何 WarehouseCapability,业务能力后续逐个接入 - 附登录只读探针,默认跳过,凭据走 -Dxincang.probe.* 待核对:生产基址(文档只给测试地址)与限流值(文档未公开,暂按 2 req/s)。 Co-Authored-By: Claude Code <noreply@anthropic.com>feature/supplier-lingxing
15 changed files with 1255 additions and 6 deletions
@ -0,0 +1,37 @@ |
|||||||
|
<?xml version="1.0" encoding="UTF-8"?> |
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" |
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" |
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> |
||||||
|
<modelVersion>4.0.0</modelVersion> |
||||||
|
|
||||||
|
<parent> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>channel-sdk-parent</artifactId> |
||||||
|
<version>1.0.0-SNAPSHOT</version> |
||||||
|
</parent> |
||||||
|
|
||||||
|
<artifactId>warehouse-sdk-xincang</artifactId> |
||||||
|
<description>信仓三方仓适配器(3PL 仓储履约,登录换 token)</description> |
||||||
|
|
||||||
|
<dependencies> |
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>sdk-common</artifactId> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>warehouse-sdk-core</artifactId> |
||||||
|
</dependency> |
||||||
|
|
||||||
|
<dependency> |
||||||
|
<groupId>ecommerce</groupId> |
||||||
|
<artifactId>sdk-testkit</artifactId> |
||||||
|
<scope>test</scope> |
||||||
|
</dependency> |
||||||
|
<dependency> |
||||||
|
<groupId>org.junit.jupiter</groupId> |
||||||
|
<artifactId>junit-jupiter</artifactId> |
||||||
|
<scope>test</scope> |
||||||
|
</dependency> |
||||||
|
</dependencies> |
||||||
|
</project> |
||||||
@ -0,0 +1,79 @@ |
|||||||
|
package common.ecommerce.xincang; |
||||||
|
|
||||||
|
import common.ecommerce.shared.support.PlatformTime; |
||||||
|
|
||||||
|
import java.time.ZoneId; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓(XinCang)协议常量。 |
||||||
|
* |
||||||
|
* <p>端点与路径是<b>协议的一部分</b>,写在代码里,不做成配置表。 |
||||||
|
* 运行时不使用 {@link #TEST_BASE_URL}:端点由调用方每次经 |
||||||
|
* {@code WarehouseConnection} 传入。</p> |
||||||
|
* |
||||||
|
* <p>依据 Apifox「OMS接口文档V2」(2026-11 核对)与其《新 OMS 接口迁移调整说明》。</p> |
||||||
|
*/ |
||||||
|
public final class XincangConstants { |
||||||
|
|
||||||
|
/** 适配器标识。 */ |
||||||
|
public static final String ADAPTER_ID = "xincang"; |
||||||
|
|
||||||
|
/** |
||||||
|
* 测试 / 联调环境基址。 |
||||||
|
* |
||||||
|
* <p>文档明确写了这个地址;末尾不带斜杠,与 {@code WarehouseConnection} 的归一化一致, |
||||||
|
* 路径直接以 {@code /} 开头拼接。</p> |
||||||
|
*/ |
||||||
|
public static final String TEST_BASE_URL = "http://test.api.oms.13u3.com/oms"; |
||||||
|
|
||||||
|
/** |
||||||
|
* 生产环境基址。 |
||||||
|
* |
||||||
|
* <p><b>待核对</b>:官方文档只给了测试地址(迁移说明里那句「生产环境接口路径与请求方法 |
||||||
|
* 全部保持不变」只谈路径)。生产域名确认后只改这一处。调用方需要时可直接传自己的 |
||||||
|
* {@code WarehouseConnection.endpointBaseUrl},不依赖本常量。</p> |
||||||
|
*/ |
||||||
|
public static final String PRODUCTION_BASE_URL = "待核对"; |
||||||
|
|
||||||
|
/** 登录换取 token。 */ |
||||||
|
public static final String PATH_LOGIN = "/api.login"; |
||||||
|
|
||||||
|
/** 登录响应里的 token 归入哪个作用域;信仓用 query 参数传递,不是 {@code Authorization} 头。 */ |
||||||
|
public static final String TOKEN_LOCATION = "query"; |
||||||
|
|
||||||
|
/** 业务接口 query 参数名(token 维度,客户级)。 */ |
||||||
|
public static final String QUERY_TOKEN = "token"; |
||||||
|
|
||||||
|
/** 登录接口的 query 参数名。 */ |
||||||
|
public static final String QUERY_APP_KEY = "appkey"; |
||||||
|
/** 登录接口的 query 参数名。 */ |
||||||
|
public static final String QUERY_APP_SECRET = "secret"; |
||||||
|
|
||||||
|
/** 业务成功:顶层 {@code errno=0} 且(列表类接口){@code rst.code="0"}。 */ |
||||||
|
public static final String SUCCESS_ERRNO = "0"; |
||||||
|
public static final String SUCCESS_RST_CODE = "0"; |
||||||
|
|
||||||
|
/** |
||||||
|
* token 有效期兜底值(秒)。 |
||||||
|
* |
||||||
|
* <p>文档:测试数据说明写明有效期 2 小时;正常以响应里的 {@code token_expire_time} 为准, |
||||||
|
* 只有该字段缺失 / 无法解析时才用这个值,并记一条 WARN 级别的日志语义。</p> |
||||||
|
*/ |
||||||
|
public static final long DEFAULT_TOKEN_TTL_SECONDS = 2 * 60 * 60L; |
||||||
|
|
||||||
|
/** 提前续期的窗口(秒)。 */ |
||||||
|
public static final long TOKEN_EARLY_REFRESH_SECONDS = 600L; |
||||||
|
|
||||||
|
/** |
||||||
|
* 限流:文档未公开限流值。 |
||||||
|
* |
||||||
|
* <p><b>待核对</b>:按三家仓的保守默认 2 req/s/仓,联调确认后只改这一处。</p> |
||||||
|
*/ |
||||||
|
public static final int PERMITS_PER_SECOND = 2; |
||||||
|
|
||||||
|
/** 信仓以北京时间为准(文档「时间:北京时间」)。 */ |
||||||
|
public static final ZoneId SYSTEM_ZONE = PlatformTime.BEIJING_ZONE; |
||||||
|
|
||||||
|
private XincangConstants() { |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,86 @@ |
|||||||
|
package common.ecommerce.xincang.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpTransport; |
||||||
|
import common.ecommerce.http.JsonCodec; |
||||||
|
import common.ecommerce.http.TokenManager; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.spi.LockProvider; |
||||||
|
import common.ecommerce.shared.spi.TokenStore; |
||||||
|
import common.ecommerce.warehouse.WarehouseCapability; |
||||||
|
import common.ecommerce.warehouse.WarehouseProvider; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseAdapter; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import common.ecommerce.xincang.auth.XincangTokenClient; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.util.EnumSet; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓适配器(本期只做登录换 token)。 |
||||||
|
* |
||||||
|
* <p>文档确认的鉴权方式:{@code GET /api.login?appkey=&secret=} 换取客户级 token, |
||||||
|
* 有效期 2 小时、无 refresh 接口;业务请求把 token 放在 query 参数 {@code token} 里。 |
||||||
|
* 本轮只落地登录与令牌缓存,出库 / 库存 / 预报等能力位<b>一律不声明</b>, |
||||||
|
* 门面调用这些能力会显式抛 {@code WarehouseUnsupportedCapabilityException}。</p> |
||||||
|
* |
||||||
|
* <p>适配器只持有协议与基础设施,不持有端点与凭据——两者随每次调用经 |
||||||
|
* {@code WarehouseConnection} 传入。</p> |
||||||
|
*/ |
||||||
|
public final class XincangAdapter implements WarehouseAdapter { |
||||||
|
|
||||||
|
private final XincangTokenClient tokenClient; |
||||||
|
private final TokenManager tokenManager; |
||||||
|
|
||||||
|
public XincangAdapter(HttpTransport transport, JsonCodec json, |
||||||
|
TokenStore tokenStore, LockProvider lockProvider, Clock clock) { |
||||||
|
this.tokenClient = new XincangTokenClient(transport, json, clock); |
||||||
|
// 信仓 token 2h、无 refresh 接口:到期前 10 分钟重新登录换取;
|
||||||
|
// TokenManager 负责锁内防击穿与缓存读写,缓存键按 appkey(客户级)。
|
||||||
|
this.tokenManager = new TokenManager(tokenStore, lockProvider, clock, |
||||||
|
XincangConstants.TOKEN_EARLY_REFRESH_SECONDS) { |
||||||
|
@Override |
||||||
|
protected AccessToken refresh(ChannelSecret secret, AccessToken previous) { |
||||||
|
return tokenClient.fetch(secret.endpointBaseUrl(), secret.appKey(), secret.appSecret()); |
||||||
|
} |
||||||
|
}; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String adapterId() { |
||||||
|
return XincangConstants.ADAPTER_ID; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public WarehouseProvider provider() { |
||||||
|
return WarehouseProvider.XINCANG; |
||||||
|
} |
||||||
|
|
||||||
|
/** 本期没有已实现的能力;后续接入业务接口时再逐个声明。 */ |
||||||
|
@Override |
||||||
|
public EnumSet<WarehouseCapability> capabilities() { |
||||||
|
return EnumSet.noneOf(WarehouseCapability.class); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 取一个可用 token(缓存命中则不登录)。 |
||||||
|
* |
||||||
|
* <p>供健康检查与联调探针使用;业务方法接入时也应经此取 token, |
||||||
|
* 不要在适配器外自行缓存。</p> |
||||||
|
* |
||||||
|
* @throws common.ecommerce.shared.error.AuthException 登录被拒或令牌结构不符合文档 |
||||||
|
*/ |
||||||
|
public AccessToken login(WarehouseContext ctx) { |
||||||
|
return tokenManager.getOrRefresh(tokenKey(ctx.secret()), ctx.secret()); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 令牌缓存维度:信仓 token 按客户(appkey)发放,同一 appkey 下多仓共用一个 token。 |
||||||
|
* |
||||||
|
* <p>用 appkey 而不是 {@code warehouseCode},避免同客户多仓重复登录。</p> |
||||||
|
*/ |
||||||
|
static String tokenKey(ChannelSecret secret) { |
||||||
|
return XincangConstants.ADAPTER_ID + ":" + secret.appKey(); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,51 @@ |
|||||||
|
package common.ecommerce.xincang.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.http.OkHttpTransport; |
||||||
|
import common.ecommerce.shared.spi.LockProvider; |
||||||
|
import common.ecommerce.shared.spi.TokenStore; |
||||||
|
import common.ecommerce.warehouse.WarehouseProvider; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseAdapter; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseAdapterFactory; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓适配器工厂。 |
||||||
|
* |
||||||
|
* <p>与领星适配器同构:令牌存储与锁由宿主注入,端点与凭据仍随每次调用传入。</p> |
||||||
|
*/ |
||||||
|
public final class XincangAdapterFactory implements WarehouseAdapterFactory { |
||||||
|
|
||||||
|
private final TokenStore tokenStore; |
||||||
|
private final LockProvider lockProvider; |
||||||
|
private final Clock clock; |
||||||
|
|
||||||
|
public XincangAdapterFactory(TokenStore tokenStore, LockProvider lockProvider, Clock clock) { |
||||||
|
this.tokenStore = tokenStore; |
||||||
|
this.lockProvider = lockProvider; |
||||||
|
this.clock = clock; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public String adapterId() { |
||||||
|
return XincangConstants.ADAPTER_ID; |
||||||
|
} |
||||||
|
|
||||||
|
@Override |
||||||
|
public WarehouseProvider provider() { |
||||||
|
return WarehouseProvider.XINCANG; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 端点与凭据由调用方在每次请求时传入,工厂只装配协议与基础设施。 |
||||||
|
*/ |
||||||
|
@Override |
||||||
|
public WarehouseAdapter create(AdapterConfig config) { |
||||||
|
return new XincangAdapter( |
||||||
|
new OkHttpTransport("common-ecommerce/1.0.0 (xincang)"), |
||||||
|
new JacksonJsonCodec(), |
||||||
|
tokenStore, lockProvider, clock); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,130 @@ |
|||||||
|
package common.ecommerce.xincang.auth; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.HttpTransport; |
||||||
|
import common.ecommerce.http.JsonCodec; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.warehouse.error.WarehouseException; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import common.ecommerce.xincang.dto.XincangDtos; |
||||||
|
import common.ecommerce.xincang.http.XincangEnvelope; |
||||||
|
import common.ecommerce.xincang.http.XincangRateLimiter; |
||||||
|
import common.ecommerce.xincang.http.XincangRequestFactory; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.LocalDateTime; |
||||||
|
import java.time.format.DateTimeFormatter; |
||||||
|
import java.time.format.DateTimeParseException; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓登录接口({@code GET /api.login})。 |
||||||
|
* |
||||||
|
* <p>文档(Apifox「OMS接口文档V2」)确认:query 参数 {@code appkey} / {@code secret}, |
||||||
|
* 响应 {@code rst} 直接给出 {@code token} 与 {@code token_expire_time}(北京时间 |
||||||
|
* {@code yyyy-MM-dd HH:mm:ss}),有效期 2 小时。<b>没有 refresh 接口</b>,过期只能重新登录; |
||||||
|
* 续期由 {@code TokenManager} 提前刷新完成。</p> |
||||||
|
* |
||||||
|
* <p>token 是客户级(同一 appkey 下多仓共用),后续业务请求把它放在 query 参数 |
||||||
|
* {@code token} 里,不是 {@code Authorization} 头。</p> |
||||||
|
*/ |
||||||
|
public final class XincangTokenClient { |
||||||
|
|
||||||
|
private static final String OP_FETCH = "token.fetch"; |
||||||
|
|
||||||
|
/** 文档给的时间格式,按北京时间解释。 */ |
||||||
|
private static final DateTimeFormatter EXPIRE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
||||||
|
|
||||||
|
private final HttpTransport transport; |
||||||
|
private final JsonCodec json; |
||||||
|
private final XincangRequestFactory requestFactory; |
||||||
|
private final XincangRateLimiter rateLimiter; |
||||||
|
private final Clock clock; |
||||||
|
|
||||||
|
public XincangTokenClient(HttpTransport transport, JsonCodec json, Clock clock) { |
||||||
|
this(transport, json, clock, new XincangRateLimiter()); |
||||||
|
} |
||||||
|
|
||||||
|
public XincangTokenClient(HttpTransport transport, JsonCodec json, Clock clock, |
||||||
|
XincangRateLimiter rateLimiter) { |
||||||
|
this.transport = transport; |
||||||
|
this.json = json; |
||||||
|
this.clock = clock; |
||||||
|
this.requestFactory = new XincangRequestFactory(json); |
||||||
|
this.rateLimiter = rateLimiter; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 登录换取令牌。端点由调用方每次传入,与其它接口一致。 |
||||||
|
* |
||||||
|
* @param baseUrl 本次调用的基址({@code WarehouseConnection.endpointBaseUrl()}) |
||||||
|
* @param appKey 登录 appkey |
||||||
|
* @param appSecret 登录 secret |
||||||
|
* @return 令牌;{@code expiresAt} 已按响应里的 {@code token_expire_time} 折算成 UTC |
||||||
|
*/ |
||||||
|
public AccessToken fetch(String baseUrl, String appKey, String appSecret) { |
||||||
|
rateLimiter.acquire(XincangConstants.PATH_LOGIN, XincangConstants.PERMITS_PER_SECOND); |
||||||
|
HttpRequest req = requestFactory.login(baseUrl, appKey, appSecret, OP_FETCH); |
||||||
|
HttpResponse resp = transport.execute(req); |
||||||
|
|
||||||
|
XincangEnvelope envelope = XincangEnvelope.of(resp, json, OP_FETCH, null); |
||||||
|
XincangDtos.LoginResponse login = json.fromJson(envelope.body(), XincangDtos.LoginResponse.class); |
||||||
|
XincangDtos.LoginResult result = login == null ? null : login.rst; |
||||||
|
|
||||||
|
String token = result == null ? null : result.token; |
||||||
|
if (token == null || token.trim().isEmpty()) { |
||||||
|
throw validation(envelope.platformTraceId(), "xincang login response has no rst.token", |
||||||
|
envelope.body()); |
||||||
|
} |
||||||
|
|
||||||
|
return AccessToken.builder() |
||||||
|
.value(token.trim()) |
||||||
|
.expiresAt(expiresAt(result.tokenExpireTime, envelope)) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 过期时刻。 |
||||||
|
* |
||||||
|
* <p>字段缺失 / 空白时按文档写明的 2 小时兜底;字段存在但格式不对则直接失败—— |
||||||
|
* 那说明报文和文档不一致,静默兜底会把续期时间算错。</p> |
||||||
|
*/ |
||||||
|
private Instant expiresAt(String raw, XincangEnvelope envelope) { |
||||||
|
if (raw == null || raw.trim().isEmpty()) { |
||||||
|
return Instant.now(clock).plusSeconds(XincangConstants.DEFAULT_TOKEN_TTL_SECONDS); |
||||||
|
} |
||||||
|
try { |
||||||
|
LocalDateTime local = LocalDateTime.parse(raw.trim(), EXPIRE_FORMAT); |
||||||
|
return local.atZone(XincangConstants.SYSTEM_ZONE).toInstant(); |
||||||
|
} catch (DateTimeParseException e) { |
||||||
|
// ChannelException.Builder.build() 只返回 ChannelException,没有 build(cause) 重载;
|
||||||
|
// 解析失败本身不带嵌套异常,靠 message 说明原因即可
|
||||||
|
throw validation(envelope.platformTraceId(), |
||||||
|
"xincang token_expire_time is not yyyy-MM-dd HH:mm:ss: " + raw, envelope.body()); |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private static ValidationException validation(String traceId, String message, String body) { |
||||||
|
return new ValidationException(base(traceId) |
||||||
|
.message(message) |
||||||
|
.rawResponse(truncate(body))); |
||||||
|
} |
||||||
|
|
||||||
|
private static WarehouseException.Builder base(String traceId) { |
||||||
|
return WarehouseException.builder() |
||||||
|
.operation(OP_FETCH) |
||||||
|
.provider(XincangConstants.ADAPTER_ID) |
||||||
|
.platformRequestId(traceId) |
||||||
|
.retryable(false); |
||||||
|
} |
||||||
|
|
||||||
|
private static String truncate(String body) { |
||||||
|
if (body == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
// 登录响应含 token 与 api_client_secret,异常里只留很短一段便于定位于字段层面
|
||||||
|
return body.length() <= 300 ? body : body.substring(0, 300) + "..."; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,68 @@ |
|||||||
|
package common.ecommerce.xincang.dto; |
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; |
||||||
|
import com.fasterxml.jackson.annotation.JsonProperty; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓报文结构。 |
||||||
|
* |
||||||
|
* <p>字段名以 Apifox「OMS接口文档V2」为准。信仓全局响应外层统一为 |
||||||
|
* {@code {"rst": ..., "errno": 0, "err": "", "trace_id": "..."}},这里只放登录接口用到的部分。 |
||||||
|
* 字段差异只改本类,不动适配器与领域模型。</p> |
||||||
|
*/ |
||||||
|
public final class XincangDtos { |
||||||
|
|
||||||
|
private XincangDtos() { |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 登录响应({@code GET /api.login})。 |
||||||
|
* |
||||||
|
* <p>注意与业务接口不同:登录的 {@code rst} <b>没有</b> {@code code/msg/data} 包裹, |
||||||
|
* 而是直接给出客户与 token 字段。</p> |
||||||
|
*/ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class LoginResponse { |
||||||
|
|
||||||
|
/** 登录结果;业务失败时可能为 null。 */ |
||||||
|
@JsonProperty("rst") |
||||||
|
public LoginResult rst; |
||||||
|
|
||||||
|
/** 0 表示成功。 */ |
||||||
|
@JsonProperty("errno") |
||||||
|
public Integer errno; |
||||||
|
|
||||||
|
/** 错误描述;成功时为空串。 */ |
||||||
|
@JsonProperty("err") |
||||||
|
public String err; |
||||||
|
|
||||||
|
/** 信仓侧链路号。 */ |
||||||
|
@JsonProperty("trace_id") |
||||||
|
public String traceId; |
||||||
|
} |
||||||
|
|
||||||
|
/** 登录结果的 {@code rst} 部分。 */ |
||||||
|
@JsonIgnoreProperties(ignoreUnknown = true) |
||||||
|
public static final class LoginResult { |
||||||
|
|
||||||
|
/** 客户 id。 */ |
||||||
|
@JsonProperty("id") |
||||||
|
public String customerId; |
||||||
|
|
||||||
|
/** 回显的 APIKEY,正常等于登录用的 appkey。 */ |
||||||
|
@JsonProperty("api_client_id") |
||||||
|
public String apiClientId; |
||||||
|
|
||||||
|
/** 回显的 APISECRET;不需要也不应落盘,仅用于排障时核对身份。 */ |
||||||
|
@JsonProperty("api_client_secret") |
||||||
|
public String apiClientSecret; |
||||||
|
|
||||||
|
/** 过期时间,北京时间 {@code yyyy-MM-dd HH:mm:ss}。 */ |
||||||
|
@JsonProperty("token_expire_time") |
||||||
|
public String tokenExpireTime; |
||||||
|
|
||||||
|
/** 令牌本体(形如 {@code {D0A7A4FB-...}})。 */ |
||||||
|
@JsonProperty("token") |
||||||
|
public String token; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,169 @@ |
|||||||
|
package common.ecommerce.xincang.http; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpResponse; |
||||||
|
import common.ecommerce.http.JsonCodec; |
||||||
|
import common.ecommerce.shared.error.AuthException; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.error.PlatformBusinessException; |
||||||
|
import common.ecommerce.shared.error.RateLimitException; |
||||||
|
import common.ecommerce.shared.error.TransientException; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓响应信封校验。 |
||||||
|
* |
||||||
|
* <p>信仓统一外层(Apifox「OMS接口文档V2」):</p> |
||||||
|
* <pre> |
||||||
|
* { "rst": ..., "errno": 0, "err": "", "trace_id": "..." } |
||||||
|
* </pre> |
||||||
|
* |
||||||
|
* <p>两条成功判定:顶层 {@code errno} 为 0;业务接口的 {@code rst} 是 |
||||||
|
* {@code {"code":"0","msg":"","data":...}} 时还要求 {@code rst.code} 为 {@code "0"}。 |
||||||
|
* 登录是例外——它的 {@code rst} 直接是客户 / token 字段,没有 {@code code},缺失即视为通过。</p> |
||||||
|
* |
||||||
|
* <p>HTTP 401/403/429/5xx 仍按 HTTP 语义映射:网关或代理层直接拒绝时也要能正确分类。</p> |
||||||
|
*/ |
||||||
|
public final class XincangEnvelope { |
||||||
|
|
||||||
|
/** 原始响应体。 */ |
||||||
|
private final String rawBody; |
||||||
|
/** 信仓侧链路号 {@code trace_id};可能为 null。 */ |
||||||
|
private final String platformTraceId; |
||||||
|
|
||||||
|
private XincangEnvelope(String rawBody, String platformTraceId) { |
||||||
|
this.rawBody = rawBody; |
||||||
|
this.platformTraceId = platformTraceId; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 校验 HTTP 状态与业务码。 |
||||||
|
* |
||||||
|
* @param response 传输层响应 |
||||||
|
* @param json 用于读 {@code errno} / {@code rst.code} / {@code trace_id} |
||||||
|
* @param operation 门面操作名,如 {@code token.fetch} |
||||||
|
* @param requestId 我方链路 ID |
||||||
|
* @throws AuthException 401 / 403 |
||||||
|
* @throws RateLimitException 429 |
||||||
|
* @throws TransientException 5xx |
||||||
|
* @throws ValidationException 其它非 2xx,或报文结构不符合预期 |
||||||
|
* @throws PlatformBusinessException errno 非 0,或 rst.code 非 0 |
||||||
|
*/ |
||||||
|
public static XincangEnvelope of(HttpResponse response, JsonCodec json, String operation, |
||||||
|
String requestId) { |
||||||
|
int status = response.statusCode(); |
||||||
|
if (status == 401 || status == 403) { |
||||||
|
throw new AuthException(base(operation, requestId) |
||||||
|
.message("xincang auth failed: http " + status) |
||||||
|
.platformCode(String.valueOf(status)) |
||||||
|
.rawResponse(truncate(response.body())) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
if (status == 429) { |
||||||
|
throw new RateLimitException(base(operation, requestId) |
||||||
|
.message("xincang rate limited") |
||||||
|
.platformCode(String.valueOf(status)) |
||||||
|
.retryable(true), retryAfterMillis(response)); |
||||||
|
} |
||||||
|
if (status >= 500) { |
||||||
|
throw new TransientException(base(operation, requestId) |
||||||
|
.message("xincang server error: http " + status) |
||||||
|
.platformCode(String.valueOf(status)) |
||||||
|
.retryable(true), null); |
||||||
|
} |
||||||
|
if (status < 200 || status >= 300) { |
||||||
|
throw new ValidationException(base(operation, requestId) |
||||||
|
.message("xincang request rejected: http " + status) |
||||||
|
.platformCode(String.valueOf(status)) |
||||||
|
.rawResponse(truncate(response.body())) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
|
||||||
|
String body = response.body(); |
||||||
|
if (body == null || body.trim().isEmpty()) { |
||||||
|
throw new ValidationException(base(operation, requestId) |
||||||
|
.message("xincang returned an empty body") |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
|
||||||
|
String traceId = json.stringAt(body, "trace_id"); |
||||||
|
String errno = json.stringAt(body, "errno"); |
||||||
|
if (errno == null || errno.trim().isEmpty()) { |
||||||
|
throw new ValidationException(base(operation, requestId) |
||||||
|
.message("xincang response has no errno") |
||||||
|
.platformRequestId(traceId) |
||||||
|
.rawResponse(truncate(body)) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
if (!XincangConstants.SUCCESS_ERRNO.equals(errno.trim())) { |
||||||
|
throw new PlatformBusinessException(base(operation, requestId) |
||||||
|
.message("xincang business error: errno=" + errno |
||||||
|
+ ", err=" + json.stringAt(body, "err")) |
||||||
|
.platformCode(errno.trim()) |
||||||
|
.platformRequestId(traceId) |
||||||
|
.rawResponse(truncate(body)) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
|
||||||
|
String rstCode = json.stringAt(body, "rst.code"); |
||||||
|
if (rstCode != null && !XincangConstants.SUCCESS_RST_CODE.equals(rstCode.trim())) { |
||||||
|
throw new PlatformBusinessException(base(operation, requestId) |
||||||
|
.message("xincang business error: rst.code=" + rstCode |
||||||
|
+ ", rst.msg=" + json.stringAt(body, "rst.msg")) |
||||||
|
.platformCode(rstCode.trim()) |
||||||
|
.platformRequestId(traceId) |
||||||
|
.rawResponse(truncate(body)) |
||||||
|
.retryable(false)); |
||||||
|
} |
||||||
|
return new XincangEnvelope(body, traceId); |
||||||
|
} |
||||||
|
|
||||||
|
/** 原始响应体;不会是 null。 */ |
||||||
|
public String body() { |
||||||
|
return rawBody; |
||||||
|
} |
||||||
|
|
||||||
|
/** 信仓侧链路号 {@code trace_id};可能为 null。 */ |
||||||
|
public String platformTraceId() { |
||||||
|
return platformTraceId; |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 统一异常字段。 |
||||||
|
* |
||||||
|
* <p>返回 {@link ChannelException.Builder} 而不是 {@code WarehouseException.Builder}: |
||||||
|
* 仓库域的自定义异常仅有 {@code WarehouseException} 一个,其余分类(Auth / RateLimit / |
||||||
|
* Transient / Validation / PlatformBusiness)的构造器都收 {@code ChannelException.Builder}。</p> |
||||||
|
* |
||||||
|
* <p>{@code warehouseCode} 保留在签名里便于调用方一致传参,但 <b>不</b>写进 |
||||||
|
* {@code omsStoreId}——那是渠道域的店铺 ID,填仓编码会污染审计字段。 |
||||||
|
* 需要仓维度的错误请由适配器层包一层 {@code WarehouseException}。</p> |
||||||
|
*/ |
||||||
|
private static ChannelException.Builder base(String operation, |
||||||
|
String requestId) { |
||||||
|
return ChannelException.builder() |
||||||
|
.operation(operation) |
||||||
|
.provider(XincangConstants.ADAPTER_ID) |
||||||
|
.requestId(requestId); |
||||||
|
} |
||||||
|
|
||||||
|
/** {@code Retry-After} 秒折算毫秒;缺失按 1s。 */ |
||||||
|
private static long retryAfterMillis(HttpResponse response) { |
||||||
|
String header = response.header("Retry-After"); |
||||||
|
if (header == null || header.trim().isEmpty()) { |
||||||
|
return 1000L; |
||||||
|
} |
||||||
|
try { |
||||||
|
return Math.max(0L, Long.parseLong(header.trim()) * 1000L); |
||||||
|
} catch (NumberFormatException e) { |
||||||
|
return 1000L; |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private static String truncate(String body) { |
||||||
|
if (body == null) { |
||||||
|
return null; |
||||||
|
} |
||||||
|
return body.length() <= 2000 ? body : body.substring(0, 2000) + "..."; |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,57 @@ |
|||||||
|
package common.ecommerce.xincang.http; |
||||||
|
|
||||||
|
import java.util.HashMap; |
||||||
|
import java.util.Map; |
||||||
|
import java.util.function.LongSupplier; |
||||||
|
|
||||||
|
/** |
||||||
|
* 按接口路径的令牌桶。 |
||||||
|
* |
||||||
|
* <p>信仓文档未公开限流值,先按保守默认 {@code XincangConstants.PERMITS_PER_SECOND} 节流; |
||||||
|
* 429 的 {@code Retry-After} 由宿主处理,这里只做本地限速。</p> |
||||||
|
* |
||||||
|
* <p>进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。 |
||||||
|
* 与领星限流器同构,可注入 {@link Sleeper} 与纳秒时钟,便于测试。</p> |
||||||
|
*/ |
||||||
|
public final class XincangRateLimiter { |
||||||
|
|
||||||
|
/** 便于测试注入,生产用 {@link Thread#sleep}。 */ |
||||||
|
public interface Sleeper { |
||||||
|
void sleep(long millis, int nanos); |
||||||
|
} |
||||||
|
|
||||||
|
private final Map<String, Long> nextAllowed = new HashMap<>(); |
||||||
|
private final Sleeper sleeper; |
||||||
|
private final LongSupplier nanoClock; |
||||||
|
|
||||||
|
public XincangRateLimiter() { |
||||||
|
this((millis, nanos) -> { |
||||||
|
try { |
||||||
|
Thread.sleep(millis, nanos); |
||||||
|
} catch (InterruptedException e) { |
||||||
|
Thread.currentThread().interrupt(); |
||||||
|
} |
||||||
|
}, System::nanoTime); |
||||||
|
} |
||||||
|
|
||||||
|
public XincangRateLimiter(Sleeper sleeper, LongSupplier nanoClock) { |
||||||
|
this.sleeper = sleeper; |
||||||
|
this.nanoClock = nanoClock; |
||||||
|
} |
||||||
|
|
||||||
|
/** 同一路径两次调用之间至少间隔 {@code 1e9 / permitsPerSecond} 纳秒。 */ |
||||||
|
public synchronized void acquire(String path, int permitsPerSecond) { |
||||||
|
if (permitsPerSecond <= 0) { |
||||||
|
return; |
||||||
|
} |
||||||
|
long interval = 1_000_000_000L / permitsPerSecond; |
||||||
|
long now = nanoClock.getAsLong(); |
||||||
|
Long next = nextAllowed.get(path); |
||||||
|
if (next != null && now < next) { |
||||||
|
long wait = next - now; |
||||||
|
sleeper.sleep(wait / 1_000_000L, (int) (wait % 1_000_000L)); |
||||||
|
now = nanoClock.getAsLong(); |
||||||
|
} |
||||||
|
nextAllowed.put(path, now + interval); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,114 @@ |
|||||||
|
package common.ecommerce.xincang.http; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.JsonCodec; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
|
||||||
|
import java.io.UnsupportedEncodingException; |
||||||
|
import java.net.URLEncoder; |
||||||
|
import java.util.Collection; |
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
/** |
||||||
|
* 构造信仓请求。 |
||||||
|
* |
||||||
|
* <p>鉴权是「登录换 token + 每次业务请求带 query 参数 {@code token}」(文档对所有业务接口 |
||||||
|
* 都把 {@code token} 列为必填 query 参数),因此不走 {@code Authorization} 头。 |
||||||
|
* 凭据复用 {@link ChannelSecret#appKey()} / {@link ChannelSecret#appSecret()}。</p> |
||||||
|
*/ |
||||||
|
public final class XincangRequestFactory { |
||||||
|
|
||||||
|
private final JsonCodec json; |
||||||
|
|
||||||
|
public XincangRequestFactory(JsonCodec json) { |
||||||
|
this.json = json; |
||||||
|
} |
||||||
|
|
||||||
|
/** 登录:{@code GET /api.login?appkey=&secret=}。 */ |
||||||
|
public HttpRequest login(String baseUrl, String appKey, String appSecret, String operation) { |
||||||
|
Map<String, Object> query = new LinkedHashMap<>(); |
||||||
|
query.put(XincangConstants.QUERY_APP_KEY, requireText(appKey, |
||||||
|
"xincang requires ChannelSecret.appKey()")); |
||||||
|
query.put(XincangConstants.QUERY_APP_SECRET, requireText(appSecret, |
||||||
|
"xincang requires ChannelSecret.appSecret()")); |
||||||
|
return get(baseUrl, XincangConstants.PATH_LOGIN, query, operation); |
||||||
|
} |
||||||
|
|
||||||
|
/** GET:业务参数全部放 query。 */ |
||||||
|
public HttpRequest get(String baseUrl, String path, Map<String, Object> params, String operation) { |
||||||
|
StringBuilder url = new StringBuilder(trimTrailingSlash(baseUrl)).append(path); |
||||||
|
if (params != null && !params.isEmpty()) { |
||||||
|
url.append('?'); |
||||||
|
boolean first = true; |
||||||
|
for (Map.Entry<String, Object> e : params.entrySet()) { |
||||||
|
if (e.getValue() == null) { |
||||||
|
continue; |
||||||
|
} |
||||||
|
if (!first) { |
||||||
|
url.append('&'); |
||||||
|
} |
||||||
|
url.append(urlEncode(e.getKey())).append('=').append(urlEncode(stringify(e.getValue()))); |
||||||
|
first = false; |
||||||
|
} |
||||||
|
} |
||||||
|
return HttpRequest.builder() |
||||||
|
.method("GET") |
||||||
|
.url(url.toString()) |
||||||
|
.operation(operation) |
||||||
|
.build(); |
||||||
|
} |
||||||
|
|
||||||
|
/** |
||||||
|
* 业务 GET:在 {@code params} 上补 {@code token}。 |
||||||
|
* |
||||||
|
* <p>后续接口(订单 / 库存 / 预报)都要求 token 作为 query 参数,这个方法集中处理, |
||||||
|
* 免得各 Source 各写一遍。本轮只落地登录,接入业务接口时直接复用。</p> |
||||||
|
*/ |
||||||
|
public HttpRequest getWithToken(String baseUrl, String path, Map<String, Object> params, |
||||||
|
String token, String operation) { |
||||||
|
Map<String, Object> query = new LinkedHashMap<>(); |
||||||
|
if (params != null) { |
||||||
|
query.putAll(params); |
||||||
|
} |
||||||
|
query.put(XincangConstants.QUERY_TOKEN, requireText(token, |
||||||
|
"xincang requires a token; call login first")); |
||||||
|
return get(baseUrl, path, query, operation); |
||||||
|
} |
||||||
|
|
||||||
|
/** 集合 / 对象按 JSON 序列化,其余按字符串。 */ |
||||||
|
private String stringify(Object value) { |
||||||
|
if (value instanceof Collection || value instanceof Map) { |
||||||
|
return json.toJson(value); |
||||||
|
} |
||||||
|
return String.valueOf(value); |
||||||
|
} |
||||||
|
|
||||||
|
private static String requireText(String value, String message) { |
||||||
|
if (value == null || value.trim().isEmpty()) { |
||||||
|
throw new IllegalStateException(message); |
||||||
|
} |
||||||
|
return value.trim(); |
||||||
|
} |
||||||
|
|
||||||
|
private static String trimTrailingSlash(String url) { |
||||||
|
if (url == null || url.trim().isEmpty()) { |
||||||
|
throw new IllegalStateException("xincang endpointBaseUrl must not be blank"); |
||||||
|
} |
||||||
|
String trimmed = url.trim(); |
||||||
|
int end = trimmed.length(); |
||||||
|
while (end > 0 && trimmed.charAt(end - 1) == '/') { |
||||||
|
end--; |
||||||
|
} |
||||||
|
return trimmed.substring(0, end); |
||||||
|
} |
||||||
|
|
||||||
|
private static String urlEncode(String v) { |
||||||
|
try { |
||||||
|
return URLEncoder.encode(v == null ? "" : v, "UTF-8"); |
||||||
|
} catch (UnsupportedEncodingException e) { |
||||||
|
throw new IllegalStateException(e); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,124 @@ |
|||||||
|
package common.ecommerce.xincang.adapter; |
||||||
|
|
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||||
|
import common.ecommerce.shared.testkit.MutableClock; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.warehouse.WarehouseCapability; |
||||||
|
import common.ecommerce.warehouse.WarehouseProvider; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import org.junit.jupiter.api.BeforeEach; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Duration; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓适配器令牌缓存:登录只发一次、到期前提前续期、按 appkey 隔离缓存。 |
||||||
|
*/ |
||||||
|
class XincangAdapterTest { |
||||||
|
|
||||||
|
private static final String BASE = XincangConstants.TEST_BASE_URL; |
||||||
|
private static final String APP_KEY = "ak-1"; |
||||||
|
|
||||||
|
private RecordingTransport transport; |
||||||
|
private InMemoryTokenStore tokens; |
||||||
|
private InMemoryLockProvider locks; |
||||||
|
private MutableClock clock; |
||||||
|
|
||||||
|
@BeforeEach |
||||||
|
void setUp() { |
||||||
|
transport = RecordingTransport.create(); |
||||||
|
tokens = new InMemoryTokenStore(); |
||||||
|
locks = new InMemoryLockProvider(); |
||||||
|
clock = MutableClock.atUtc("2026-11-09T00:00:00Z"); |
||||||
|
} |
||||||
|
|
||||||
|
/** 每次登录都返回一个新 token,并给 2 小时有效期(北京时间)。 */ |
||||||
|
private XincangAdapter adapter() { |
||||||
|
int[] sequence = {0}; |
||||||
|
transport.route(XincangConstants.PATH_LOGIN, req -> { |
||||||
|
sequence[0]++; |
||||||
|
return Responses.ok("{\"rst\":{\"id\":\"c-1\",\"token\":\"{T-" + sequence[0] + "}\"," |
||||||
|
+ "\"token_expire_time\":\"" + beijing(clock) + "\"}," |
||||||
|
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"trace-" + sequence[0] + "\"}"); |
||||||
|
}); |
||||||
|
return new XincangAdapter(transport, new common.ecommerce.http.JacksonJsonCodec(), |
||||||
|
tokens, locks, clock); |
||||||
|
} |
||||||
|
|
||||||
|
/** 当前时钟 + 2 小时,按北京时间 {@code yyyy-MM-dd HH:mm:ss} 输出。 */ |
||||||
|
private static String beijing(MutableClock clock) { |
||||||
|
return java.time.LocalDateTime.ofInstant(clock.instant().plus(Duration.ofHours(2)), |
||||||
|
XincangConstants.SYSTEM_ZONE) |
||||||
|
.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); |
||||||
|
} |
||||||
|
|
||||||
|
private static WarehouseContext ctx(String appKey) { |
||||||
|
return WarehouseContext.of("XC-CA-3790", WarehouseProvider.XINCANG, "CA-3790", |
||||||
|
WarehouseConnection.of(BASE, ChannelSecret.builder() |
||||||
|
.appKey(appKey).appSecret("sk").build()), |
||||||
|
"req-1", java.time.Clock.systemUTC()); |
||||||
|
} |
||||||
|
|
||||||
|
private static int loginCount(RecordingTransport transport) { |
||||||
|
int n = 0; |
||||||
|
for (common.ecommerce.http.HttpRequest req : transport.recorded()) { |
||||||
|
if (req.url().contains(XincangConstants.PATH_LOGIN)) { |
||||||
|
n++; |
||||||
|
} |
||||||
|
} |
||||||
|
return n; |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void secondLoginReusesCachedToken() { |
||||||
|
XincangAdapter adapter = adapter(); |
||||||
|
|
||||||
|
String first = adapter.login(ctx(APP_KEY)).value(); |
||||||
|
String second = adapter.login(ctx(APP_KEY)).value(); |
||||||
|
|
||||||
|
assertEquals(first, second); |
||||||
|
assertEquals(1, loginCount(transport), "第二次登录必须命中缓存"); |
||||||
|
assertEquals(1, locks.acquireCount("token-refresh:" + XincangConstants.ADAPTER_ID + ":" + APP_KEY)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void refreshesInsideEarlyWindow() { |
||||||
|
XincangAdapter adapter = adapter(); |
||||||
|
String first = adapter.login(ctx(APP_KEY)).value(); |
||||||
|
|
||||||
|
// 2h 有效期,提前 10 分钟续期:推进到 1h50m 后应重新登录
|
||||||
|
clock.advance(Duration.ofMinutes(110)); |
||||||
|
String second = adapter.login(ctx(APP_KEY)).value(); |
||||||
|
|
||||||
|
assertNotEquals(first, second, "进入提前续期窗口后必须换新 token"); |
||||||
|
assertEquals(2, loginCount(transport)); |
||||||
|
assertEquals(2, tokens.saveCount()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void tokenCacheIsPerAppKey() { |
||||||
|
XincangAdapter adapter = adapter(); |
||||||
|
|
||||||
|
adapter.login(ctx("ak-1")); |
||||||
|
adapter.login(ctx("ak-2")); |
||||||
|
|
||||||
|
assertEquals(2, loginCount(transport), "不同 appkey 各自登录"); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void capabilitiesAreEmptyUntilBusinessApisLand() { |
||||||
|
XincangAdapter adapter = adapter(); |
||||||
|
|
||||||
|
assertEquals(WarehouseProvider.XINCANG, adapter.provider()); |
||||||
|
assertEquals(XincangConstants.ADAPTER_ID, adapter.adapterId()); |
||||||
|
assertTrue(adapter.capabilities().isEmpty(), "本期只做登录,不声明任何能力位"); |
||||||
|
assertFalse(adapter.supports("XC-CA-3790", WarehouseCapability.OUTBOUND)); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,153 @@ |
|||||||
|
package common.ecommerce.xincang.auth; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.shared.error.AuthException; |
||||||
|
import common.ecommerce.shared.error.PlatformBusinessException; |
||||||
|
import common.ecommerce.shared.error.ValidationException; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.shared.testkit.RecordingTransport; |
||||||
|
import common.ecommerce.shared.testkit.Responses; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
import java.time.Instant; |
||||||
|
import java.time.ZoneOffset; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓登录契约测试:请求形状、token / 过期时间解析、错误分类。 |
||||||
|
* |
||||||
|
* <p>请求与响应都按 Apifox「OMS接口文档V2」的真实报文构造,无需网络。</p> |
||||||
|
*/ |
||||||
|
class XincangTokenClientTest { |
||||||
|
|
||||||
|
private static final String BASE = "http://test.api.oms.13u3.com/oms"; |
||||||
|
/** |
||||||
|
* 测试用占位凭据。 |
||||||
|
* |
||||||
|
* <p>真实凭据(含文档里的测试 appkey/secret)一律不入库:联调用 |
||||||
|
* {@code XincangLoginProbeTest} 走系统属性传入。</p> |
||||||
|
*/ |
||||||
|
private static final String APP_KEY = "test-appkey"; |
||||||
|
private static final String APP_SECRET = "test-secret"; |
||||||
|
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-09T00:00:00Z"), ZoneOffset.UTC); |
||||||
|
|
||||||
|
/** 文档「成功示例」原文;token_expire_time 是北京时间。 */ |
||||||
|
private static final String OK_BODY = "{" |
||||||
|
+ "\"rst\":{" |
||||||
|
+ "\"id\":\"120421451252766436\"," |
||||||
|
+ "\"api_client_id\":\"86159e50d22f31388b31ad135ff1174b\"," |
||||||
|
+ "\"api_client_secret\":\"RRWd7TeKJoMpoMvYZ0lpTkuYc7EgR4a0q18gE8Yn0cf03df7\"," |
||||||
|
+ "\"token_expire_time\":\"2026-10-14 09:34:09\"," |
||||||
|
+ "\"token\":\"{D0A7A4FB-6461-5EA4-194B-F273F1E87BFA}\"" |
||||||
|
+ "}," |
||||||
|
+ "\"errno\":0," |
||||||
|
+ "\"err\":\"\"," |
||||||
|
+ "\"trace_id\":\"005cbead-44f7-450d-9ed8-e1e65fbbb6e5\"" |
||||||
|
+ "}"; |
||||||
|
|
||||||
|
private static XincangTokenClient client(RecordingTransport transport) { |
||||||
|
return new XincangTokenClient(transport, new JacksonJsonCodec(), CLOCK); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void sendsGetWithCredentialsInQuery() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok(OK_BODY)); |
||||||
|
|
||||||
|
client(transport).fetch(BASE, APP_KEY, APP_SECRET); |
||||||
|
|
||||||
|
HttpRequest req = transport.recorded().get(0); |
||||||
|
assertEquals("GET", req.method()); |
||||||
|
assertTrue(req.url().startsWith(BASE + XincangConstants.PATH_LOGIN + "?"), req.url()); |
||||||
|
assertTrue(req.url().contains("appkey=" + APP_KEY), req.url()); |
||||||
|
assertTrue(req.url().contains("secret=" + APP_SECRET), req.url()); |
||||||
|
// 信仓把 token 放 query,不发 Authorization 头
|
||||||
|
assertFalse(req.headers().containsKey("Authorization"), req.headers().toString()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void parsesTokenAndBeijingExpiryToUtc() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok(OK_BODY)); |
||||||
|
|
||||||
|
AccessToken token = client(transport).fetch(BASE, APP_KEY, APP_SECRET); |
||||||
|
|
||||||
|
assertEquals("{D0A7A4FB-6461-5EA4-194B-F273F1E87BFA}", token.value()); |
||||||
|
// 2026-10-14 09:34:09 北京时间 = 2026-10-14T01:34:09Z
|
||||||
|
assertEquals(Instant.parse("2026-10-14T01:34:09Z"), token.expiresAt()); |
||||||
|
// 登录没有 refresh 机制
|
||||||
|
assertNull(token.refreshToken()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingTokenFailsInsteadOfReturningBlank() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||||
|
"{\"rst\":{\"id\":\"1\",\"token_expire_time\":\"2026-10-14 09:34:09\"}," |
||||||
|
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-1\"}")); |
||||||
|
|
||||||
|
ValidationException e = assertThrows(ValidationException.class, |
||||||
|
() -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); |
||||||
|
assertTrue(e.getMessage().contains("rst.token"), e.getMessage()); |
||||||
|
assertEquals("t-1", e.platformRequestId()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void malformedExpiryFailsInsteadOfGuessing() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||||
|
"{\"rst\":{\"token\":\"{T-1}\",\"token_expire_time\":\"2026/10/14 09:34\"}," |
||||||
|
+ "\"errno\":0,\"err\":\"\",\"trace_id\":\"t-2\"}")); |
||||||
|
|
||||||
|
ValidationException e = assertThrows(ValidationException.class, |
||||||
|
() -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); |
||||||
|
assertTrue(e.getMessage().contains("token_expire_time"), e.getMessage()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingExpiryFallsBackToDocumentedTwoHours() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||||
|
"{\"rst\":{\"token\":\"{T-2}\"},\"errno\":0,\"err\":\"\",\"trace_id\":\"t-3\"}")); |
||||||
|
|
||||||
|
AccessToken token = client(transport).fetch(BASE, APP_KEY, APP_SECRET); |
||||||
|
|
||||||
|
assertEquals(Instant.parse("2026-11-09T02:00:00Z"), token.expiresAt()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void nonzeroErrnoIsBusinessErrorWithTraceId() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.ok( |
||||||
|
"{\"rst\":null,\"errno\":1001,\"err\":\"secret error\"," |
||||||
|
+ "\"trace_id\":\"t-4\"}")); |
||||||
|
|
||||||
|
PlatformBusinessException e = assertThrows(PlatformBusinessException.class, |
||||||
|
() -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); |
||||||
|
assertTrue(e.getMessage().contains("errno=1001"), e.getMessage()); |
||||||
|
assertTrue(e.getMessage().contains("secret error"), e.getMessage()); |
||||||
|
assertEquals("t-4", e.platformRequestId()); |
||||||
|
assertEquals("1001", e.platformCode()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void http401IsAuthFailure() { |
||||||
|
RecordingTransport transport = RecordingTransport.create() |
||||||
|
.route(XincangConstants.PATH_LOGIN, req -> Responses.status(401, "")); |
||||||
|
|
||||||
|
assertThrows(AuthException.class, () -> client(transport).fetch(BASE, APP_KEY, APP_SECRET)); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void blankCredentialsFailBeforeSending() { |
||||||
|
RecordingTransport transport = RecordingTransport.create(); |
||||||
|
|
||||||
|
assertThrows(IllegalStateException.class, |
||||||
|
() -> client(transport).fetch(BASE, " ", APP_SECRET)); |
||||||
|
assertEquals(0, transport.recorded().size()); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,54 @@ |
|||||||
|
package common.ecommerce.xincang.http; |
||||||
|
|
||||||
|
import common.ecommerce.http.HttpRequest; |
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
|
||||||
|
import java.util.LinkedHashMap; |
||||||
|
import java.util.Map; |
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓请求构造:token 放 query、基址末尾斜杠归一、缺 token 直接失败。 |
||||||
|
*/ |
||||||
|
class XincangRequestFactoryTest { |
||||||
|
|
||||||
|
private static final String BASE = "http://test.api.oms.13u3.com/oms/"; |
||||||
|
private final XincangRequestFactory factory = new XincangRequestFactory(new JacksonJsonCodec()); |
||||||
|
|
||||||
|
@Test |
||||||
|
void loginPutsCredentialsInQuery() { |
||||||
|
HttpRequest req = factory.login(BASE, "ak", "sk", "token.fetch"); |
||||||
|
|
||||||
|
assertEquals("GET", req.method()); |
||||||
|
assertEquals("http://test.api.oms.13u3.com/oms" + XincangConstants.PATH_LOGIN |
||||||
|
+ "?appkey=ak&secret=sk", req.url()); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void businessRequestCarriesTokenInQuery() { |
||||||
|
Map<String, Object> params = new LinkedHashMap<>(); |
||||||
|
params.put("page", 1); |
||||||
|
params.put("limit", 20); |
||||||
|
|
||||||
|
HttpRequest req = factory.getWithToken(BASE, "/api.orderlist", params, "{T-1}", "outbound.query"); |
||||||
|
|
||||||
|
assertEquals("http://test.api.oms.13u3.com/oms/api.orderlist?page=1&limit=20&token=%7BT-1%7D", |
||||||
|
req.url()); |
||||||
|
assertFalse(req.headers().containsKey("Authorization")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingTokenFailsBeforeSending() { |
||||||
|
assertThrows(IllegalStateException.class, |
||||||
|
() -> factory.getWithToken(BASE, "/api.orderlist", null, " ", "outbound.query")); |
||||||
|
} |
||||||
|
|
||||||
|
@Test |
||||||
|
void missingAppKeyFailsBeforeSending() { |
||||||
|
assertThrows(IllegalStateException.class, |
||||||
|
() -> factory.login(BASE, "", "sk", "token.fetch")); |
||||||
|
} |
||||||
|
} |
||||||
@ -0,0 +1,103 @@ |
|||||||
|
package common.ecommerce.xincang.probe; |
||||||
|
|
||||||
|
import common.ecommerce.http.JacksonJsonCodec; |
||||||
|
import common.ecommerce.http.OkHttpTransport; |
||||||
|
import common.ecommerce.shared.error.ChannelException; |
||||||
|
import common.ecommerce.shared.spi.AccessToken; |
||||||
|
import common.ecommerce.shared.spi.ChannelSecret; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryLockProvider; |
||||||
|
import common.ecommerce.shared.testkit.InMemoryTokenStore; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseConnection; |
||||||
|
import common.ecommerce.warehouse.sdk.WarehouseContext; |
||||||
|
import common.ecommerce.warehouse.WarehouseProvider; |
||||||
|
import common.ecommerce.xincang.XincangConstants; |
||||||
|
import common.ecommerce.xincang.adapter.XincangAdapter; |
||||||
|
import org.junit.jupiter.api.Assumptions; |
||||||
|
import org.junit.jupiter.api.Test; |
||||||
|
import org.junit.jupiter.api.condition.EnabledIfSystemProperty; |
||||||
|
|
||||||
|
import java.time.Clock; |
||||||
|
|
||||||
|
/** |
||||||
|
* 信仓登录只读探针:核对 {@code GET /api.login} 的真实出入参。 |
||||||
|
* |
||||||
|
* <p>默认跳过,用 {@code -Dxincang.probe=true} 显式开启,凭据走系统属性、 |
||||||
|
* <b>真实凭据不入库</b>:</p> |
||||||
|
* |
||||||
|
* <pre> |
||||||
|
* mvn -pl warehouse-sdk-xincang -am -DfailIfNoTests=false \ |
||||||
|
* -Dxincang.probe=true \ |
||||||
|
* -Dxincang.probe.appKey=你的appkey -Dxincang.probe.appSecret=你的secret \ |
||||||
|
* -Dtest=XincangLoginProbeTest test |
||||||
|
* </pre> |
||||||
|
* |
||||||
|
* <p>可选系统属性:{@code -Dxincang.probe.baseUrl}(默认测试环境 {@code XincangConstants.TEST_BASE_URL}) |
||||||
|
* 与 {@code -Dxincang.probe.warehouseCode}(仅用于日志)。</p> |
||||||
|
* |
||||||
|
* <p><b>只做登录</b>,不调用任何业务接口;输出只打印 token 指纹与过期时间,不打印 token 本体。</p> |
||||||
|
*/ |
||||||
|
@EnabledIfSystemProperty(named = "xincang.probe", matches = "true") |
||||||
|
class XincangLoginProbeTest { |
||||||
|
|
||||||
|
// 真实凭据不入库:本地跑探针时用 -Dxincang.probe.appKey=... -Dxincang.probe.appSecret=...
|
||||||
|
private static final String APP_KEY = System.getProperty("xincang.probe.appKey", ""); |
||||||
|
private static final String APP_SECRET = System.getProperty("xincang.probe.appSecret", ""); |
||||||
|
private static final String BASE_URL = opt("xincang.probe.baseUrl", XincangConstants.TEST_BASE_URL); |
||||||
|
private static final String WAREHOUSE_CODE = opt("xincang.probe.warehouseCode", "XC-PROBE"); |
||||||
|
|
||||||
|
@Test |
||||||
|
void probeLogin() { |
||||||
|
Assumptions.assumeTrue(!APP_KEY.trim().isEmpty() && !APP_SECRET.trim().isEmpty(), |
||||||
|
"未提供 -Dxincang.probe.appKey / -Dxincang.probe.appSecret,跳过登录探针"); |
||||||
|
|
||||||
|
System.out.println("\n================ xincang / api.login ================"); |
||||||
|
System.out.println("[login] baseUrl=" + BASE_URL + " appKey=" + mask()); |
||||||
|
|
||||||
|
XincangAdapter adapter = new XincangAdapter( |
||||||
|
new OkHttpTransport("common-ecommerce-xincang-probe"), |
||||||
|
new JacksonJsonCodec(), |
||||||
|
new InMemoryTokenStore(), new InMemoryLockProvider(), Clock.systemUTC()); |
||||||
|
WarehouseContext ctx = WarehouseContext.of(WAREHOUSE_CODE, WarehouseProvider.XINCANG, null, |
||||||
|
WarehouseConnection.of(BASE_URL, ChannelSecret.builder() |
||||||
|
.appKey(APP_KEY).appSecret(APP_SECRET).build()), |
||||||
|
"probe-" + System.currentTimeMillis(), Clock.systemUTC()); |
||||||
|
|
||||||
|
try { |
||||||
|
AccessToken token = adapter.login(ctx); |
||||||
|
System.out.println("[login] ok token=" + token.fingerprint() |
||||||
|
+ " expiresAt=" + token.expiresAt() |
||||||
|
+ " (剩余 " + seconds(token) + " 秒)"); |
||||||
|
} catch (RuntimeException e) { |
||||||
|
// 探针异常只打印不抛出,方便一次跑完并对照真实报文
|
||||||
|
String msg = e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage(); |
||||||
|
System.out.println("[ERROR] " + e.getClass().getSimpleName() + ": " |
||||||
|
+ (msg.length() <= 300 ? msg : msg.substring(0, 300) + "…")); |
||||||
|
if (e instanceof ChannelException) { |
||||||
|
ChannelException ce = (ChannelException) e; |
||||||
|
System.out.println(" platformCode=" + ce.platformCode() |
||||||
|
+ " platformRequestId=" + ce.platformRequestId() |
||||||
|
+ " retryable=" + ce.retryable()); |
||||||
|
} |
||||||
|
} |
||||||
|
} |
||||||
|
|
||||||
|
private static long seconds(AccessToken token) { |
||||||
|
return token.expiresAt().getEpochSecond() - java.time.Instant.now().getEpochSecond(); |
||||||
|
} |
||||||
|
|
||||||
|
private static String mask() { |
||||||
|
if (XincangLoginProbeTest.APP_KEY.length() <= 6) { |
||||||
|
return "***"; |
||||||
|
} |
||||||
|
return XincangLoginProbeTest.APP_KEY.substring(0, 4) + "***" + XincangLoginProbeTest.APP_KEY.substring(XincangLoginProbeTest.APP_KEY.length() - 2); |
||||||
|
} |
||||||
|
|
||||||
|
private static String opt(String name, String fallback) { |
||||||
|
String value = System.getProperty(name, ""); |
||||||
|
if (value == null) { |
||||||
|
return fallback; |
||||||
|
} |
||||||
|
String trimmed = value.trim(); |
||||||
|
return trimmed.isEmpty() ? fallback : trimmed; |
||||||
|
} |
||||||
|
} |
||||||
Loading…
Reference in new issue