端点与路径是协议的一部分,写在代码里,不做成配置表。 + * 运行时不使用 {@link #TEST_BASE_URL}:端点由调用方每次经 + * {@code WarehouseConnection} 传入。
+ * + *依据 Apifox「OMS接口文档V2」(2026-11 核对)与其《新 OMS 接口迁移调整说明》。
+ */ +public final class XincangConstants { + + /** 适配器标识。 */ + public static final String ADAPTER_ID = "xincang"; + + /** + * 测试 / 联调环境基址。 + * + *文档明确写了这个地址;末尾不带斜杠,与 {@code WarehouseConnection} 的归一化一致, + * 路径直接以 {@code /} 开头拼接。
+ */ + public static final String TEST_BASE_URL = "http://test.api.oms.13u3.com/oms"; + + /** + * 生产环境基址。 + * + *待核对:官方文档只给了测试地址(迁移说明里那句「生产环境接口路径与请求方法 + * 全部保持不变」只谈路径)。生产域名确认后只改这一处。调用方需要时可直接传自己的 + * {@code WarehouseConnection.endpointBaseUrl},不依赖本常量。
+ */ + 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 有效期兜底值(秒)。 + * + *文档:测试数据说明写明有效期 2 小时;正常以响应里的 {@code token_expire_time} 为准, + * 只有该字段缺失 / 无法解析时才用这个值,并记一条 WARN 级别的日志语义。
+ */ + public static final long DEFAULT_TOKEN_TTL_SECONDS = 2 * 60 * 60L; + + /** 提前续期的窗口(秒)。 */ + public static final long TOKEN_EARLY_REFRESH_SECONDS = 600L; + + /** + * 限流:文档未公开限流值。 + * + *待核对:按三家仓的保守默认 2 req/s/仓,联调确认后只改这一处。
+ */ + public static final int PERMITS_PER_SECOND = 2; + + /** 信仓以北京时间为准(文档「时间:北京时间」)。 */ + public static final ZoneId SYSTEM_ZONE = PlatformTime.BEIJING_ZONE; + + private XincangConstants() { + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java new file mode 100644 index 0000000..809ae36 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapter.java @@ -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)。 + * + *文档确认的鉴权方式:{@code GET /api.login?appkey=&secret=} 换取客户级 token, + * 有效期 2 小时、无 refresh 接口;业务请求把 token 放在 query 参数 {@code token} 里。 + * 本轮只落地登录与令牌缓存,出库 / 库存 / 预报等能力位一律不声明, + * 门面调用这些能力会显式抛 {@code WarehouseUnsupportedCapabilityException}。
+ * + *适配器只持有协议与基础设施,不持有端点与凭据——两者随每次调用经 + * {@code WarehouseConnection} 传入。
+ */ +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供健康检查与联调探针使用;业务方法接入时也应经此取 token, + * 不要在适配器外自行缓存。
+ * + * @throws common.ecommerce.shared.error.AuthException 登录被拒或令牌结构不符合文档 + */ + public AccessToken login(WarehouseContext ctx) { + return tokenManager.getOrRefresh(tokenKey(ctx.secret()), ctx.secret()); + } + + /** + * 令牌缓存维度:信仓 token 按客户(appkey)发放,同一 appkey 下多仓共用一个 token。 + * + *用 appkey 而不是 {@code warehouseCode},避免同客户多仓重复登录。
+ */ + static String tokenKey(ChannelSecret secret) { + return XincangConstants.ADAPTER_ID + ":" + secret.appKey(); + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java new file mode 100644 index 0000000..d884817 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/adapter/XincangAdapterFactory.java @@ -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; + +/** + * 信仓适配器工厂。 + * + *与领星适配器同构:令牌存储与锁由宿主注入,端点与凭据仍随每次调用传入。
+ */ +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); + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java new file mode 100644 index 0000000..675d0a2 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/auth/XincangTokenClient.java @@ -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})。 + * + *文档(Apifox「OMS接口文档V2」)确认:query 参数 {@code appkey} / {@code secret}, + * 响应 {@code rst} 直接给出 {@code token} 与 {@code token_expire_time}(北京时间 + * {@code yyyy-MM-dd HH:mm:ss}),有效期 2 小时。没有 refresh 接口,过期只能重新登录; + * 续期由 {@code TokenManager} 提前刷新完成。
+ * + *token 是客户级(同一 appkey 下多仓共用),后续业务请求把它放在 query 参数 + * {@code token} 里,不是 {@code Authorization} 头。
+ */ +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(); + } + + /** + * 过期时刻。 + * + *字段缺失 / 空白时按文档写明的 2 小时兜底;字段存在但格式不对则直接失败—— + * 那说明报文和文档不一致,静默兜底会把续期时间算错。
+ */ + 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) + "..."; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java new file mode 100644 index 0000000..4333d81 --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/dto/XincangDtos.java @@ -0,0 +1,68 @@ +package common.ecommerce.xincang.dto; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 信仓报文结构。 + * + *字段名以 Apifox「OMS接口文档V2」为准。信仓全局响应外层统一为 + * {@code {"rst": ..., "errno": 0, "err": "", "trace_id": "..."}},这里只放登录接口用到的部分。 + * 字段差异只改本类,不动适配器与领域模型。
+ */ +public final class XincangDtos { + + private XincangDtos() { + } + + /** + * 登录响应({@code GET /api.login})。 + * + *注意与业务接口不同:登录的 {@code rst} 没有 {@code code/msg/data} 包裹, + * 而是直接给出客户与 token 字段。
+ */ + @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; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java new file mode 100644 index 0000000..87c7d1d --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangEnvelope.java @@ -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; + +/** + * 信仓响应信封校验。 + * + *信仓统一外层(Apifox「OMS接口文档V2」):
+ *
+ * { "rst": ..., "errno": 0, "err": "", "trace_id": "..." }
+ *
+ *
+ * 两条成功判定:顶层 {@code errno} 为 0;业务接口的 {@code rst} 是 + * {@code {"code":"0","msg":"","data":...}} 时还要求 {@code rst.code} 为 {@code "0"}。 + * 登录是例外——它的 {@code rst} 直接是客户 / token 字段,没有 {@code code},缺失即视为通过。
+ * + *HTTP 401/403/429/5xx 仍按 HTTP 语义映射:网关或代理层直接拒绝时也要能正确分类。
+ */ +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; + } + + /** + * 统一异常字段。 + * + *返回 {@link ChannelException.Builder} 而不是 {@code WarehouseException.Builder}: + * 仓库域的自定义异常仅有 {@code WarehouseException} 一个,其余分类(Auth / RateLimit / + * Transient / Validation / PlatformBusiness)的构造器都收 {@code ChannelException.Builder}。
+ * + *{@code warehouseCode} 保留在签名里便于调用方一致传参,但 不写进 + * {@code omsStoreId}——那是渠道域的店铺 ID,填仓编码会污染审计字段。 + * 需要仓维度的错误请由适配器层包一层 {@code WarehouseException}。
+ */ + 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) + "..."; + } +} diff --git a/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java new file mode 100644 index 0000000..64fa4bf --- /dev/null +++ b/warehouse-sdk-xincang/src/main/java/common/ecommerce/xincang/http/XincangRateLimiter.java @@ -0,0 +1,57 @@ +package common.ecommerce.xincang.http; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.LongSupplier; + +/** + * 按接口路径的令牌桶。 + * + *信仓文档未公开限流值,先按保守默认 {@code XincangConstants.PERMITS_PER_SECOND} 节流; + * 429 的 {@code Retry-After} 由宿主处理,这里只做本地限速。
+ * + *进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。 + * 与领星限流器同构,可注入 {@link Sleeper} 与纳秒时钟,便于测试。
+ */ +public final class XincangRateLimiter { + + /** 便于测试注入,生产用 {@link Thread#sleep}。 */ + public interface Sleeper { + void sleep(long millis, int nanos); + } + + private final Map鉴权是「登录换 token + 每次业务请求带 query 参数 {@code token}」(文档对所有业务接口 + * 都把 {@code token} 列为必填 query 参数),因此不走 {@code Authorization} 头。 + * 凭据复用 {@link ChannelSecret#appKey()} / {@link ChannelSecret#appSecret()}。
+ */ +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后续接口(订单 / 库存 / 预报)都要求 token 作为 query 参数,这个方法集中处理, + * 免得各 Source 各写一遍。本轮只落地登录,接入业务接口时直接复用。
+ */ + public HttpRequest getWithToken(String baseUrl, String path, Map请求与响应都按 Apifox「OMS接口文档V2」的真实报文构造,无需网络。
+ */ +class XincangTokenClientTest { + + private static final String BASE = "http://test.api.oms.13u3.com/oms"; + /** + * 测试用占位凭据。 + * + *真实凭据(含文档里的测试 appkey/secret)一律不入库:联调用 + * {@code XincangLoginProbeTest} 走系统属性传入。
+ */ + 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()); + } +} diff --git a/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java new file mode 100644 index 0000000..5754d02 --- /dev/null +++ b/warehouse-sdk-xincang/src/test/java/common/ecommerce/xincang/http/XincangRequestFactoryTest.java @@ -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默认跳过,用 {@code -Dxincang.probe=true} 显式开启,凭据走系统属性、 + * 真实凭据不入库:
+ * + *+ * mvn -pl warehouse-sdk-xincang -am -DfailIfNoTests=false \ + * -Dxincang.probe=true \ + * -Dxincang.probe.appKey=你的appkey -Dxincang.probe.appSecret=你的secret \ + * -Dtest=XincangLoginProbeTest test + *+ * + *
可选系统属性:{@code -Dxincang.probe.baseUrl}(默认测试环境 {@code XincangConstants.TEST_BASE_URL}) + * 与 {@code -Dxincang.probe.warehouseCode}(仅用于日志)。
+ * + *只做登录,不调用任何业务接口;输出只打印 token 指纹与过期时间,不打印 token 本体。
+ */ +@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; + } +}