From e522c08377ff4b07ec42b9e5712a67c23309ed2a Mon Sep 17 00:00:00 2001 From: chenchuchuan <13554600537@163.com> Date: Thu, 12 Nov 2026 14:35:40 +0800 Subject: [PATCH] =?UTF-8?q?feat(edayun):=20=E5=AF=B9=E6=8E=A5=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=20token=EF=BC=88POST=20/oauth/token=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 按文档实现鉴权第一段: - auth/EdayunTokenClient:POST /oauth/token,body 用 client_id / client_secret (下划线风格照文档),无业务请求头 - http/EdayunRequestFactory:构造 token 请求;另备了业务请求构造(token / appKey / timestamp / sign 四个头)与 sign() = MD5(body + "." + appSecret) - adapter/EdayunAdapter.token(ctx):走 TokenManager 缓存,按 appKey + clientId 维度 - 工厂构造函数接收 TokenStore / LockProvider / Clock,与信仓同构 **文档只给了 code 取值(200/500/503/504),没给响应体结构**,所以做了兼容: 优先 data.access_token + data.expires_in,其次 data.expiry(绝对时刻), 再其次顶层 token;都没有则失败并带出截断的原始报文,不猜。 有效期同样三级兜底,最后按 2 小时(常量里标了「待联调确认」)。 错误分级: - 500 明确失败,不重试 - 503 网关无效 / 504 超时,标记 retryable - HTTP 非 2xx 单独处理,5xx(除 504)可重试 测试 12 个:请求形状、三种响应形态、无 token、500 不可重试、 503/504 可重试、缺 code、非 2xx、凭据缺失不发请求、MD5 签名(独立实现对照)、 空 body 签名。 全量 533 个测试通过。 Co-Authored-By: Claude --- docs-warehouse/edayun/README.md | 49 ++++- .../common/ecommerce/edayun/EdayunConstants.java | 37 ++++ .../ecommerce/edayun/adapter/EdayunAdapter.java | 50 ++++++ .../edayun/adapter/EdayunAdapterFactory.java | 15 +- .../ecommerce/edayun/auth/EdayunTokenClient.java | 198 +++++++++++++++++++++ .../ecommerce/edayun/dto/EdayunTokenDtos.java | 67 +++++++ .../edayun/http/EdayunRequestFactory.java | 140 +++++++++++++++ .../edayun/adapter/EdayunAdapterTest.java | 3 +- .../edayun/auth/EdayunTokenClientTest.java | 196 ++++++++++++++++++++ 9 files changed, 749 insertions(+), 6 deletions(-) create mode 100644 warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/auth/EdayunTokenClient.java create mode 100644 warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/dto/EdayunTokenDtos.java create mode 100644 warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/http/EdayunRequestFactory.java create mode 100644 warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/auth/EdayunTokenClientTest.java diff --git a/docs-warehouse/edayun/README.md b/docs-warehouse/edayun/README.md index a83401e..6eee6a4 100644 --- a/docs-warehouse/edayun/README.md +++ b/docs-warehouse/edayun/README.md @@ -6,20 +6,61 @@ |---|---| | 模块 | ✅ `warehouse-sdk-edayun` 已建、已注册 | | 适配器 / 工厂 | ✅ 类型就绪,能力位为空 | -| 接口 | ⬜ 等文档 | +| 获取 token | ✅ 已对接(`POST /oauth/token`) | +| 业务接口 | ⬜ 等文档 | | 回调 | ⬜ 等文档 | | 真机验证 | ⬜ 等测试环境 | **骨架阶段的行为**:任何业务调用都会抛 `WarehouseUnsupportedCapabilityException`——这是有意为之,不返回空集合。 +## 鉴权(已确认部分) + +``` +① POST /oauth/token + body: { "client_id": "OMS授权用户名", "client_secret": "密码" } + 无业务请求头 + → 返回 token + +② 业务请求头 + token 来自 ① + appKey 测试: 7289ded35b198243883151876eaf3213 + timestamp 毫秒,5 分钟内有效 + sign MD5(body + "." + appSecret),测试环境可传 openApiAdminSecret 免签 +``` + +**凭据映射**(复用 `ChannelSecret`): + +| 易达云 | ChannelSecret | +|---|---| +| appKey(请求头) | `appKey()` | +| appSecret(签名用) | `appSecret()` | +| client_id(换 token) | `clientId()` | +| client_secret(换 token) | `clientSecret()` | + +**代码位置**: + +| 类 | 职责 | +|---|---| +| `auth/EdayunTokenClient` | 换 token,兼容三种响应形态,按 code 区分可重试 | +| `http/EdayunRequestFactory` | 构造 token 请求与业务请求;`sign()` 算 MD5 | +| `adapter/EdayunAdapter.token(ctx)` | 走 `TokenManager` 缓存(按 `appKey + clientId` 维度) | + +**三处待联调确认**: + +1. **响应体结构**——文档只给了 `code` 取值(200/500/503/504),**没给 body 字段**。 + 现在兼容 `data.access_token` / `data.expiry` / 顶层 `token` 三种形态,真机确认后删多余分支。 +2. **token 有效期**——文档未写。`data.expires_in` 优先,其次 `data.expiry`, + 都没有按 2 小时兜底(`DEFAULT_TOKEN_TTL_SECONDS`)。 +3. **是否有 refresh**——文档没提。当前按「过期重新登录」处理。 + ## 待确认(问易达云) | # | 要确认 | |---|---| -| 1 | **接口文档**(含回调) | -| 2 | **测试环境**:域名、凭证、测试仓、测试 SKU | -| 3 | **鉴权方式**:固定 token / 签名 / OAuth?是否需要换 token 与刷新? | +| 1 | **业务接口文档**(含回调) | +| 2 | **测试环境**:域名、OMS 授权账号、测试仓、测试 SKU | +| 3 | token 响应的**实际 body 结构**与**有效期** | | 4 | **限流**:每秒许可数、单日配额 | | 5 | **能否在 PR 环境走写操作**(建单 / 取消 / 销毁),决定探针设计 | | 6 | **回调**:验签算法、时间戳单位、响应体格式、是否按路径区分 | diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/EdayunConstants.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/EdayunConstants.java index 2cad1c9..1b21b07 100644 --- a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/EdayunConstants.java +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/EdayunConstants.java @@ -29,6 +29,43 @@ public final class EdayunConstants { */ public static final String PRODUCTION_BASE_URL = "TODO"; + /** 获取 token({@code POST /oauth/token})。 */ + public static final String PATH_TOKEN = "/oauth/token"; + + /** Content-Type。 */ + public static final String CONTENT_TYPE_JSON = "application/json"; + + /** 请求头:token(来自 {@code POST /oauth/token})。 */ + public static final String HEADER_TOKEN = "token"; + + /** 请求头:appKey。 */ + public static final String HEADER_APP_KEY = "appKey"; + + /** 请求头:毫秒时间戳,5 分钟内有效。 */ + public static final String HEADER_TIMESTAMP = "timestamp"; + + /** 请求头:{@code MD5(body + "." + appSecret)}。 */ + public static final String HEADER_SIGN = "sign"; + + /** 业务码:成功。 */ + public static final int CODE_SUCCESS = 200; + /** 业务码:失败(不重试)。 */ + public static final int CODE_FAILED = 500; + /** 业务码:网关无效(可重试)。 */ + public static final int CODE_GATEWAY_INVALID = 503; + /** 业务码:超时(可重试)。 */ + public static final int CODE_TIMEOUT = 504; + + /** + * token 有效期兜底值(秒)。 + * + *

