Browse Source
回调是仓方主动推送,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
10 changed files with 964 additions and 64 deletions
@ -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); |
||||
} |
||||
} |
||||
} |
||||
@ -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)); |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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; |
||||
} |
||||
} |
||||
@ -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…
Reference in new issue