From 2bc5da043aa654915fbb5879df65b5d1aa0fad5c Mon Sep 17 00:00:00 2001 From: lml <1297555865@qq.com> Date: Mon, 2 Nov 2026 11:44:57 +0800 Subject: [PATCH] =?UTF-8?q?feat(lingxing):=20=E6=8C=89=202026=20=E7=89=88?= =?UTF-8?q?=E5=AE=98=E6=96=B9=E7=AE=97=E6=B3=95=E9=87=8D=E5=86=99=E7=AD=BE?= =?UTF-8?q?=E5=90=8D=E5=B9=B6=E6=8A=BD=E5=87=BA=E7=BB=9F=E4=B8=80=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 签名: - 签名范围改为「业务参数 + access_token + app_key + timestamp」,按 key 升序拼接 - MD5 输出 32 位大写,再用 appId 做 AES/ECB/PKCS5Padding 加密并 Base64 - 集合参数先 JSON 序列化再参与签名 - appId 不是 16/24/32 字节时直接抛 IllegalArgumentException,不静默补齐 请求层: - 新增 LingxingEnvelope,业务错误看 body.code,映射限流/鉴权/业务异常 - 新增 LingxingRateLimiter,按接口路径分桶,订单列表 10 req/s - 新增 LingxingRequestFactory,access_token 只进 Authorization 但参与签名 - 订单列表请求体改为 start_time/end_time(epoch 秒)+ platform_code/store_id 数组 - 分页改为「满页 + total 兜底」,避免最后一页多发一次请求 - 令牌缓存键从 store_id 改为 appKey,同 app 多店铺共用 token - 映射异常包装成 ValidationException 并保留原始报文,避免以 NPE 形式冒出 --- .../common/ecommerce/lingxing/LingxingAdapter.java | 126 +++++++-------------- .../ecommerce/lingxing/LingxingConstants.java | 3 + .../ecommerce/lingxing/LingxingEnvelope.java | 120 ++++++++++++++++++++ .../ecommerce/lingxing/LingxingRateLimiter.java | 64 +++++++++++ .../ecommerce/lingxing/LingxingRequestFactory.java | 95 ++++++++++++++++ .../common/ecommerce/lingxing/LingxingSigner.java | 89 +++++++++++---- .../ecommerce/lingxing/LingxingAdapterTest.java | 20 ++-- .../ecommerce/lingxing/LingxingEnvelopeTest.java | 67 +++++++++++ .../ecommerce/lingxing/LingxingLiveSmokeTest.java | 4 +- .../lingxing/LingxingRateLimiterTest.java | 66 +++++++++++ .../lingxing/LingxingRequestFactoryTest.java | 73 ++++++++++++ .../ecommerce/lingxing/LingxingSignerTest.java | 59 +++++----- 12 files changed, 638 insertions(+), 148 deletions(-) create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/LingxingEnvelope.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/LingxingRateLimiter.java create mode 100644 lingxing/src/main/java/common/ecommerce/lingxing/LingxingRequestFactory.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/LingxingEnvelopeTest.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/LingxingRateLimiterTest.java create mode 100644 lingxing/src/test/java/common/ecommerce/lingxing/LingxingRequestFactoryTest.java diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java index 56a55a6..20d87d4 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingAdapter.java @@ -3,11 +3,11 @@ package common.ecommerce.lingxing; import common.ecommerce.capability.AggregatorCapable; import common.ecommerce.capability.SalesOrderCapable; import common.ecommerce.error.ChannelException; +import common.ecommerce.error.ValidationException; import common.ecommerce.http.HttpRequest; import common.ecommerce.http.HttpResponse; import common.ecommerce.http.HttpTransport; import common.ecommerce.http.JacksonJsonCodec; -import common.ecommerce.http.Responses; import common.ecommerce.http.TokenManager; import common.ecommerce.lingxing.dto.LingxingOrderDto; import common.ecommerce.model.Capability; @@ -25,8 +25,6 @@ import common.ecommerce.spi.LockProvider; import common.ecommerce.spi.SecretProvider; import common.ecommerce.spi.TokenStore; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; import java.time.Clock; import java.time.Duration; import java.time.Instant; @@ -44,15 +42,9 @@ import java.util.Set; * *