待联调确认:文档未写明有效期,先按 2 小时;拿到真实响应后改。

+ */ + public static final long DEFAULT_TOKEN_TTL_SECONDS = 2 * 60 * 60L; + + /** 提前刷新秒数:避免临界点过期。 */ + public static final long TOKEN_EARLY_REFRESH_SECONDS = 600L; + /** * 限流:每秒许可数。 * diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapter.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapter.java index d060748..cf9c514 100644 --- a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapter.java +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapter.java @@ -1,12 +1,21 @@ package common.ecommerce.edayun.adapter; +import common.ecommerce.edayun.auth.EdayunTokenClient; +import common.ecommerce.edayun.http.EdayunRequestFactory; import common.ecommerce.http.HttpTransport; import common.ecommerce.http.JacksonJsonCodec; +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.enums.WarehouseCapability; import common.ecommerce.warehouse.enums.WarehouseProvider; import common.ecommerce.warehouse.sdk.WarehouseAdapter; +import common.ecommerce.warehouse.sdk.WarehouseContext; import common.ecommerce.edayun.EdayunConstants; +import java.time.Clock; import java.util.EnumSet; /** @@ -23,10 +32,51 @@ public final class EdayunAdapter implements WarehouseAdapter { private final HttpTransport transport; private final JacksonJsonCodec json; + private final EdayunRequestFactory requestFactory; + private final EdayunTokenClient tokenClient; + private final TokenManager tokenManager; public EdayunAdapter(HttpTransport transport, JacksonJsonCodec json) { + this(transport, json, null, null, Clock.systemUTC()); + } + + /** + * @param tokenStore 令牌缓存;为 null 时 {@link #token(WarehouseContext)} 每次都重新登录 + * @param lockProvider 防击穿锁;与 tokenStore 成对提供 + */ + public EdayunAdapter(HttpTransport transport, JacksonJsonCodec json, + TokenStore tokenStore, LockProvider lockProvider, Clock clock) { this.transport = transport; this.json = json; + this.requestFactory = new EdayunRequestFactory(json); + this.tokenClient = new EdayunTokenClient(transport, json, clock); + this.tokenManager = tokenStore == null || lockProvider == null ? null + : new TokenManager(tokenStore, lockProvider, clock, + EdayunConstants.TOKEN_EARLY_REFRESH_SECONDS) { + @Override + protected AccessToken refresh(ChannelSecret secret, AccessToken previous) { + return tokenClient.fetch(secret.endpointBaseUrl(), + secret.clientId(), secret.clientSecret()); + } + }; + } + + /** + * 取一个可用 token(缓存命中则不登录)。 + * + *

token 按 {@code appKey + clientId} 维度缓存——同一 OMS 授权账号下多个仓共用一个。

+ */ + public AccessToken token(WarehouseContext ctx) { + ChannelSecret secret = ctx.secret(); + if (tokenManager == null) { + return tokenClient.fetch(ctx.endpointBaseUrl(), secret.clientId(), secret.clientSecret()); + } + return tokenManager.getOrRefresh(tokenKey(secret), secret); + } + + /** 令牌缓存维度。 */ + static String tokenKey(ChannelSecret secret) { + return EdayunConstants.ADAPTER_ID + ":" + secret.appKey() + ":" + secret.clientId(); } @Override diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapterFactory.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapterFactory.java index 66dc2c3..7156fa4 100644 --- a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapterFactory.java +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/adapter/EdayunAdapterFactory.java @@ -3,6 +3,9 @@ package common.ecommerce.edayun.adapter; import common.ecommerce.edayun.EdayunConstants; 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.sdk.WarehouseAdapterFactory; import common.ecommerce.warehouse.enums.WarehouseProvider; import common.ecommerce.warehouse.sdk.WarehouseAdapter; import common.ecommerce.warehouse.sdk.WarehouseAdapterFactory; @@ -18,6 +21,16 @@ import common.ecommerce.warehouse.sdk.WarehouseAdapterFactory; */ public final class EdayunAdapterFactory implements WarehouseAdapterFactory { + private final TokenStore tokenStore; + private final LockProvider lockProvider; + private final java.time.Clock clock; + + public EdayunAdapterFactory(TokenStore tokenStore, LockProvider lockProvider, java.time.Clock clock) { + this.tokenStore = tokenStore; + this.lockProvider = lockProvider; + this.clock = clock; + } + @Override public String adapterId() { return EdayunConstants.ADAPTER_ID; @@ -32,6 +45,6 @@ public final class EdayunAdapterFactory implements WarehouseAdapterFactory { public WarehouseAdapter create(AdapterConfig config) { return new EdayunAdapter( new OkHttpTransport("common-ecommerce/1.0.0 (edayun)"), - new JacksonJsonCodec()); + new JacksonJsonCodec(), tokenStore, lockProvider, clock); } } diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/auth/EdayunTokenClient.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/auth/EdayunTokenClient.java new file mode 100644 index 0000000..181a1f6 --- /dev/null +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/auth/EdayunTokenClient.java @@ -0,0 +1,198 @@ +package common.ecommerce.edayun.auth; + +import common.ecommerce.edayun.EdayunConstants; +import common.ecommerce.edayun.dto.EdayunTokenDtos; +import common.ecommerce.edayun.http.EdayunRequestFactory; +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.http.HttpTransport; +import common.ecommerce.shared.error.ValidationException; +import common.ecommerce.shared.spi.AccessToken; +import common.ecommerce.warehouse.error.WarehouseException; + +import java.time.Clock; +import java.time.Instant; + +/** + * 易达云获取 token({@code POST /oauth/token})。 + * + *

凭据用 OMS 授权账号:{@link common.ecommerce.shared.spi.ChannelSecret#clientId()} + * / {@link common.ecommerce.shared.spi.ChannelSecret#clientSecret()}。 + * appKey 不参与这一步(它是业务请求头的字段)。

+ * + *

待联调确认:文档只给了 {@code code} 的取值(200 / 500 / 503 / 504), + * 没给响应体结构。所以这里同时兼容三种常见形态:

+ * + *

都取不到时按 500 处理并带出原始报文(截断)。

+ */ +public final class EdayunTokenClient { + + private static final String OP_FETCH = "token.fetch"; + + private final HttpTransport transport; + private final JsonCodec json; + private final EdayunRequestFactory requestFactory; + private final Clock clock; + + public EdayunTokenClient(HttpTransport transport, JsonCodec json, Clock clock) { + this.transport = transport; + this.json = json; + this.clock = clock; + this.requestFactory = new EdayunRequestFactory(json); + } + + /** + * 换取令牌。 + * + * @param baseUrl 本次调用的基址 + * @param clientId OMS 授权用户名 + * @param clientSecret OMS 授权密码 + */ + public AccessToken fetch(String baseUrl, String clientId, String clientSecret) { + HttpRequest req = requestFactory.token(baseUrl, clientId, clientSecret, OP_FETCH); + HttpResponse resp = transport.execute(req); + requireHttpOk(resp); + + String body = resp.body(); + EdayunTokenDtos.TokenResponse parsed; + try { + parsed = json.fromJson(body, EdayunTokenDtos.TokenResponse.class); + } catch (RuntimeException e) { + throw validation("edayun token response is not json", body); + } + requireBusinessOk(parsed, body); + + String token = tokenOf(parsed, body); + return AccessToken.builder() + .value(token) + .expiresAt(expiresAtOf(parsed)) + .build(); + } + + /** HTTP 层:非 2xx 直接失败。 */ + private void requireHttpOk(HttpResponse resp) { + int status = resp.statusCode(); + if (status >= 200 && status < 300) { + return; + } + throw toException(status, resp.body()); + } + + private WarehouseException toException(int status, String body) { + boolean retryable = status >= 500 && status != 504; + return WarehouseException.builder() + .message("edayun token request failed: http " + status + + ", body=" + truncate(body)) + .operation(OP_FETCH) + .provider(EdayunConstants.ADAPTER_ID) + .platformCode(String.valueOf(status)) + .rawResponse(truncate(body)) + .retryable(retryable) + .build(); + } + + /** + * 业务码:200 成功;500 失败;503 网关无效;504 超时。 + * + *

503 通常是网关问题、504 是超时,都值得重试;500 是明确失败,不重试。

+ */ + private void requireBusinessOk(EdayunTokenDtos.TokenResponse parsed, String body) { + if (parsed == null) { + throw validation("edayun token response is empty", body); + } + Integer code = parsed.code; + if (code == null) { + throw validation("edayun token response has no code", body); + } + if (code == EdayunConstants.CODE_SUCCESS) { + return; + } + throw WarehouseException.builder() + .message("edayun token business error: code=" + code + + ", message=" + parsed.message) + .operation(OP_FETCH) + .provider(EdayunConstants.ADAPTER_ID) + .platformCode(String.valueOf(code)) + .rawResponse(truncate(body)) + .retryable(code == EdayunConstants.CODE_GATEWAY_INVALID + || code == EdayunConstants.CODE_TIMEOUT) + .build(); + } + + /** 三种形态都试一遍;都取不到就失败,不猜。 */ + private String tokenOf(EdayunTokenDtos.TokenResponse parsed, String body) { + if (parsed.data != null && hasText(parsed.data.accessToken)) { + return parsed.data.accessToken.trim(); + } + // 顶层 token(部分网关会把 data 拍平) + String topLevel = json.stringAt(body, "token"); + if (hasText(topLevel)) { + return topLevel.trim(); + } + throw validation("edayun token response has no access token" + + " (looked for data.access_token and token)", body); + } + + /** + * 过期时刻。 + * + *

优先 {@code data.expires_in}(相对秒),其次 {@code data.expiry}(绝对), + * 都没有就按 {@link EdayunConstants#DEFAULT_TOKEN_TTL_SECONDS} 兜底并标注待确认。

+ */ + private Instant expiresAtOf(EdayunTokenDtos.TokenResponse parsed) { + Instant now = Instant.now(clock); + EdayunTokenDtos.TokenResponse.TokenData data = parsed.data; + if (data != null && data.expiresIn != null && data.expiresIn > 0) { + return now.plusSeconds(data.expiresIn); + } + if (data != null && hasText(data.expiry)) { + Instant absolute = parseAbsolute(data.expiry.trim()); + if (absolute != null) { + return absolute; + } + } + return now.plusSeconds(EdayunConstants.DEFAULT_TOKEN_TTL_SECONDS); + } + + /** 绝对时刻:兼容 ISO-8601 与毫秒 / 秒数字。 */ + private static Instant parseAbsolute(String raw) { + try { + return Instant.parse(raw); + } catch (RuntimeException ignored) { + // 继续试数字 + } + try { + long n = Long.parseLong(raw); + // 10 位按秒、13 位按毫秒 + return raw.length() <= 10 ? Instant.ofEpochSecond(n) : Instant.ofEpochMilli(n); + } catch (RuntimeException ignored) { + return null; + } + } + + private static ValidationException validation(String message, String body) { + return new ValidationException(WarehouseException.builder() + .message(message) + .operation(OP_FETCH) + .provider(EdayunConstants.ADAPTER_ID) + .rawResponse(truncate(body)) + .retryable(false)); + } + + private static boolean hasText(String v) { + return v != null && !v.trim().isEmpty(); + } + + /** 响应可能含 token 与密码,异常里只留很短一段。 */ + private static String truncate(String body) { + if (body == null) { + return null; + } + return body.length() <= 300 ? body : body.substring(0, 300) + "..."; + } +} diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/dto/EdayunTokenDtos.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/dto/EdayunTokenDtos.java new file mode 100644 index 0000000..5259d3a --- /dev/null +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/dto/EdayunTokenDtos.java @@ -0,0 +1,67 @@ +package common.ecommerce.edayun.dto; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * 易达云报文结构:获取 token({@code POST /oauth/token})。 + * + *

一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构; + * 与其它接口共用的结构各自复制一份,避免跨接口耦合。

+ */ +public final class EdayunTokenDtos { + + private EdayunTokenDtos() { + } + + /** + * 获取 token 请求体。 + * + *

字段名是下划线风格,与易达云其它接口的驼峰不同,照文档原样保留。

+ * + *

注意:{@code client_id} / {@code client_secret} 是易达云 OMS 系统的 + * 授权账号,不是 appKey / appSecret。appKey 走请求头。

+ */ + public static final class TokenRequest { + + /** 用户名(oms 系统授权)。 */ + @JsonProperty("client_id") + public String clientId; + /** 密码(oms 系统授权)。 */ + @JsonProperty("client_secret") + public String clientSecret; + } + + /** + * 获取 token 响应。 + * + *

待联调确认:文档只给了 {@code code} 的取值约定 + * (200 成功 / 500 失败 / 503 网关无效 / 504 超时),没有给响应体结构。 + * 这里按常见形态预留了 {@code data.access_token} / {@code expires_in} / + * {@code expiry},实际字段名以真机返回为准。

+ */ + public static final class TokenResponse { + + /** 200 成功 / 500 失败 / 503 网关无效 / 504 超时。 */ + public Integer code; + public String message; + + /** 业务载荷;字段名待确认。 */ + public TokenData data; + + /** token 载荷。 */ + public static final class TokenData { + /** access token。 */ + @JsonProperty("access_token") + public String accessToken; + /** 有效期(秒)。 */ + @JsonProperty("expires_in") + public Long expiresIn; + /** 绝对过期时刻;单位与格式待确认。 */ + @JsonProperty("expiry") + public String expiry; + /** 刷新令牌;易达云是否提供待确认。 */ + @JsonProperty("refresh_token") + public String refreshToken; + } + } +} diff --git a/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/http/EdayunRequestFactory.java b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/http/EdayunRequestFactory.java new file mode 100644 index 0000000..d6b46c2 --- /dev/null +++ b/warehouse-sdk-edayun/src/main/java/common/ecommerce/edayun/http/EdayunRequestFactory.java @@ -0,0 +1,140 @@ +package common.ecommerce.edayun.http; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JsonCodec; +import common.ecommerce.shared.spi.ChannelSecret; +import common.ecommerce.edayun.EdayunConstants; +import common.ecommerce.edayun.dto.EdayunTokenDtos; + +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 构造易达云请求。 + * + *

鉴权分两段:

+ *
    + *
  1. 先 {@code POST /oauth/token} 换 token(用 OMS 授权账号 client_id / client_secret)
  2. + *
  3. 业务请求把 token 放请求头 {@code token},并带 {@code appKey} / {@code timestamp} / {@code sign}
  4. + *
+ * + *

凭据映射(复用 {@link ChannelSecret}):

+ * + * + * + * + * + * + *
易达云ChannelSecret
appKey(请求头){@link ChannelSecret#appKey()}
appSecret(签名用){@link ChannelSecret#appSecret()}
client_id{@link ChannelSecret#clientId()}
client_secret{@link ChannelSecret#clientSecret()}
+ */ +public final class EdayunRequestFactory { + + private final JsonCodec json; + + public EdayunRequestFactory(JsonCodec json) { + this.json = json; + } + + /** + * 获取 token:{@code POST /oauth/token}。 + * + *

文档要求不需要 header 参数(除了 Content-Type)。

+ * + * @param clientId 易达云 OMS 授权用户名 + * @param clientSecret 易达云 OMS 授权密码 + */ + public HttpRequest token(String baseUrl, String clientId, String clientSecret, String operation) { + EdayunTokenDtos.TokenRequest body = new EdayunTokenDtos.TokenRequest(); + body.clientId = requireText(clientId, "edayun requires ChannelSecret.clientId()"); + body.clientSecret = requireText(clientSecret, "edayun requires ChannelSecret.clientSecret()"); + + return HttpRequest.builder() + .method("POST") + .url(join(baseUrl, EdayunConstants.PATH_TOKEN)) + .contentType(EdayunConstants.CONTENT_TYPE_JSON) + .body(json.toJson(body)) + .operation(operation) + .build(); + } + + /** + * 业务请求:带 token / appKey / timestamp / sign 四个头。 + * + *

{@code sign = MD5(body + "." + appSecret)},小写十六进制。 + * 测试环境传 {@code openApiAdminSecret} 可免签,但生产必须算。

+ * + * @param token {@code /oauth/token} 拿到的 token + * @param appKey {@code ChannelSecret.appKey()} + * @param appSecret {@code ChannelSecret.appSecret()} + * @param timestamp 毫秒时间戳;5 分钟内有效 + * @param bodyJson 请求体(GET 时为空串) + */ + public HttpRequest business(String baseUrl, String path, String method, + String token, String appKey, String appSecret, + long timestamp, String bodyJson, String operation) { + Map headers = new LinkedHashMap(); + headers.put(EdayunConstants.HEADER_TOKEN, requireText(token, "edayun requires a token")); + headers.put(EdayunConstants.HEADER_APP_KEY, requireText(appKey, + "edayun requires ChannelSecret.appKey()")); + headers.put(EdayunConstants.HEADER_TIMESTAMP, String.valueOf(timestamp)); + headers.put(EdayunConstants.HEADER_SIGN, sign(bodyJson, appSecret)); + + HttpRequest.Builder builder = HttpRequest.builder() + .method(method) + .url(join(baseUrl, path)) + .headers(headers) + .operation(operation); + if (bodyJson != null && !bodyJson.isEmpty()) { + builder.contentType(EdayunConstants.CONTENT_TYPE_JSON).body(bodyJson); + } + return builder.build(); + } + + /** + * 签名:{@code MD5(body + "." + appSecret)},小写十六进制。 + * + *

注意是 body 原文参与签名——所以业务方法要把「即将发出的那个字符串」 + * 传进来,不能传反序列化后再序列化的结果(字段顺序变了签名就对不上)。

+ */ + public static String sign(String bodyJson, String appSecret) { + String secret = requireText(appSecret, "edayun requires ChannelSecret.appSecret()"); + String raw = (bodyJson == null ? "" : bodyJson) + "." + secret; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + byte[] digest = md.digest(raw.getBytes(StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(digest.length * 2); + for (byte b : digest) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } catch (java.security.NoSuchAlgorithmException e) { + throw new IllegalStateException("MD5 not available", e); + } + } + + private static String join(String baseUrl, String path) { + String base = requireText(baseUrl, "edayun requires an endpoint base url"); + return base.endsWith("/") ? base + (path.startsWith("/") ? path.substring(1) : path) + : base + (path.startsWith("/") ? path : "/" + path); + } + + private static String requireText(String value, String message) { + if (value == null || value.trim().isEmpty()) { + throw new IllegalArgumentException(message); + } + return value.trim(); + } + + /** 供将来带 query 参数的接口使用。 */ + static String encode(String v) { + try { + return URLEncoder.encode(v, "UTF-8"); + } catch (java.io.UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } +} diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java index c20662e..49b0d32 100644 --- a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/adapter/EdayunAdapterTest.java @@ -45,7 +45,8 @@ class EdayunAdapterTest { return WarehouseSdk.builder() .warehouseRepository(new InMemoryWarehouses().put(account())) .clock(CLOCK) - .register(new EdayunAdapterFactory()) + .register(new EdayunAdapterFactory(new common.ecommerce.shared.testkit.InMemoryTokenStore(), + new common.ecommerce.shared.testkit.InMemoryLockProvider(), CLOCK)) .build(); } diff --git a/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/auth/EdayunTokenClientTest.java b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/auth/EdayunTokenClientTest.java new file mode 100644 index 0000000..a51e107 --- /dev/null +++ b/warehouse-sdk-edayun/src/test/java/common/ecommerce/edayun/auth/EdayunTokenClientTest.java @@ -0,0 +1,196 @@ +package common.ecommerce.edayun.auth; + +import common.ecommerce.edayun.EdayunConstants; +import common.ecommerce.edayun.http.EdayunRequestFactory; +import common.ecommerce.http.JacksonJsonCodec; +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.warehouse.error.WarehouseException; +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.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * 易达云获取 token({@code POST /oauth/token})。 + * + *

文档只给了 {@code code} 的取值,没给响应体结构,所以这里把三种常见形态 + * (OAuth 标准 / 绝对时刻 / 顶层 token)都固化成测试,等真机确认后再删多余的分支。

+ */ +class EdayunTokenClientTest { + + private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-12T00:00:00Z"), ZoneOffset.UTC); + private static final String BASE = "https://api.edayun.test"; + + private static EdayunTokenClient client(RecordingTransport transport) { + return new EdayunTokenClient(transport, new JacksonJsonCodec(), CLOCK); + } + + // ------------------------------------------------------------ 请求 + + @Test + void sendsDocumentedRequest() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); + + client(transport).fetch(BASE, "dl-test", "123456"); + + String body = transport.lastDataRequest().body(); + assertEquals("POST", transport.lastDataRequest().method()); + assertEquals(BASE + "/oauth/token", transport.lastDataRequest().url()); + // 字段名是下划线风格,照文档原样 + assertTrue(body.contains("\"client_id\":\"dl-test\""), body); + assertTrue(body.contains("\"client_secret\":\"123456\""), body); + // 文档明确:这一步不需要业务头 + assertTrue(transport.lastDataRequest().headers().isEmpty() + || !transport.lastDataRequest().headers().containsKey("token")); + } + + // ------------------------------------------------------------ 响应形态 + + @Test + void acceptsOauthStandardShape() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":200,\"data\":{\"access_token\":\"T1\",\"expires_in\":7200}}")); + + AccessToken token = client(transport).fetch(BASE, "u", "p"); + + assertEquals("T1", token.value()); + assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); + } + + @Test + void acceptsAbsoluteExpiry() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":200,\"data\":{\"access_token\":\"T2\"," + + "\"expiry\":\"2026-11-12T03:00:00Z\"}}")); + + AccessToken token = client(transport).fetch(BASE, "u", "p"); + + assertEquals("T2", token.value()); + assertEquals(Instant.parse("2026-11-12T03:00:00Z"), token.expiresAt()); + } + + @Test + void acceptsTopLevelToken() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":200,\"token\":\"T3\"}")); + + AccessToken token = client(transport).fetch(BASE, "u", "p"); + + assertEquals("T3", token.value()); + // 没有有效期信息时按兜底 TTL + assertEquals(Instant.parse("2026-11-12T02:00:00Z"), token.expiresAt()); + } + + // ------------------------------------------------------------ 失败路径 + + @Test + void noTokenInResponseIsRejected() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":200,\"data\":{\"foo\":\"bar\"}}")); + + ValidationException ex = assertThrows(ValidationException.class, + () -> client(transport).fetch(BASE, "u", "p")); + assertTrue(ex.getMessage().contains("no access token"), ex.getMessage()); + } + + /** 500 是明确失败,不重试。 */ + @Test + void business500IsNotRetryable() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":500,\"message\":\"bad credentials\"}")); + + WarehouseException ex = assertThrows(WarehouseException.class, + () -> client(transport).fetch(BASE, "u", "p")); + assertTrue(ex.getMessage().contains("code=500"), ex.getMessage()); + assertEquals(Boolean.FALSE, ex.retryable()); + } + + /** 503 / 504 是网关与超时,值得重试。 */ + @Test + void gatewayAndTimeoutAreRetryable() { + for (String code : new String[] {"503", "504"}) { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok( + "{\"code\":" + code + ",\"message\":\"gw\"}")); + WarehouseException ex = assertThrows(WarehouseException.class, + () -> client(transport).fetch(BASE, "u", "p"), code); + assertEquals(Boolean.TRUE, ex.retryable(), code); + } + } + + @Test + void missingCodeIsRejected() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.ok("{\"message\":\"ok\"}")); + + assertThrows(ValidationException.class, () -> client(transport).fetch(BASE, "u", "p")); + } + + @Test + void non2xxIsRejected() { + RecordingTransport transport = RecordingTransport.create() + .route(EdayunConstants.PATH_TOKEN, req -> Responses.status(401, "{}")); + + WarehouseException ex = assertThrows(WarehouseException.class, + () -> client(transport).fetch(BASE, "u", "p")); + assertTrue(ex.getMessage().contains("http 401"), ex.getMessage()); + } + + // ------------------------------------------------------------ 凭据校验 + + @Test + void missingCredentialsFailFast() { + RecordingTransport transport = RecordingTransport.create(); + + assertThrows(IllegalArgumentException.class, + () -> client(transport).fetch(BASE, " ", "p")); + assertThrows(IllegalArgumentException.class, + () -> client(transport).fetch(BASE, "u", null)); + assertTrue(transport.recorded().isEmpty(), "凭据缺失不应发出请求"); + } + + // ------------------------------------------------------------ 签名 + + @Test + void signIsMd5OfBodyDotSecret() { + // MD5("{\"a\":1}.secret") 的已知值,用独立实现校验 + String expected = md5Hex("{\"a\":1}.secret"); + assertEquals(expected, EdayunRequestFactory.sign("{\"a\":1}", "secret")); + } + + @Test + void emptyBodyStillSigns() { + assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign(null, "secret")); + assertEquals(md5Hex(".secret"), EdayunRequestFactory.sign("", "secret")); + } + + private static String md5Hex(String s) { + try { + java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5"); + byte[] d = md.digest(s.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + StringBuilder sb = new StringBuilder(); + for (byte b : d) { + sb.append(Character.forDigit((b >> 4) & 0xF, 16)); + sb.append(Character.forDigit(b & 0xF, 16)); + } + return sb.toString(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + } +}