Browse Source

feat(warehouse): 回调链路 —— 按 provider 的 SDK 入口 + HMAC 验签 + 统一出参

回调是仓方主动推送,SDK 不监听端口:OMS 暴露 HTTP(如 /user/callback/yqn),
取到 headers 与原始 body 后交给 SDK,SDK 只做「验签 + 解析」。

三处新增:

1. 入口 WarehouseSdk.webhook(provider, secret, headers, rawBody, nowMillis)
   原来只能 warehouses(warehouseCode, conn).parseWebhook(...),但回调进来时
   只有 provider、没有 warehouseCode。新入口按 provider 分派,不查账户。

2. 出参 WarehouseCallback
   原 WarehouseEvent 只有 5 个字段,装不下退货的明细行 id / 处理方式,
   也装不下入库实收量。改为「公共头 + 按业务分型载荷」:outbound / returns /
   inbound 三个可空字段,按 eventType 取用;rawBody 原样保留供回溯。
   提供指纹方法供宿主去重(报文无事件 id 时使用)。

3. 验签能力 WebhookSignatures
   HMAC-SHA256 + Base64、恒定时间比较(避免时间差泄漏签名前缀)、
   时间戳窗口校验、大小写不敏感的取头。

运去哪面单回调(API 149)实现:
   signature = Base64(HmacSHA256(appSecret, appKey|timestamp|rawBody))
   头:X-AppKey / X-Timestamp / X-Signature
   时间戳单位文档未写明,按位数兼容秒与毫秒(<=10 位按秒),联调后收紧。

新增 YqnLabelCallbackParserTest(10 个):验签通过 / 篡改 body / 错误密钥 /
缺头 / 时间窗过期 / 头名大小写 / X-AppKey 回退 / 载荷解析 / 指纹 / 时间戳单位。

Co-Authored-By: Claude <noreply@anthropic.com>
feature/supplier-lingxing
chenchuchuan 1 week ago
parent
commit
4eb15bd91a
  1. 9
      README.md
  2. 77
      warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/capability/WarehouseWebhookCapable.java
  3. 409
      warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/model/WarehouseCallback.java
  4. 12
      warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WarehouseOperations.java
  5. 47
      warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WarehouseSdk.java
  6. 122
      warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WebhookSignatures.java
  7. 27
      warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/adapter/YqnAdapter.java
  8. 33
      warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/dto/YqnLabelCallbackDtos.java
  9. 131
      warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/webhook/YqnLabelCallbackParser.java
  10. 161
      warehouse-sdk-yqn/src/test/java/common/ecommerce/yqn/webhook/YqnLabelCallbackParserTest.java

9
README.md

@ -309,7 +309,7 @@ common.ecommerce @@ -309,7 +309,7 @@ common.ecommerce
│ │ InboundReceipt / ReturnCommand / ReturnProcessCommand /
│ │ WarehouseReturn / TransferCommand / TransferOrder(含 errorCode/errorReason 等)/
│ │ BillingDocument / FeeQuery / FeeEstimateQuery / FeeEstimateResult /
│ │ TrackEvent / TrackingInfo / DestructionCommand / DestructionOrder /
│ │ TrackEvent / TrackingInfo / WarehouseCallback / DestructionCommand / DestructionOrder /
│ │ BoxLabelCommand / SkuLabelCommand / LabelPrintTask / WarehouseLabel /
│ │ LogisticsProduct / WarehouseInfo
│ ├── capability OutboundCapable / InventoryCapable / InboundCapable /
@ -324,9 +324,11 @@ common.ecommerce @@ -324,9 +324,11 @@ common.ecommerce
│ │ UnmatchedCallbackStore
│ └── sdk WarehouseSdk / WarehouseOperations / WarehouseOutbounds /
│ WarehouseAdapter / WarehouseAdapterFactory / WarehouseContext /
│ WarehouseConnection(主基址 + 可选辅助基址)/ WarehouseWriteScope
│ WarehouseConnection(主基址 + 可选辅助基址)/ WarehouseWriteScope /
│ WebhookSignatures(HMAC / 恒定时间比较 / 时间窗)
│
├── yqn 运去哪三方仓(warehouse-sdk-yqn)
│ ├── webhook 回调验签与解析(YqnLabelCallbackParser)
│ ├── dto (按接口拆分,一个接口一个文件)
│ │ YqnCreateOrderDtos / YqnOrderDetailDtos / YqnCancelOrderDtos /
│ │ YqnProductDtos / YqnFeeDetailDtos / YqnInventoryDtos /
@ -334,7 +336,8 @@ common.ecommerce @@ -334,7 +336,8 @@ common.ecommerce
│ │ YqnCreateSaleReturnDtos / YqnReturnProcessDtos /
│ │ YqnFeeEstimateDtos / YqnTrackingDtos / YqnDestroyPlanDtos /
│ │ YqnBoxLabelDtos / YqnSkuLabelDtos /
│ │ YqnLogisticsProductDtos / YqnWarehouseDtos
│ │ YqnLogisticsProductDtos / YqnWarehouseDtos /
│ │ YqnLabelCallbackDtos
│ ├── YqnConstants 端点、路径、固定 token 请求头名、限流
│ ├── adapter YqnAdapter(P1 出库) / YqnAdapterFactory / YqnOutboundMapper
│ ├── dto YqnDtos(字段级契约待打样核对)

77
warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/capability/WarehouseWebhookCapable.java

@ -1,5 +1,7 @@ @@ -1,5 +1,7 @@
package common.ecommerce.warehouse.capability;
import common.ecommerce.shared.spi.ChannelSecret;
import common.ecommerce.warehouse.model.WarehouseCallback;
import common.ecommerce.warehouse.sdk.WarehouseAdapter;
import common.ecommerce.warehouse.sdk.WarehouseContext;
@ -7,61 +9,40 @@ import java.util.List; @@ -7,61 +9,40 @@ import java.util.List;
import java.util.Map;
/**
* 状态回调能力:验签 + 事件解析。宿主 HTTP 入口调用,SDK 不监听端口。
* 状态回调能力:验签 + 解析。宿主 HTTP 入口调用,SDK <b>不监听端口</b>。
*
* <p>典型链路:仓方推送到 OMS 的 {@code /user/callback/yqn} → 宿主取 headers 与
* 原始 body → 调 {@code sdk.webhook(provider, secret, headers, body, now)} →
* 拿到 {@link WarehouseCallback} 列表后落库。</p>
*
* <p><b>验签与解析分开</b>:验签失败必须直接拒绝(4xx、不重试),解析失败则要看
* 是否需要留档。合成一个方法会让宿主无法区分这两种情况。</p>
*/
public interface WarehouseWebhookCapable extends WarehouseAdapter {
/**
* 验签。
*
* <p>各仓算法不同(HMAC 拼串、固定 token、时间窗),由适配器决定;
* 通用能力见 {@code WebhookSignatures}。</p>
*
* @param secret 只用于验签的凭据(通常取 {@code appSecret}),SDK 不缓存
* @throws common.ecommerce.warehouse.error.WarehouseWebhookVerificationException 验签或时间戳失败
*/
boolean verify(WarehouseContext ctx, Map<String, String> headers, String rawBody);
/** 解析事件,归一化为仓无关的键值。 */
List<WarehouseEvent> parse(WarehouseContext ctx, Map<String, String> headers, String rawBody);
/** 归一化后的事件。 */
final class WarehouseEvent {
private final String eventId;
private final String eventType;
private final String providerOrderId;
private final String status;
private final String occurredAt;
private WarehouseEvent(String eventId, String eventType, String providerOrderId,
String status, String occurredAt) {
this.eventId = eventId;
this.eventType = eventType;
this.providerOrderId = providerOrderId;
this.status = status;
this.occurredAt = occurredAt;
}
public static WarehouseEvent of(String eventId, String eventType, String providerOrderId,
String status, String occurredAt) {
return new WarehouseEvent(eventId, eventType, providerOrderId, status, occurredAt);
}
public String eventId() {
return eventId;
}
void verify(ChannelSecret secret, Map<String, String> headers, String rawBody,
long nowMillis);
public String eventType() {
return eventType;
}
public String providerOrderId() {
return providerOrderId;
}
public String status() {
return status;
}
public String occurredAt() {
return occurredAt;
}
}
/**
* 解析事件,归一化为 {@link WarehouseCallback}。
*
* <p>一条回调可能对应多个事件(如批量推送),所以返回列表。
* <b>不在这里做去重</b>——去重需要宿主存储,SDK 只解析。</p>
*
* @param ctx 上下文;只用到 provider 与请求 id,业务字段以报文为准
* @param secret 验签用的同一份凭据;部分实现需要在解析时再取一次
* @param headers 原始请求头
* @param rawBody 原始请求体(一字不改,必须用它解析,不要用反序列化后的对象)
*/
List<WarehouseCallback> parse(WarehouseContext ctx, ChannelSecret secret,
Map<String, String> headers, String rawBody);
}

409
warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/model/WarehouseCallback.java

@ -0,0 +1,409 @@ @@ -0,0 +1,409 @@
package common.ecommerce.warehouse.model;
import common.ecommerce.warehouse.enums.WarehouseProvider;
import java.time.Instant;
/**
* 仓方主动推送的回调事件(统一出参)。
*
* <p>由 {@code WarehouseSdk.webhook(...)} 返回,宿主 HTTP 入口拿到后按业务落库。
* SDK 不监听端口、不做去重存储,只负责「验签 + 解析成统一结构」。</p>
*
* <p>不同业务的载荷放在各自的可空字段里,按 {@link #eventType()} 区分:
* 出库存 {@link #outbound()},退货存 {@link #returns()},入库存 {@link #inbound()}。
* 没用到的字段为 null,不用再建一套平行的类型层级。</p>
*
* <p>{@link #rawBody()} 原样保留:解析出错或以后加字段时,它是唯一能回溯的依据。</p>
*/
public final class WarehouseCallback {
private final WarehouseProvider sourceProvider;
/** 仓方给的事件 id;没有时用 {@link #fingerprint()} 去重。 */
private final String eventId;
/** 仓方的事件类型原值,如 {@code LABEL_PURCHASED};不猜语义。 */
private final String eventType;
/** 仓方仓 code;报文未给时为 null。 */
private final String providerWarehouseCode;
/** 仓方单据号(运去哪 {@code orderNo})。 */
private final String providerOrderNo;
/** 我们下发的来源单号(运去哪 {@code sourceNo});报文未回传时为 null。 */
private final String requestNo;
/** 事件发生时间;报文未给时为 null。 */
private final Instant occurredAt;
private final String rawBody;
private final OutboundPayload outbound;
private final ReturnPayload returns;
private final InboundPayload inbound;
private WarehouseCallback(Builder b) {
this.sourceProvider = b.sourceProvider;
this.eventId = b.eventId;
this.eventType = b.eventType;
this.providerWarehouseCode = b.providerWarehouseCode;
this.providerOrderNo = b.providerOrderNo;
this.requestNo = b.requestNo;
this.occurredAt = b.occurredAt;
this.rawBody = b.rawBody;
this.outbound = b.outbound;
this.returns = b.returns;
this.inbound = b.inbound;
}
public static Builder builder() {
return new Builder();
}
public WarehouseProvider sourceProvider() {
return sourceProvider;
}
public String eventId() {
return eventId;
}
public String eventType() {
return eventType;
}
public String providerWarehouseCode() {
return providerWarehouseCode;
}
public String providerOrderNo() {
return providerOrderNo;
}
public String requestNo() {
return requestNo;
}
public Instant occurredAt() {
return occurredAt;
}
/** 原始报文;排查与回溯用。 */
public String rawBody() {
return rawBody;
}
/** 出库类载荷;非出库事件为 null。 */
public OutboundPayload outbound() {
return outbound;
}
/** 退货类载荷;非退货事件为 null。 */
public ReturnPayload returns() {
return returns;
}
/** 入库类载荷;非入库事件为 null。 */
public InboundPayload inbound() {
return inbound;
}
/**
* 去重指纹:仓方没给事件 id 时用它。
*
* <p>参与计算的字段都是「同一事件重复推送时不变」的:类型 + 仓单号 + 来源单号 +
* 发生时间。载荷内容不参与——载荷里可能有随推送变化的字段(如重试计数)。</p>
*/
public String fingerprint() {
return sourceProvider + "|" + eventType + "|" + providerOrderNo + "|"
+ requestNo + "|" + occurredAt;
}
/** 出库 / 面单类载荷。 */
public static final class OutboundPayload {
/** 面单追踪号。 */
private final String trackingNumber;
/** 承运商。 */
private final String carrier;
/** 发货方式码。 */
private final String shippingMethodCode;
/** 配货单号。 */
private final String deliverOrderNo;
private OutboundPayload(Builder b) {
this.trackingNumber = b.trackingNumber;
this.carrier = b.carrier;
this.shippingMethodCode = b.shippingMethodCode;
this.deliverOrderNo = b.deliverOrderNo;
}
public static Builder builder() {
return new Builder();
}
public String trackingNumber() {
return trackingNumber;
}
public String carrier() {
return carrier;
}
public String shippingMethodCode() {
return shippingMethodCode;
}
public String deliverOrderNo() {
return deliverOrderNo;
}
public static final class Builder {
private String trackingNumber;
private String carrier;
private String shippingMethodCode;
private String deliverOrderNo;
public Builder trackingNumber(String v) {
this.trackingNumber = v;
return this;
}
public Builder carrier(String v) {
this.carrier = v;
return this;
}
public Builder shippingMethodCode(String v) {
this.shippingMethodCode = v;
return this;
}
public Builder deliverOrderNo(String v) {
this.deliverOrderNo = v;
return this;
}
public OutboundPayload build() {
return new OutboundPayload(this);
}
}
}
/**
* 退货类载荷。
*
* <p>{@link ReturnLinePayload#lineId()} 是仓侧明细行 id——API 77(退货条目处理)
* 的操作键,只能从回调里拿。</p>
*/
public static final class ReturnPayload {
private final java.util.List<ReturnLinePayload> lines;
private ReturnPayload(Builder b) {
this.lines = java.util.Collections.unmodifiableList(
new java.util.ArrayList<ReturnLinePayload>(b.lines));
}
public static Builder builder() {
return new Builder();
}
public java.util.List<ReturnLinePayload> lines() {
return lines;
}
public static final class Builder {
private final java.util.List<ReturnLinePayload> lines =
new java.util.ArrayList<ReturnLinePayload>();
public Builder line(ReturnLinePayload v) {
this.lines.add(v);
return this;
}
public ReturnPayload build() {
return new ReturnPayload(this);
}
}
}
/** 退货单的一行。 */
public static final class ReturnLinePayload {
private final Long lineId;
private final String providerSku;
private final Integer quantity;
/** 仓方处理方式原值;语义解释由适配器对应的平台枚举负责。 */
private final String disposition;
private ReturnLinePayload(Builder b) {
this.lineId = b.lineId;
this.providerSku = b.providerSku;
this.quantity = b.quantity;
this.disposition = b.disposition;
}
public static Builder builder() {
return new Builder();
}
public Long lineId() {
return lineId;
}
public String providerSku() {
return providerSku;
}
public Integer quantity() {
return quantity;
}
public String disposition() {
return disposition;
}
public static final class Builder {
private Long lineId;
private String providerSku;
private Integer quantity;
private String disposition;
public Builder lineId(Long v) {
this.lineId = v;
return this;
}
public Builder providerSku(String v) {
this.providerSku = v;
return this;
}
public Builder quantity(Integer v) {
this.quantity = v;
return this;
}
public Builder disposition(String v) {
this.disposition = v;
return this;
}
public ReturnLinePayload build() {
return new ReturnLinePayload(this);
}
}
}
/** 入库类载荷。 */
public static final class InboundPayload {
private final Integer receivedQuantity;
private final Integer cartonQuantity;
private InboundPayload(Builder b) {
this.receivedQuantity = b.receivedQuantity;
this.cartonQuantity = b.cartonQuantity;
}
public static Builder builder() {
return new Builder();
}
public Integer receivedQuantity() {
return receivedQuantity;
}
public Integer cartonQuantity() {
return cartonQuantity;
}
public static final class Builder {
private Integer receivedQuantity;
private Integer cartonQuantity;
public Builder receivedQuantity(Integer v) {
this.receivedQuantity = v;
return this;
}
public Builder cartonQuantity(Integer v) {
this.cartonQuantity = v;
return this;
}
public InboundPayload build() {
return new InboundPayload(this);
}
}
}
public static final class Builder {
private WarehouseProvider sourceProvider;
private String eventId;
private String eventType;
private String providerWarehouseCode;
private String providerOrderNo;
private String requestNo;
private Instant occurredAt;
private String rawBody;
private OutboundPayload outbound;
private ReturnPayload returns;
private InboundPayload inbound;
public Builder sourceProvider(WarehouseProvider v) {
this.sourceProvider = v;
return this;
}
public Builder eventId(String v) {
this.eventId = v;
return this;
}
public Builder eventType(String v) {
this.eventType = v;
return this;
}
public Builder providerWarehouseCode(String v) {
this.providerWarehouseCode = v;
return this;
}
public Builder providerOrderNo(String v) {
this.providerOrderNo = v;
return this;
}
public Builder requestNo(String v) {
this.requestNo = v;
return this;
}
public Builder occurredAt(Instant v) {
this.occurredAt = v;
return this;
}
public Builder rawBody(String v) {
this.rawBody = v;
return this;
}
public Builder outbound(OutboundPayload v) {
this.outbound = v;
return this;
}
public Builder returns(ReturnPayload v) {
this.returns = v;
return this;
}
public Builder inbound(InboundPayload v) {
this.inbound = v;
return this;
}
public WarehouseCallback build() {
return new WarehouseCallback(this);
}
}
}

12
warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WarehouseOperations.java

@ -19,7 +19,6 @@ import common.ecommerce.warehouse.model.FeeEstimateResult; @@ -19,7 +19,6 @@ import common.ecommerce.warehouse.model.FeeEstimateResult;
import common.ecommerce.warehouse.capability.WarehouseProduct;
import common.ecommerce.warehouse.capability.WarehouseProductCapable;
import common.ecommerce.warehouse.capability.WarehouseReturnCapable;
import common.ecommerce.warehouse.capability.WarehouseWebhookCapable;
import common.ecommerce.warehouse.error.WarehouseUnsupportedCapabilityException;
import common.ecommerce.warehouse.model.BillingDocument;
import common.ecommerce.warehouse.model.FeeQuery;
@ -225,17 +224,6 @@ public final class WarehouseOperations { @@ -225,17 +224,6 @@ public final class WarehouseOperations {
() -> ((DestructionCapable) adapter).getDestruction(ctx, destructionNo));
}
/** 回调验签。 */
public boolean verifyWebhook(Map<String, String> headers, String rawBody) {
require(WarehouseCapability.WEBHOOK, WarehouseWebhookCapable.class);
return ((WarehouseWebhookCapable) adapter).verify(ctx, headers, rawBody);
}
/** 回调解析。 */
public List<WarehouseWebhookCapable.WarehouseEvent> parseWebhook(Map<String, String> headers, String rawBody) {
require(WarehouseCapability.WEBHOOK, WarehouseWebhookCapable.class);
return ((WarehouseWebhookCapable) adapter).parse(ctx, headers, rawBody);
}
/** 本仓默认的库存同步策略。 */
public InventorySyncStrategy inventorySyncStrategy() {

47
warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WarehouseSdk.java

@ -13,6 +13,8 @@ import common.ecommerce.warehouse.capability.WarehouseFeeCapable; @@ -13,6 +13,8 @@ import common.ecommerce.warehouse.capability.WarehouseFeeCapable;
import common.ecommerce.warehouse.capability.WarehouseProductCapable;
import common.ecommerce.warehouse.capability.WarehouseReturnCapable;
import common.ecommerce.warehouse.capability.WarehouseWebhookCapable;
import common.ecommerce.warehouse.model.WarehouseCallback;
import common.ecommerce.shared.spi.ChannelSecret;
import common.ecommerce.warehouse.capability.DestructionCapable;
import common.ecommerce.warehouse.error.WarehouseUnsupportedCapabilityException;
import common.ecommerce.warehouse.model.BillingDocument;
@ -118,6 +120,51 @@ public final class WarehouseSdk { @@ -118,6 +120,51 @@ public final class WarehouseSdk {
return new EnumSetView(adapter, account.warehouseCode());
}
/**
* 解析仓方推送的回调。<b>宿主 HTTP 入口调用,SDK 不监听端口。</b>
*
* <p>回调进来时只知道 provider(由 OMS 的路由决定,如 {@code /user/callback/yqn}),
* 不知道 warehouseCode——报文里才有仓单号。所以本入口只按 provider 分派,
* 不走 {@link #warehouses(String, WarehouseConnection)}(那个需要先有仓编码)。</p>
*
* @param provider 接入通道,来自 OMS 的路由
* @param secret 验签凭据(通常 {@code appSecret});由宿主按 provider 提供,SDK 不缓存
* @param headers 原始请求头(键名大小写不敏感)
* @param rawBody 原始请求体,一字不改
* @param nowMillis 当前时间(毫秒),用于时间戳窗口校验;SDK 不读系统时钟
* @return 解析出的事件,可能为空(如仓方的探测请求)
* @throws common.ecommerce.warehouse.error.WarehouseWebhookVerificationException 验签失败,应返回 4xx 且不重试
*/
public List<WarehouseCallback> webhook(WarehouseProvider provider, ChannelSecret secret,
Map<String, String> headers, String rawBody,
long nowMillis) {
WarehouseAdapter adapter = resolve(provider);
if (!(adapter instanceof WarehouseWebhookCapable)
|| !adapter.supports(null, WarehouseCapability.WEBHOOK)) {
throw new WarehouseUnsupportedCapabilityException(WarehouseCapability.WEBHOOK);
}
WarehouseWebhookCapable capable = (WarehouseWebhookCapable) adapter;
capable.verify(secret, headers, rawBody, nowMillis);
WarehouseContext ctx = newContextForWebhook(provider, secret, rawBody);
return capable.parse(ctx, secret, headers, rawBody);
}
/** 回调没有仓编码与端点,只带 provider 与链路 id。 */
private WarehouseContext newContextForWebhook(WarehouseProvider provider,
ChannelSecret secret, String rawBody) {
String id = requestIdSupplier.get();
if (id == null || id.trim().isEmpty()) {
throw new IllegalStateException("requestIdSupplier returned blank id");
}
// 端点与凭据来自调用方;回调侧没有真实端点,用占位符避免 NPE
WarehouseConnection connection = WarehouseConnection.of(
secret != null && secret.endpointBaseUrl() != null && !secret.endpointBaseUrl().isEmpty()
? secret.endpointBaseUrl() : "https://callback.local", secret);
return WarehouseContext.of(
// 回调可能多仓共用入口,warehouseCode 未知;用 provider 名占位,业务字段以报文为准
"CALLBACK-" + provider.name(), provider, null, connection, id, clock);
}
/** 能力查询结果。 */
public static final class EnumSetView {

122
warehouse-sdk-core/src/main/java/common/ecommerce/warehouse/sdk/WebhookSignatures.java

@ -0,0 +1,122 @@ @@ -0,0 +1,122 @@
package common.ecommerce.warehouse.sdk;
import common.ecommerce.shared.spi.ChannelSecret;
import common.ecommerce.warehouse.enums.WarehouseProvider;
import common.ecommerce.warehouse.error.WarehouseWebhookVerificationException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* 回调签名校验。
*
* <p>各仓的回调验签算法不同,所以这里只放通用的 HMAC 能力,具体「拼什么串、
* 用哪个头、时间窗多长」由适配器决定。SDK 不缓存 secret,每次由调用方传入。</p>
*
* <p>验签失败统一抛 {@link WarehouseWebhookVerificationException}——宿主 HTTP 入口
* 应当返回 4xx 且不重试,这类错误重试也不会成功。</p>
*/
public final class WebhookSignatures {
private static final String HMAC_SHA256 = "HmacSHA256";
private WebhookSignatures() {
}
/**
* 计算 {@code HmacSHA256(secret, data)} 的 Base64。
*
* @param secret 密钥,取 {@link ChannelSecret#appSecret()}
* @param data 待签名原文,各仓自己拼
*/
public static String hmacSha256Base64(String secret, String data) {
if (secret == null || secret.trim().isEmpty()) {
throw new IllegalStateException("webhook verification requires a secret");
}
try {
Mac mac = Mac.getInstance(HMAC_SHA256);
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), HMAC_SHA256));
byte[] raw = mac.doFinal((data == null ? "" : data).getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(raw);
} catch (Exception e) {
throw new IllegalStateException("HmacSHA256 unavailable", e);
}
}
/**
* 恒定时间比较签名。
*
* <p>不用 {@code String.equals}:签名逐字节比较,提前返回会把「匹配了几位」
* 泄漏成时间差,攻击者可据此逐位试探。</p>
*
* @return 相等返回 true;任一为 null 或长度不同返回 false
*/
public static boolean constantTimeEquals(String expected, String actual) {
if (expected == null || actual == null) {
return false;
}
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
if (a.length != b.length) {
return false;
}
int diff = 0;
for (int i = 0; i < a.length; i++) {
diff |= a[i] ^ b[i];
}
return diff == 0;
}
/** 取头;键名大小写不敏感,缺失返回 null。 */
public static String header(Map<String, String> headers, String name) {
if (headers == null || name == null) {
return null;
}
for (Map.Entry<String, String> e : headers.entrySet()) {
if (e.getKey() != null && e.getKey().equalsIgnoreCase(name)) {
return e.getValue();
}
}
return null;
}
/**
* 时间戳窗口校验。
*
* @param timestampMillis 报文里的时间戳(毫秒)
* @param nowMillis 当前时间(毫秒),由调用方传入,SDK 不读系统时钟
* @param toleranceMillis 允许的偏差
* @throws WarehouseWebhookVerificationException 超出窗口
*/
public static void requireFreshTimestamp(long timestampMillis, long nowMillis, long toleranceMillis) {
long skew = Math.abs(nowMillis - timestampMillis);
if (skew > toleranceMillis) {
throw new WarehouseWebhookVerificationException(
common.ecommerce.warehouse.error.WarehouseException.builder()
.message("webhook timestamp outside tolerance: skew=" + skew
+ "ms, tolerance=" + toleranceMillis + "ms")
.operation("warehouse.webhook.verify")
.retryable(false));
}
}
/**
* 验签失败的统一异常。
*
* @param provider 接入通道,便于日志定位
* @param reason 失败原因(不要放原始 secret / 签名)
*/
public static WarehouseWebhookVerificationException verificationFailure(
WarehouseProvider provider, String reason) {
return new WarehouseWebhookVerificationException(
common.ecommerce.warehouse.error.WarehouseException.builder()
.message("webhook verification failed: " + reason)
.operation("warehouse.webhook.verify")
.provider(provider == null ? null : provider.name())
.retryable(false));
}
}

27
warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/adapter/YqnAdapter.java

@ -47,6 +47,7 @@ import common.ecommerce.warehouse.capability.LogisticsProductCapable; @@ -47,6 +47,7 @@ import common.ecommerce.warehouse.capability.LogisticsProductCapable;
import common.ecommerce.warehouse.capability.TransferCapable;
import common.ecommerce.warehouse.capability.WarehouseReturnCapable;
import common.ecommerce.warehouse.capability.DestructionCapable;
import common.ecommerce.warehouse.capability.WarehouseWebhookCapable;
import common.ecommerce.warehouse.capability.TrackingCapable;
import common.ecommerce.warehouse.capability.WarehouseFeeCapable;
import common.ecommerce.warehouse.model.BoxLabelCommand;
@ -54,6 +55,7 @@ import common.ecommerce.warehouse.model.DestructionCommand; @@ -54,6 +55,7 @@ import common.ecommerce.warehouse.model.DestructionCommand;
import common.ecommerce.warehouse.model.DestructionOrder;
import common.ecommerce.warehouse.model.LabelPrintTask;
import common.ecommerce.warehouse.model.LogisticsProduct;
import common.ecommerce.warehouse.model.WarehouseCallback;
import common.ecommerce.warehouse.model.WarehouseInfo;
import common.ecommerce.warehouse.model.SkuLabelCommand;
import common.ecommerce.warehouse.model.TrackEvent;
@ -101,7 +103,7 @@ import java.util.Map; @@ -101,7 +103,7 @@ import java.util.Map;
public final class YqnAdapter implements OutboundCapable, WarehouseProductCapable,
WarehouseFeeCapable, WarehouseFeeEstimateCapable, InventoryCapable, InboundCapable,
TransferCapable, WarehouseReturnCapable, TrackingCapable, DestructionCapable,
LogisticsProductCapable, WarehouseDirectoryCapable {
LogisticsProductCapable, WarehouseDirectoryCapable, WarehouseWebhookCapable {
/** 运去哪请求里的时间格式;待核对。 */
private static final DateTimeFormatter REQUEST_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@ -142,6 +144,7 @@ public final class YqnAdapter implements OutboundCapable, WarehouseProductCapabl @@ -142,6 +144,7 @@ public final class YqnAdapter implements OutboundCapable, WarehouseProductCapabl
WarehouseCapability.PLATFORM_LABEL_DELIVERY,
WarehouseCapability.LOGISTICS_PRODUCT,
WarehouseCapability.WAREHOUSE_DIRECTORY,
WarehouseCapability.WEBHOOK,
WarehouseCapability.TRANSFER,
WarehouseCapability.RETURN,
WarehouseCapability.RETURN_DISPOSITION,
@ -529,6 +532,28 @@ public final class YqnAdapter implements OutboundCapable, WarehouseProductCapabl @@ -529,6 +532,28 @@ public final class YqnAdapter implements OutboundCapable, WarehouseProductCapabl
throw new WarehouseUnsupportedCapabilityException(WarehouseCapability.RETURN);
}
// ------------------------------------------------------------------ 回调
/**
* 回调验签(API 149)。
*
* <p>算法:{@code Base64(HmacSHA256(appSecret, appKey + "|" + timestamp + "|" + rawBody))},
* 签名放在 {@code X-Signature} 头。时间戳单位文档未写,按位数兼容秒 / 毫秒。</p>
*/
@Override
public void verify(common.ecommerce.shared.spi.ChannelSecret secret,
Map<String, String> headers, String rawBody, long nowMillis) {
common.ecommerce.yqn.webhook.YqnLabelCallbackParser.verify(
secret, headers, rawBody, nowMillis);
}
@Override
public List<WarehouseCallback> parse(WarehouseContext ctx,
common.ecommerce.shared.spi.ChannelSecret secret,
Map<String, String> headers, String rawBody) {
return common.ecommerce.yqn.webhook.YqnLabelCallbackParser.parse(rawBody);
}
// ------------------------------------------------------------------ 仓库目录
/**

33
warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/dto/YqnLabelCallbackDtos.java

@ -0,0 +1,33 @@ @@ -0,0 +1,33 @@
package common.ecommerce.yqn.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
/**
* 运去哪报文结构:购买面单成功回调(API 149,仓方推送到商户配置的地址)。
*
* <p>一个文件对应一个接口,只放该接口的请求 / 响应与内嵌子结构;
* 与其它接口共用的结构各自复制一份,避免跨接口耦合。</p>
*/
public final class YqnLabelCallbackDtos {
private YqnLabelCallbackDtos() {
}
/** 面单购买成功回调体。 */
@JsonInclude(JsonInclude.Include.NON_NULL)
public static final class LabelPurchasedCallback {
/** 单据号(运去哪单号)。 */
public String orderNo;
/** 来源单号(我们下发时的单号)。 */
public String sourceNo;
/** 配货单号。 */
public String deliverOrderNo;
/** 面单追踪号。 */
public String trackingNo;
/** 承运商。 */
public String carrier;
/** 发货方式码。 */
public String shippingMethodCode;
}
}

131
warehouse-sdk-yqn/src/main/java/common/ecommerce/yqn/webhook/YqnLabelCallbackParser.java

@ -0,0 +1,131 @@ @@ -0,0 +1,131 @@
package common.ecommerce.yqn.webhook;
import common.ecommerce.http.JacksonJsonCodec;
import common.ecommerce.shared.spi.ChannelSecret;
import common.ecommerce.warehouse.enums.WarehouseProvider;
import common.ecommerce.warehouse.model.WarehouseCallback;
import common.ecommerce.warehouse.sdk.WebhookSignatures;
import common.ecommerce.yqn.dto.YqnLabelCallbackDtos;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* 运去哪「购买面单成功」回调(API 149)。
*
* <p>验签算法(文档给出):</p>
* <pre>
* data = appKey + "|" + timestamp + "|" + rawBody
* signature = Base64(HmacSHA256(secretKey, data))
* </pre>
* <p>请求头:{@code X-AppKey} / {@code X-Timestamp} / {@code X-Signature}。</p>
*
* <p><b>注意</b>:时间戳的单位文档没写(秒还是毫秒),这里按「位数判断」兼容两种;
* 联调确认后应收紧。</p>
*/
public final class YqnLabelCallbackParser {
/** 时间戳窗口:5 分钟。回调重推一般在秒级,窗口过大会放大重放风险。 */
public static final long TIMESTAMP_TOLERANCE_MILLIS = 5 * 60 * 1000L;
/** 事件类型:面单购买成功。 */
static final String EVENT_LABEL_PURCHASED = "LABEL_PURCHASED";
private static final String HEADER_APP_KEY = "X-AppKey";
private static final String HEADER_TIMESTAMP = "X-Timestamp";
private static final String HEADER_SIGNATURE = "X-Signature";
private YqnLabelCallbackParser() {
}
/**
* 验签。
*
* @param secret {@code appKey} 与 {@code appSecret} 都要有
* @param headers 原始请求头
* @param rawBody 原始请求体(验签用它,不能用反序列化后的对象)
* @param nowMillis 当前时间(毫秒)
* @throws common.ecommerce.warehouse.error.WarehouseWebhookVerificationException 头缺失 / 签名不符 / 时间戳过期
*/
public static void verify(ChannelSecret secret, Map<String, String> headers,
String rawBody, long nowMillis) {
if (secret == null) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "secret is required for callback verification");
}
String signature = WebhookSignatures.header(headers, HEADER_SIGNATURE);
String timestamp = WebhookSignatures.header(headers, HEADER_TIMESTAMP);
if (signature == null || signature.trim().isEmpty()) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "missing " + HEADER_SIGNATURE);
}
if (timestamp == null || timestamp.trim().isEmpty()) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "missing " + HEADER_TIMESTAMP);
}
String appKey = WebhookSignatures.header(headers, HEADER_APP_KEY);
if (appKey == null || appKey.trim().isEmpty()) {
// 文档标 X-AppKey 非必填,但签名原文里有它,缺了算不出正确的签名
appKey = secret.appKey();
}
if (appKey == null || appKey.trim().isEmpty()) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "missing " + HEADER_APP_KEY + " and no appKey in secret");
}
String data = appKey + "|" + timestamp + "|" + (rawBody == null ? "" : rawBody);
String expected = WebhookSignatures.hmacSha256Base64(secret.appSecret(), data);
if (!WebhookSignatures.constantTimeEquals(expected, signature)) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "signature mismatch");
}
WebhookSignatures.requireFreshTimestamp(
toMillis(timestamp), nowMillis, TIMESTAMP_TOLERANCE_MILLIS);
}
/** 解析报文。 */
public static List<WarehouseCallback> parse(String rawBody) {
YqnLabelCallbackDtos.LabelPurchasedCallback body =
new JacksonJsonCodec().fromJson(rawBody, YqnLabelCallbackDtos.LabelPurchasedCallback.class);
WarehouseCallback callback = WarehouseCallback.builder()
.sourceProvider(WarehouseProvider.YQN)
// 报文没有事件 id 与时间:用仓单号 + 来源单号做去重依据
.eventId(null)
.eventType(EVENT_LABEL_PURCHASED)
.providerOrderNo(body.orderNo)
.requestNo(body.sourceNo)
.rawBody(rawBody)
.outbound(WarehouseCallback.OutboundPayload.builder()
.trackingNumber(body.trackingNo)
.carrier(body.carrier)
.shippingMethodCode(body.shippingMethodCode)
.deliverOrderNo(body.deliverOrderNo)
.build())
.build();
List<WarehouseCallback> out = new ArrayList<WarehouseCallback>(1);
out.add(callback);
return out;
}
/**
* 时间戳转毫秒:10 位按秒、13 位按毫秒处理。
*
* <p>文档只写「时间戳」,没写单位;两种都见过,先兼容,联调确认后收紧。</p>
*/
static long toMillis(String timestamp) {
String v = timestamp == null ? "" : timestamp.trim();
if (v.isEmpty()) {
throw WebhookSignatures.verificationFailure(WarehouseProvider.YQN, "empty timestamp");
}
long raw;
try {
raw = Long.parseLong(v);
} catch (NumberFormatException e) {
throw WebhookSignatures.verificationFailure(
WarehouseProvider.YQN, "timestamp is not numeric: " + v);
}
// 10 位 = 秒级(到 2286 年),13 位 = 毫秒级
return v.length() <= 10 ? raw * 1000L : raw;
}
}

161
warehouse-sdk-yqn/src/test/java/common/ecommerce/yqn/webhook/YqnLabelCallbackParserTest.java

@ -0,0 +1,161 @@ @@ -0,0 +1,161 @@
package common.ecommerce.yqn.webhook;
import common.ecommerce.shared.spi.ChannelSecret;
import common.ecommerce.warehouse.enums.WarehouseProvider;
import common.ecommerce.warehouse.error.WarehouseWebhookVerificationException;
import common.ecommerce.warehouse.model.WarehouseCallback;
import common.ecommerce.warehouse.sdk.WebhookSignatures;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* 购买面单成功回调(API 149)验签与解析。
*
* <p>签名算法按文档给出的实现独立复算一遍,确保与官方 SDK 行为一致。</p>
*/
class YqnLabelCallbackParserTest {
private static final String APP_KEY = "app-key-1";
private static final String SECRET = "secret-1";
/** 固定一个秒级时间戳,避免依赖系统时钟。 */
private static final String TIMESTAMP = "1762764000";
private static final long NOW_MILLIS = 1762764000L * 1000L + 10_000L;
private static final String BODY = "{\"orderNo\":\"IP123\",\"sourceNo\":\"OB-123\","
+ "\"deliverOrderNo\":\"D-1\",\"trackingNo\":\"TRK9988\","
+ "\"carrier\":\"FEDEX\",\"shippingMethodCode\":\"FedEx_FEDEX_GROUND\"}";
private static ChannelSecret secret() {
return ChannelSecret.builder().appKey(APP_KEY).appSecret(SECRET).build();
}
/** 按文档给出的算法独立实现一遍,作为对照。 */
private static String sign(String appKey, String secretKey, String timestamp, String body) {
return WebhookSignatures.hmacSha256Base64(secretKey,
appKey + "|" + timestamp + "|" + body);
}
private static Map<String, String> headers(String signature, String timestamp, String appKey) {
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("X-AppKey", appKey);
h.put("X-Timestamp", timestamp);
h.put("X-Signature", signature);
return h;
}
@Test
void acceptsValidSignature() {
String sig = sign(APP_KEY, SECRET, TIMESTAMP, BODY);
YqnLabelCallbackParser.verify(secret(), headers(sig, TIMESTAMP, APP_KEY), BODY, NOW_MILLIS);
}
@Test
void rejectsTamperedBody() {
String sig = sign(APP_KEY, SECRET, TIMESTAMP, BODY);
String tampered = BODY.replace("TRK9988", "TRK0000");
assertThrows(WarehouseWebhookVerificationException.class,
() -> YqnLabelCallbackParser.verify(secret(),
headers(sig, TIMESTAMP, APP_KEY), tampered, NOW_MILLIS));
}
@Test
void rejectsWrongSecret() {
String sig = sign(APP_KEY, "another-secret", TIMESTAMP, BODY);
assertThrows(WarehouseWebhookVerificationException.class,
() -> YqnLabelCallbackParser.verify(secret(),
headers(sig, TIMESTAMP, APP_KEY), BODY, NOW_MILLIS));
}
@Test
void rejectsMissingSignatureHeader() {
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("X-Timestamp", TIMESTAMP);
assertThrows(WarehouseWebhookVerificationException.class,
() -> YqnLabelCallbackParser.verify(secret(), h, BODY, NOW_MILLIS));
}
@Test
void rejectsStaleTimestamp() {
String sig = sign(APP_KEY, SECRET, TIMESTAMP, BODY);
// 超过 5 分钟窗口
long tooLate = NOW_MILLIS + YqnLabelCallbackParser.TIMESTAMP_TOLERANCE_MILLIS + 1000L;
assertThrows(WarehouseWebhookVerificationException.class,
() -> YqnLabelCallbackParser.verify(secret(),
headers(sig, TIMESTAMP, APP_KEY), BODY, tooLate));
}
/** 头名大小写不敏感:不同网关会改写大小写。 */
@Test
void headerNamesAreCaseInsensitive() {
String sig = sign(APP_KEY, SECRET, TIMESTAMP, BODY);
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("x-appkey", APP_KEY);
h.put("x-timestamp", TIMESTAMP);
h.put("x-signature", sig);
YqnLabelCallbackParser.verify(secret(), h, BODY, NOW_MILLIS);
}
/** X-AppKey 缺失时回退到 secret 里的 appKey。 */
@Test
void fallsBackToSecretAppKey() {
String sig = sign(APP_KEY, SECRET, TIMESTAMP, BODY);
Map<String, String> h = new LinkedHashMap<String, String>();
h.put("X-Timestamp", TIMESTAMP);
h.put("X-Signature", sig);
YqnLabelCallbackParser.verify(secret(), h, BODY, NOW_MILLIS);
}
@Test
void parsesOutboundPayload() {
List<WarehouseCallback> list = YqnLabelCallbackParser.parse(BODY);
assertEquals(1, list.size());
WarehouseCallback cb = list.get(0);
assertEquals(WarehouseProvider.YQN, cb.sourceProvider());
assertEquals("LABEL_PURCHASED", cb.eventType());
assertEquals("IP123", cb.providerOrderNo());
assertEquals("OB-123", cb.requestNo());
assertNull(cb.eventId());
assertEquals(BODY, cb.rawBody());
assertEquals("TRK9988", cb.outbound().trackingNumber());
assertEquals("FEDEX", cb.outbound().carrier());
assertEquals("FedEx_FEDEX_GROUND", cb.outbound().shippingMethodCode());
assertEquals("D-1", cb.outbound().deliverOrderNo());
assertNull(cb.returns());
assertNull(cb.inbound());
}
/** 报文没有事件 id,去重靠指纹。 */
@Test
void fingerprintIsStableForSameEvent() {
String first = YqnLabelCallbackParser.parse(BODY).get(0).fingerprint();
String second = YqnLabelCallbackParser.parse(BODY).get(0).fingerprint();
assertEquals(first, second);
assertTrue(first.contains("LABEL_PURCHASED"));
assertTrue(first.contains("IP123"));
}
@Test
void timestampAcceptsSecondsAndMillis() {
assertEquals(1762764000000L, YqnLabelCallbackParser.toMillis("1762764000"));
assertEquals(1762764000123L, YqnLabelCallbackParser.toMillis("1762764000123"));
assertThrows(WarehouseWebhookVerificationException.class,
() -> YqnLabelCallbackParser.toMillis("not-a-number"));
}
}
Loading…
Cancel
Save