一个适配器服务多个子平台,子平台由 {@code ChannelAccount.platformCode} 决定, * 能力按子平台细化({@link #supports})。首期只实现订单列表拉取。

- * - *

领星字段名与签名细节标注为「待核对」的地方集中在 {@code dto} 与 - * {@link LingxingSigner},联调时只改这两处。

*/ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapable { - /** 领星订单列表令牌桶:10 req/s(文档 9.3 按接口配置)。 */ - private static final int ORDERS_PER_SECOND = 10; - private final String baseUrl; private final HttpTransport transport; private final JacksonJsonCodec json; @@ -60,7 +52,8 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab private final Clock clock; private final LingxingOrderMapper mapper; private final TokenManager tokenManager; - private final SimpleRateLimiter rateLimiter; + private final LingxingRateLimiter rateLimiter; + private final LingxingRequestFactory requestFactory; public LingxingAdapter(String baseUrl, HttpTransport transport, JacksonJsonCodec json, SecretProvider secretProvider, TokenStore tokenStore, LockProvider lockProvider, @@ -79,7 +72,8 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab return tokenClient.fetch(secret.appKey(), secret.appSecret()); } }; - this.rateLimiter = new SimpleRateLimiter(ORDERS_PER_SECOND); + this.rateLimiter = new LingxingRateLimiter(); + this.requestFactory = new LingxingRequestFactory(baseUrl, json, clock); } @Override @@ -147,25 +141,37 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab int length = Math.min(query.pageSize() <= 0 ? 100 : query.pageSize(), LingxingConstants.MAX_PAGE_SIZE); int offset = query.cursor() == null ? 0 : Integer.parseInt(query.cursor()); + Map body = buildOrderListBody(account, from, to, offset, length); - rateLimiter.acquire(); - String body = buildOrderListBody(account, from, to, offset, length); - HttpRequest req = signedPost(ctx, LingxingConstants.PATH_ORDER_LIST, body, "salesOrders.pull"); - + rateLimiter.acquire(LingxingConstants.PATH_ORDER_LIST, LingxingConstants.ORDER_LIST_PER_SECOND); + HttpRequest req = signedRequest(ctx, LingxingConstants.PATH_ORDER_LIST, body, "salesOrders.pull"); HttpResponse resp = transport.execute(req); - Responses.throwIfNotSuccess(resp, "salesOrders.pull"); - List dtos = mapper.parseList(resp.body()); - int total = mapper.parseTotal(resp.body()); + LingxingEnvelope envelope = LingxingEnvelope.of(resp, json, "salesOrders.pull", + ctx.omsStoreId(), ctx.requestId()); + List dtos = mapper.parseList(envelope.body()); List orders = new ArrayList(dtos.size()); for (LingxingOrderDto dto : dtos) { - orders.add(mapper.toSalesOrder(dto, account.omsStoreId(), zone)); + try { + orders.add(mapper.toSalesOrder(dto, account.omsStoreId(), zone)); + } catch (RuntimeException e) { + // 映射失败保留原始报文,交给人工修映射;不要让它以 NPE 形式冒出去 + throw new ValidationException(ChannelException.builder() + .message("lingxing order mapping failed: " + e.getMessage()) + .operation("salesOrders.pull") + .provider(provider().name()) + .omsStoreId(ctx.omsStoreId()) + .requestId(ctx.requestId()) + .rawResponse(envelope.body()), e); + } } + // 满页才可能有下一页;total 存在时再用它兜底,避免最后一页多发一次请求 int nextOffset = offset + dtos.size(); - String nextCursor = (dtos.isEmpty() || nextOffset >= total) ? null : String.valueOf(nextOffset); - return Page.of(orders, nextCursor); + boolean hasMore = dtos.size() >= length + && (envelope.total() < 0 || nextOffset < envelope.total()); + return Page.of(orders, hasMore ? String.valueOf(nextOffset) : null); } /** 单订单详情接口待核对(领星以列表接口为主),先显式拒绝而不是返回 null。 */ @@ -184,46 +190,34 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab // ---------------------------------------------------------------- internals - private String buildOrderListBody(ChannelAccount account, Instant from, Instant to, int offset, int length) { + /** + * 多平台订单列表请求体。 + * + *

字段名以官方文档为准:{@code start_time}/{@code end_time} 是 epoch 秒, + * {@code platform_code} 与 {@code store_id} 都是数组。

+ */ + private Map buildOrderListBody(ChannelAccount account, Instant from, Instant to, + int offset, int length) { Map body = new LinkedHashMap(); body.put("offset", offset); body.put("length", length); + body.put("date_type", "update_time"); + body.put("start_time", from.getEpochSecond()); + body.put("end_time", to.getEpochSecond()); if (account.platformCode() != null) { - body.put("platform_code", account.platformCode()); + body.put("platform_code", Collections.singletonList(account.platformCode())); } if (account.externalStoreId() != null) { - body.put("store_id", account.externalStoreId()); + body.put("store_id", Collections.singletonList(account.externalStoreId())); } - // 领星查询时间为 epoch 秒 - body.put("update_time_start", from.getEpochSecond()); - body.put("update_time_end", to.getEpochSecond()); - return json.toJson(body); + return body; } - private HttpRequest signedPost(ChannelContext ctx, String path, String body, String operation) { + private HttpRequest signedRequest(ChannelContext ctx, String path, Map body, String operation) { ChannelAccount account = ctx.account(); ChannelSecret secret = secretProvider.get(account.credentialRef()); AccessToken token = tokenManager.getOrRefresh(tokenKey(account, secret), secret); - - Map common = new LinkedHashMap(); - common.put("app_key", secret.appKey()); - common.put("timestamp", String.valueOf(Instant.now(clock).getEpochSecond())); - String sign = LingxingSigner.sign(common, secret); - - String url = baseUrl + path - + "?app_key=" + urlEncode(common.get("app_key")) - + "×tamp=" + common.get("timestamp") - + "&sign=" + sign; - - return HttpRequest.builder() - .method("POST") - .url(url) - .header("Content-Type", "application/json") - .header("Authorization", token.tokenType() + " " + token.value()) - .header("X-Request-Id", ctx.requestId()) - .body(body) - .operation(operation) - .build(); + return requestFactory.post(path, body, secret, token, ctx, operation); } /** @@ -234,36 +228,4 @@ public final class LingxingAdapter implements SalesOrderCapable, AggregatorCapab private static String tokenKey(ChannelAccount account, ChannelSecret secret) { return "lingxing:" + secret.appKey(); } - - private static String urlEncode(String v) { - try { - return URLEncoder.encode(v == null ? "" : v, "UTF-8"); - } catch (UnsupportedEncodingException e) { - throw new IllegalStateException(e); - } - } - - /** 简单令牌桶;首期按接口串行即可,后续替换为通用 RateLimiter。 */ - static final class SimpleRateLimiter { - - private final long intervalNanos; - private long nextAllowed; - - SimpleRateLimiter(int permitsPerSecond) { - this.intervalNanos = 1_000_000_000L / permitsPerSecond; - } - - synchronized void acquire() { - long now = System.nanoTime(); - if (now < nextAllowed) { - long waitNanos = nextAllowed - now; - try { - Thread.sleep(waitNanos / 1_000_000L, (int) (waitNanos % 1_000_000L)); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - } - nextAllowed = System.nanoTime() + intervalNanos; - } - } -} +} \ No newline at end of file diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java index 38939da..2e9bfa0 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingConstants.java @@ -21,6 +21,9 @@ public final class LingxingConstants { /** 店铺列表。 */ public static final String PATH_SELLER_LIST = "/pb/mp/shop/v2/getSellerList"; + /** 多平台订单列表令牌桶:10 req/s(亚马逊/VC/Walmart 接口是 1 req/s)。 */ + public static final int ORDER_LIST_PER_SECOND = 10; + /** 订单查询时间跨度上限:31 天。 */ public static final int MAX_QUERY_DAYS = 31; /** 分页 length 上限。 */ diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingEnvelope.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingEnvelope.java new file mode 100644 index 0000000..647a5ad --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingEnvelope.java @@ -0,0 +1,120 @@ +package common.ecommerce.lingxing; + +import common.ecommerce.error.AuthException; +import common.ecommerce.error.ChannelException; +import common.ecommerce.error.PlatformBusinessException; +import common.ecommerce.error.RateLimitException; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.http.Responses; + +/** + * 领星响应信封。 + * + *

领星业务错误一律返回 HTTP 200,只能看 body 里的 {@code code}: + * {@link common.ecommerce.http.Responses#throwIfNotSuccess} 只判 HTTP 状态码,不够用。

+ * + *
    + *
  • {@code 0} / {@code "0"} / {@code "200"}:成功(令牌接口用 "200")
  • + *
  • {@code 3001008}:限流
  • + *
  • {@code 2001003}:token 失效
  • + *
  • {@code 2001006} / {@code 2001007}:签名错误 / 签名过期
  • + *
  • {@code 3001002}:IP 不在白名单
  • + *
+ */ +public final class LingxingEnvelope { + + static final String CODE_RATE_LIMITED = "3001008"; + static final String CODE_TOKEN_INVALID = "2001003"; + static final String CODE_SIGN_ERROR = "2001006"; + static final String CODE_SIGN_EXPIRED = "2001007"; + static final String CODE_IP_DENIED = "3001002"; + + /** 限流响应不带 Retry-After,按 1s 退避。 */ + private static final long DEFAULT_RETRY_AFTER_MILLIS = 1_000L; + + private final String body; + private final String code; + private final String message; + private final int total; + + private LingxingEnvelope(String body, String code, String message, int total) { + this.body = body; + this.code = code; + this.message = message; + this.total = total; + } + + public static LingxingEnvelope of(HttpResponse resp, JacksonJsonCodec json, + String operation, String omsStoreId, String requestId) { + Responses.throwIfNotSuccess(resp, operation); + + String body = resp.body(); + String code = json.stringAt(body, "code"); + String message = json.stringAt(body, "message"); + if (message == null) { + message = json.stringAt(body, "msg"); + } + + ChannelException.Builder b = ChannelException.builder() + .message("lingxing code=" + code + " msg=" + message + " on " + operation) + .operation(operation) + .provider(LingxingConstants.ADAPTER_ID) + .omsStoreId(omsStoreId) + .requestId(requestId) + .platformCode(code) + .rawResponse(body); + + if (code == null) { + throw new PlatformBusinessException(b); + } + if (!"0".equals(code) && !"200".equals(code)) { + throw failure(code, b); + } + return new LingxingEnvelope(body, code, message, parseTotal(body, json)); + } + + private static ChannelException failure(String code, ChannelException.Builder b) { + if (CODE_RATE_LIMITED.equals(code)) { + return new RateLimitException(b, DEFAULT_RETRY_AFTER_MILLIS); + } + if (CODE_TOKEN_INVALID.equals(code) || CODE_SIGN_ERROR.equals(code) + || CODE_SIGN_EXPIRED.equals(code) || CODE_IP_DENIED.equals(code)) { + return new AuthException(b); + } + return new PlatformBusinessException(b); + } + + /** 顶层 {@code total} 优先,其次 {@code data.total};都没有返回 -1。 */ + private static int parseTotal(String body, JacksonJsonCodec json) { + String raw = json.stringAt(body, "total"); + if (raw == null) { + raw = json.stringAt(body, "data.total"); + } + if (raw == null) { + return -1; + } + try { + return Integer.parseInt(raw.trim()); + } catch (NumberFormatException e) { + return -1; + } + } + + public String body() { + return body; + } + + public String code() { + return code; + } + + public String message() { + return message; + } + + /** 总数;响应里没有 total 时为 -1。 */ + public int total() { + return total; + } +} \ No newline at end of file diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRateLimiter.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRateLimiter.java new file mode 100644 index 0000000..b94380e --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRateLimiter.java @@ -0,0 +1,64 @@ +package common.ecommerce.lingxing; + +import java.util.HashMap; +import java.util.Map; +import java.util.function.LongSupplier; + +/** + * 按接口路径的令牌桶。 + * + *

领星各接口容量不同:亚马逊 / VC / Walmart 是 1 req/s,多平台 / 结算是 10 req/s, + * 统一按 10 会直接把亚马逊接口打成 {@code 3001008}。

+ * + *

进程内实现,多实例部署会叠加;需要跨实例限流时由宿主替换。

+ */ +final class LingxingRateLimiter { + + /** 便于测试注入,生产用 {@link Thread#sleep}。 */ + interface Sleeper { + void sleep(long millis, int nanos); + } + + private final Map nextAllowed = new HashMap(); + private final Sleeper sleeper; + private final LongSupplier nanoClock; + + LingxingRateLimiter() { + this(new Sleeper() { + @Override + public void sleep(long millis, int nanos) { + try { + Thread.sleep(millis, nanos); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + }, new LongSupplier() { + @Override + public long getAsLong() { + return System.nanoTime(); + } + }); + } + + LingxingRateLimiter(Sleeper sleeper, LongSupplier nanoClock) { + this.sleeper = sleeper; + this.nanoClock = nanoClock; + } + + /** 同一路径两次调用之间至少间隔 {@code 1e9 / permitsPerSecond} 纳秒。 */ + 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); + } +} \ No newline at end of file diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRequestFactory.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRequestFactory.java new file mode 100644 index 0000000..d90afb4 --- /dev/null +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingRequestFactory.java @@ -0,0 +1,95 @@ +package common.ecommerce.lingxing; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; + +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.time.Clock; +import java.time.Instant; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 构造已签名的领星请求。 + * + *

签名范围是「业务参数 + {@code access_token} + {@code app_key} + {@code timestamp}」。 + * 集合参数先序列化成 JSON 字符串参与签名,请求体里仍然是数组 + * (与官方 SDK {@code OrderListDemo} 的做法一致)。

+ * + *

{@code access_token} 只放 {@code Authorization} 头、不进 query,但必须参与签名。

+ */ +final class LingxingRequestFactory { + + private final String baseUrl; + private final JacksonJsonCodec json; + private final Clock clock; + + LingxingRequestFactory(String baseUrl, JacksonJsonCodec json, Clock clock) { + this.baseUrl = baseUrl; + this.json = json; + this.clock = clock; + } + + HttpRequest post(String path, Map body, ChannelSecret secret, + AccessToken token, ChannelContext ctx, String operation) { + Map payload = withoutNulls(body); + + Map signParams = new LinkedHashMap(); + for (Map.Entry e : payload.entrySet()) { + signParams.put(e.getKey(), stringify(e.getValue())); + } + signParams.put("access_token", token.value()); + signParams.put("app_key", secret.appKey()); + String timestamp = String.valueOf(Instant.now(clock).getEpochSecond()); + signParams.put("timestamp", timestamp); + + String sign = LingxingSigner.sign(signParams, secret); + + String url = baseUrl + path + + "?app_key=" + urlEncode(secret.appKey()) + + "×tamp=" + timestamp + + "&sign=" + urlEncode(sign); + + return HttpRequest.builder() + .method("POST") + .url(url) + .contentType("application/json") + .header("Authorization", token.tokenType() + " " + token.value()) + .header("X-Request-Id", ctx.requestId()) + .body(json.toJson(payload)) + .operation(operation) + .build(); + } + + /** 集合按 JSON 参与签名;其余按字符串。 */ + private String stringify(Object value) { + if (value instanceof Collection || value instanceof Map) { + return json.toJson(value); + } + return String.valueOf(value); + } + + /** 值为 null 的字段既不签名也不发送,避免两端对「null 算不算参数」理解不一致。 */ + private static Map withoutNulls(Map body) { + Map out = new LinkedHashMap(); + for (Map.Entry e : body.entrySet()) { + if (e.getValue() != null) { + out.put(e.getKey(), e.getValue()); + } + } + return out; + } + + private static String urlEncode(String v) { + try { + return URLEncoder.encode(v == null ? "" : v, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new IllegalStateException(e); + } + } +} \ No newline at end of file diff --git a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingSigner.java b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingSigner.java index 86ce876..3992962 100644 --- a/lingxing/src/main/java/common/ecommerce/lingxing/LingxingSigner.java +++ b/lingxing/src/main/java/common/ecommerce/lingxing/LingxingSigner.java @@ -2,57 +2,96 @@ package common.ecommerce.lingxing; import common.ecommerce.spi.ChannelSecret; +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Map; /** - * 领星签名:公共参数按 ASCII 升序拼接 {@code key+value},前后拼 appSecret,MD5 小写。 + * 领星签名(2026 版官方算法,对照 openapi-sdk-java 的 ApiSign / AesUtil)。 * - *

待核对:官方文档对 sign 的大小写与大写规则未在需求文档中固化, - * 实现集中在 {@link #sign(Map, String)} 一处,便于联调时调整。

+ *
    + *
  1. 业务参数 + {@code access_token} + {@code app_key} + {@code timestamp},按 key ASCII 升序
  2. + *
  3. 拼成 {@code k=v&k=v},value 做 trim;集合类型必须先 JSON 序列化再参与签名
  4. + *
  5. MD5 32 位大写
  6. + *
  7. AES/ECB/PKCS5Padding 加密,密钥是 appId(即 app_key),输出 Base64
  8. + *
+ * + *

注意:SDK 里 {@code ApiSign.sign(params, appSecret)} 的第二个形参命名有误, + * 实际传的是 appId;appSecret 不参与签名。

*/ public final class LingxingSigner { + private static final String AES_ECB = "AES/ECB/PKCS5Padding"; + private static final char[] HEX = "0123456789ABCDEF".toCharArray(); + private LingxingSigner() { } + /** 便捷:appId 就是凭证里的 appKey。 */ + public static String sign(Map params, ChannelSecret secret) { + return sign(params, secret.appKey()); + } + /** - * @param params 参与签名的参数(不含 sign),值不得为 null - * @param appSecret 应用密钥 + * @param params 参与签名的全部参数(含 access_token / app_key / timestamp),不含 sign + * @param appId 应用 AppID,同时作为 AES 密钥,必须 16/24/32 字节 */ - public static String sign(Map params, String appSecret) { + public static String sign(Map params, String appId) { + return aesEcbBase64(md5HexUpper(canonical(params)), appId); + } + + /** 拼接待签名原文:按 key 升序,跳过 null,value trim。 */ + static String canonical(Map params) { List keys = new ArrayList(params.keySet()); Collections.sort(keys); - StringBuilder sb = new StringBuilder(appSecret); - for (String k : keys) { - sb.append(k).append(params.get(k)); + StringBuilder sb = new StringBuilder(); + for (String key : keys) { + String value = params.get(key); + if (value == null) { + continue; + } + if (sb.length() > 0) { + sb.append('&'); + } + sb.append(key).append('=').append(value.trim()); } - sb.append(appSecret); - return md5Hex(sb.toString()); + return sb.toString(); } - /** 便捷:从凭证取 appSecret。 */ - public static String sign(Map params, ChannelSecret secret) { - return sign(params, secret.appSecret()); - } - - static String md5Hex(String raw) { + static String md5HexUpper(String raw) { 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)); + byte[] digest = MessageDigest.getInstance("MD5").digest(raw.getBytes(StandardCharsets.UTF_8)); + char[] out = new char[digest.length * 2]; + for (int i = 0; i < digest.length; i++) { + int v = digest[i] & 0xFF; + out[i * 2] = HEX[v >>> 4]; + out[i * 2 + 1] = HEX[v & 0x0F]; } - return sb.toString(); + return new String(out); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("MD5 not available", e); } } -} + + static String aesEcbBase64(String plain, String appId) { + byte[] key = appId.getBytes(StandardCharsets.UTF_8); + if (key.length != 16 && key.length != 24 && key.length != 32) { + throw new IllegalArgumentException( + "领星 appId 必须是 16/24/32 字节(AES 密钥),实际 " + key.length + " 字节:" + appId); + } + try { + Cipher cipher = Cipher.getInstance(AES_ECB); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES")); + return Base64.getEncoder().encodeToString(cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8))); + } catch (Exception e) { + throw new IllegalStateException("领星签名 AES 加密失败", e); + } + } +} \ No newline at end of file diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java index a8c2d24..c403ff1 100644 --- a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingAdapterTest.java @@ -43,6 +43,9 @@ class LingxingAdapterTest { private static final String CREDENTIAL_REF = "kms://test/lingxing/001"; + /** 领星 appId 同时是 AES 密钥,必须 16 字节;测试用假值。 */ + private static final String APP_KEY = "ak_testappkey123"; + private FakeTransport transport; private InMemoryTokenStore tokenStore; private InMemoryAccounts accounts; @@ -68,7 +71,7 @@ class LingxingAdapterTest { .build(); accounts.put(account).putSecret(CREDENTIAL_REF, ChannelSecret.builder() - .appKey("test-app-key") + .appKey(APP_KEY) .appSecret("test-app-secret") .build()); @@ -109,8 +112,8 @@ class LingxingAdapterTest { adapter.pull(ctx, q); assertEquals(1, tokenStore.saveCount(), "token should be refreshed only once"); - assertEquals(1, locks.acquireCount("token-refresh:lingxing:test-app-key")); - assertNotNull(tokenStore.get("lingxing:test-app-key").orElse(null)); + assertEquals(1, locks.acquireCount("token-refresh:lingxing:" + APP_KEY)); + assertNotNull(tokenStore.get("lingxing:" + APP_KEY).orElse(null)); } @Test @@ -121,12 +124,12 @@ class LingxingAdapterTest { .build()); common.ecommerce.http.HttpRequest last = transport.lastRequest(); - assertTrue(last.url().contains("app_key=test-app-key"), last.url()); + assertTrue(last.url().contains("app_key=" + APP_KEY), last.url()); assertTrue(last.url().contains("sign="), last.url()); assertEquals("Bearer lx-access-token-abc", last.headers().get("Authorization")); assertEquals("req-1", last.headers().get("X-Request-Id")); - assertTrue(last.body().contains("\"platform_code\":10008"), last.body()); - assertTrue(last.body().contains("\"store_id\":\"1108413237731\""), last.body()); + assertTrue(last.body().contains("\"platform_code\":[10008]"), last.body()); + assertTrue(last.body().contains("\"store_id\":[\"1108413237731\"]"), last.body()); } @Test @@ -139,8 +142,9 @@ class LingxingAdapterTest { String body = transport.lastRequest().body(); long end = Instant.parse("2026-10-26T00:00:00Z").getEpochSecond(); long expectedStart = Instant.parse("2026-10-26T00:00:00Z").minus(Duration.ofDays(31)).getEpochSecond(); - assertTrue(body.contains("\"update_time_end\":" + end), body); - assertTrue(body.contains("\"update_time_start\":" + expectedStart), body); + assertTrue(body.contains("\"end_time\":" + end), body); + assertTrue(body.contains("\"start_time\":" + expectedStart), body); + assertTrue(body.contains("\"date_type\":\"update_time\""), body); } @Test diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingEnvelopeTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingEnvelopeTest.java new file mode 100644 index 0000000..3cb663c --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingEnvelopeTest.java @@ -0,0 +1,67 @@ +package common.ecommerce.lingxing; + +import common.ecommerce.error.AuthException; +import common.ecommerce.error.PlatformBusinessException; +import common.ecommerce.error.RateLimitException; +import common.ecommerce.http.HttpResponse; +import common.ecommerce.http.JacksonJsonCodec; +import org.junit.jupiter.api.Test; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +class LingxingEnvelopeTest { + + private final JacksonJsonCodec json = new JacksonJsonCodec(); + + private LingxingEnvelope parse(String body) { + return LingxingEnvelope.of( + HttpResponse.of(200, Collections.emptyMap(), body, 1L), + json, "salesOrders.pull", "oms-1", "req-1"); + } + + @Test + void acceptsZeroCode() { + LingxingEnvelope e = parse("{\"code\":0,\"message\":\"success\",\"data\":{\"total\":3,\"list\":[]}}"); + assertEquals("0", e.code()); + assertEquals(3, e.total()); + } + + @Test + void acceptsTwoHundredCode() { + LingxingEnvelope e = parse("{\"code\":\"200\",\"msg\":\"OK\",\"data\":{}}"); + assertEquals("200", e.code()); + assertEquals(-1, e.total()); + } + + @Test + void rateLimitCodeBecomesRateLimitException() { + assertThrows(RateLimitException.class, + () -> parse("{\"code\":3001008,\"msg\":\"too many requests\"}")); + } + + @Test + void signErrorBecomesAuthException() { + assertThrows(AuthException.class, + () -> parse("{\"code\":2001006,\"msg\":\"sign not correct\"}")); + } + + @Test + void unknownCodeBecomesBusinessException() { + PlatformBusinessException e = assertThrows(PlatformBusinessException.class, + () -> parse("{\"code\":3001001,\"msg\":\"bad param\"}")); + assertEquals("3001001", e.platformCode()); + } + + @Test + void totalFallsBackToDataTotal() { + assertEquals(7, parse("{\"code\":0,\"data\":{\"total\":\"7\",\"list\":[]}}").total()); + } + + @Test + void topLevelTotalWins() { + assertEquals(9, parse("{\"code\":0,\"total\":9,\"data\":{\"total\":7}}").total()); + } +} \ No newline at end of file diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java index 3086537..1aba5eb 100644 --- a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingLiveSmokeTest.java @@ -83,7 +83,7 @@ class LingxingLiveSmokeTest { Page page = adapter.pull(ctx, SalesOrderQuery.builder() .updatedAfter(from) .updatedBefore(to) - .pageSize(5) + .pageSize(20) .build()); System.out.println("[orders] window=" + from + " .. " + to @@ -96,7 +96,7 @@ class LingxingLiveSmokeTest { + " lines=" + o.lines().size() + " utc=" + o.occurredAt().utc()); } - assertFalse(page.size() > 5, "pageSize 未被平台遵守"); + assertFalse(page.size() > 20, "pageSize 未被平台遵守"); } // ---------------------------------------------------------------- helpers diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRateLimiterTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRateLimiterTest.java new file mode 100644 index 0000000..336392a --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRateLimiterTest.java @@ -0,0 +1,66 @@ +package common.ecommerce.lingxing; + +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LingxingRateLimiterTest { + + /** 可推进的纳秒时钟,sleep 时同步前进。 */ + private static final class FakeNano { + private long nanos; + + long now() { + return nanos; + } + + void advance(long delta) { + nanos += delta; + } + } + + private final FakeNano clock = new FakeNano(); + private final List sleeps = new ArrayList(); + private final LingxingRateLimiter limiter = new LingxingRateLimiter( + (millis, nanos) -> { + long total = millis * 1_000_000L + nanos; + sleeps.add(total); + clock.advance(total); + }, + clock::now); + + @Test + void firstCallDoesNotSleep() { + limiter.acquire("/a", 1); + assertTrue(sleeps.isEmpty()); + } + + @Test + void onePerSecondWaitsOneSecond() { + limiter.acquire("/a", 1); + limiter.acquire("/a", 1); + + assertEquals(1, sleeps.size()); + assertEquals(1_000_000_000L, sleeps.get(0).longValue()); + } + + @Test + void tenPerSecondWaitsOneHundredMillis() { + limiter.acquire("/a", 10); + limiter.acquire("/a", 10); + + assertEquals(1, sleeps.size()); + assertEquals(100_000_000L, sleeps.get(0).longValue()); + } + + @Test + void differentPathsHaveIndependentBuckets() { + limiter.acquire("/a", 1); + limiter.acquire("/b", 1); + assertTrue(sleeps.isEmpty()); + } +} \ No newline at end of file diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRequestFactoryTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRequestFactoryTest.java new file mode 100644 index 0000000..4f18ac0 --- /dev/null +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingRequestFactoryTest.java @@ -0,0 +1,73 @@ +package common.ecommerce.lingxing; + +import common.ecommerce.http.HttpRequest; +import common.ecommerce.http.JacksonJsonCodec; +import common.ecommerce.model.ChannelProvider; +import common.ecommerce.model.Platform; +import common.ecommerce.model.account.AccountKey; +import common.ecommerce.model.account.ChannelAccount; +import common.ecommerce.sdk.ChannelContext; +import common.ecommerce.spi.AccessToken; +import common.ecommerce.spi.ChannelSecret; +import org.junit.jupiter.api.Test; + +import java.net.URLEncoder; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class LingxingRequestFactoryTest { + + private static final String APP_ID = "ak_1234567890123"; + private static final String TOKEN = "805181e7-4365-468c-bf5c-8c0762a1d358"; + + @Test + void signsAccessTokenAndBusinessParamsAndEncodesSign() throws Exception { + Clock clock = Clock.fixed(Instant.ofEpochSecond(1760000000L), ZoneOffset.UTC); + ChannelSecret secret = ChannelSecret.builder().appKey(APP_ID).appSecret("not-used").build(); + AccessToken token = AccessToken.builder() + .value(TOKEN) + .tokenType("Bearer") + .expiresAt(Instant.ofEpochSecond(1760007200L)) + .build(); + + Map body = new LinkedHashMap(); + body.put("offset", 0); + body.put("length", 200); + body.put("platform_code", Arrays.asList(10008, 10011)); + + ChannelAccount account = ChannelAccount.builder() + .key(AccountKey.of(ChannelProvider.LINGXING, Platform.WALMART_SC, "oms-1")) + .externalStoreId("1108413237731") + .platformCode(10008) + .credentialRef("ref") + .marketplaceZone("America/Los_Angeles") + .currency("USD") + .build(); + ChannelContext ctx = ChannelContext.of(account, "req-1", clock); + + HttpRequest req = new LingxingRequestFactory("https://openapi.lingxing.com", + new JacksonJsonCodec(), clock) + .post("/pb/mp/order/v2/list", body, secret, token, ctx, "salesOrders.pull"); + + Map signParams = new LinkedHashMap(); + signParams.put("offset", "0"); + signParams.put("length", "200"); + signParams.put("platform_code", "[10008,10011]"); + signParams.put("access_token", TOKEN); + signParams.put("app_key", APP_ID); + signParams.put("timestamp", "1760000000"); + String sign = LingxingSigner.sign(signParams, APP_ID); + + assertTrue(req.url().endsWith("&sign=" + URLEncoder.encode(sign, "UTF-8")), req.url()); + assertEquals("Bearer " + TOKEN, req.headers().get("Authorization")); + assertEquals("req-1", req.headers().get("X-Request-Id")); + assertEquals("{\"offset\":0,\"length\":200,\"platform_code\":[10008,10011]}", req.body()); + } +} \ No newline at end of file diff --git a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingSignerTest.java b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingSignerTest.java index be439af..21bdb58 100644 --- a/lingxing/src/test/java/common/ecommerce/lingxing/LingxingSignerTest.java +++ b/lingxing/src/test/java/common/ecommerce/lingxing/LingxingSignerTest.java @@ -1,54 +1,51 @@ package common.ecommerce.lingxing; -import common.ecommerce.http.JsonCodec; import org.junit.jupiter.api.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; class LingxingSignerTest { - @Test - void signatureIsOrderIndependent() { - Map a = new LinkedHashMap(); - a.put("app_key", "k1"); - a.put("timestamp", "1793001600"); - - Map b = new LinkedHashMap(); - b.put("timestamp", "1793001600"); - b.put("app_key", "k1"); - - assertEquals(LingxingSigner.sign(a, "secret"), LingxingSigner.sign(b, "secret")); - } + private static final String APP_ID = "ak_1234567890123"; @Test - void signatureIs32LowercaseHex() { + void canonicalIsSortedAndTrimmed() { Map p = new LinkedHashMap(); - p.put("app_key", "k1"); - p.put("timestamp", "1793001600"); - String sign = LingxingSigner.sign(p, "secret"); - assertEquals(32, sign.length()); - assertEquals(sign.toLowerCase(), sign); - assertEquals(true, sign.matches("[0-9a-f]{32}")); + p.put("timestamp", "1760000000"); + p.put("app_key", APP_ID); + p.put("offset", " 0 "); + assertEquals("app_key=" + APP_ID + "&offset=0×tamp=1760000000", + LingxingSigner.canonical(p)); } @Test - void differentSecretDifferentSignature() { + void nullValuesAreSkipped() { Map p = new LinkedHashMap(); - p.put("app_key", "k1"); - assertNotEquals(LingxingSigner.sign(p, "a"), LingxingSigner.sign(p, "b")); + p.put("b", null); + p.put("a", "1"); + assertEquals("a=1", LingxingSigner.canonical(p)); } + /** 官方固定向量;MD5 与最终 sign 均已离线复算确认。 */ @Test - void knownVector() { - // 固定向量:appSecret + "app_key" + "k1" + "timestamp" + "1793001600" + appSecret + void matchesOfficialVector() { Map p = new LinkedHashMap(); - p.put("app_key", "k1"); - p.put("timestamp", "1793001600"); - assertEquals(LingxingSigner.md5Hex("secretapp_keyk1timestamp1793001600secret"), - LingxingSigner.sign(p, "secret")); + p.put("timestamp", "1760000000"); + p.put("access_token", "805181e7-4365-468c-bf5c-8c0762a1d358"); + p.put("app_key", APP_ID); + p.put("offset", "0"); + p.put("length", "200"); + p.put("platform_code", "[10008,10011]"); + + String expected = "access_token=805181e7-4365-468c-bf5c-8c0762a1d358" + + "&app_key=" + APP_ID + + "&length=200&offset=0&platform_code=[10008,10011]×tamp=1760000000"; + assertEquals(expected, LingxingSigner.canonical(p)); + assertEquals("7B96947C5EBDC4A48600F13476982A25", LingxingSigner.md5HexUpper(expected)); + assertEquals("dt+kVetT8x7alI8wS1ClLRLxLX/bs9TKjyBUZL5zde8jNWg6lba39sPCfqtfAdVT", + LingxingSigner.sign(p, APP_ID)); } -} +} \ No newline at end of file