Webhook
可用
当批次被封签、召回或撤出市场,批次显示的可信等级发生变化,记录化验结果,货运出发,或消费者就您的某个果实提交报告时,在您的 HTTPS 端点接收签名事件。
本页列出要点。完整的合作伙伴指南 webhooks.md(链接见本页末尾)包含每种事件的请求体、Python、Node.js、Java、C#、Go 和 PHP 的完整接收端示例、各 SDK 的签名验证器、用于检验代码的固定测试投递以及完整的故障排查表。
配置
租户管理员在管理控制台(设置 → API 令牌 → Webhook 部分)或通过 POST /v1/webhooks 注册您的端点,并选择事件类型。您的系统也可以通过 API 自行管理端点,使用角色为 tenant_admin 的 API 令牌,或带有 webhook_admin 范围的 OAuth2 令牌。每个租户最多 20 个订阅,已停用的也计算在内。
端点必须使用 https://,并具有由公共证书颁发机构为其主机名签发的有效证书;其主机名解析到的每个地址都必须是公网地址(每次投递前都会重新检查)。CropPath 不跟随重定向:3xx 响应计为失败。请在 10 秒内返回 2xx。
签名密钥(whsec_…)只在创建订阅或更换密钥时显示一次。请立即存入密钥管理系统,切勿放在源代码、日志或电子邮件中。
验证每个请求
任何人都可以向您的地址发送 POST。请在解析或信任每个请求之前先验证它:
- 取请求体的原始字节,在任何 JSON 解析之前。
- 当
webhook-timestamp与您的时钟相差超过 300 秒(无论早晚)时,拒绝该请求。 - 拼出被签名的内容
<webhook-id>.<webhook-timestamp>.<原始请求体>:事件 ID、一个点、原样的时间戳、一个点,然后是请求体字节。 - HMAC 密钥:去掉签名密钥的
whsec_前缀,再对其余部分做 base64 解码。 - 用该密钥计算被签名内容的 HMAC-SHA256,并做 base64 编码。
- 使用恒定时间比较,将其与
webhook-signature中的每个v1,…条目(以空格分隔)比较;只要有一个匹配即可。 - 按
webhook-id去重,然后再处理事件。
以下每个示例只使用该语言的标准库,并已用固定测试投递 webhook-test-vector.json(由后端自身签名,链接见本页末尾)运行验证。Java、.NET 和 Go SDK 提供 WebhookVerifier;Python 和 TypeScript SDK 没有。
Python
import base64
import binascii
import hashlib
import hmac
import time
REPLAY_WINDOW_S = 300 # seconds allowed between webhook-timestamp and your clock
def verify_webhook(secret, msg_id, timestamp, signature_header, body, now=None):
"""True when the delivery is authentic and fresh. `body` is the raw request body (bytes), never parsed JSON."""
if not msg_id or not timestamp or not signature_header:
return False
if not (timestamp.isascii() and timestamp.isdigit()):
return False
now = time.time() if now is None else now
if abs(now - int(timestamp)) > REPLAY_WINDOW_S:
return False
if not secret.startswith("whsec_"):
raise ValueError("not a CropPath webhook secret (whsec_...)")
key = base64.b64decode(secret[len("whsec_"):], validate=True)
signed = f"{msg_id}.{timestamp}.".encode() + body
expected = hmac.new(key, signed, hashlib.sha256).digest()
valid = False
for entry in signature_header.split():
version, _, signature = entry.partition(",")
if version != "v1":
continue
try:
given = base64.b64decode(signature, validate=True)
except binascii.Error:
continue
if hmac.compare_digest(given, expected): # constant time; check every entry
valid = True
return validNode.js
import { createHmac, timingSafeEqual } from "node:crypto";
const REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock
/** True when the delivery is authentic and fresh. `body` is the raw request body (a Buffer), never parsed JSON. */
export function verifyWebhook(secret, id, timestamp, signatureHeader, body, now = Date.now() / 1000) {
if (!id || !timestamp || !signatureHeader) return false;
if (!/^[0-9]+$/.test(timestamp)) return false;
if (Math.abs(now - Number(timestamp)) > REPLAY_WINDOW_S) return false;
if (!secret.startsWith("whsec_")) throw new Error("not a CropPath webhook secret (whsec_...)");
const key = Buffer.from(secret.slice("whsec_".length), "base64");
const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
let valid = false;
for (const entry of signatureHeader.split(" ")) {
if (!entry.startsWith("v1,")) continue;
const given = Buffer.from(entry.slice(3), "base64");
// constant time; check every entry
if (given.length === expected.length && timingSafeEqual(given, expected)) valid = true;
}
return valid;
}Java
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public final class WebhookVerification {
static final long REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock
/** True when the delivery is authentic and fresh; {@code body} is the raw request body, never parsed JSON. */
public static boolean verify(String secret, String id, String timestamp, String signatureHeader, byte[] body,
long nowSeconds) throws GeneralSecurityException {
if (id == null || id.isEmpty() || timestamp == null || signatureHeader == null) return false;
if (!timestamp.matches("[0-9]{1,12}")) return false;
if (Math.abs(nowSeconds - Long.parseLong(timestamp)) > REPLAY_WINDOW_S) return false;
if (!secret.startsWith("whsec_")) throw new IllegalArgumentException("not a CropPath webhook secret");
byte[] key = Base64.getDecoder().decode(secret.substring("whsec_".length()));
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
mac.update((id + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));
byte[] expected = mac.doFinal(body);
boolean valid = false;
for (String entry : signatureHeader.trim().split(" +")) {
if (!entry.startsWith("v1,")) continue;
byte[] given;
try {
given = Base64.getDecoder().decode(entry.substring(3));
} catch (IllegalArgumentException e) {
continue;
}
if (MessageDigest.isEqual(expected, given)) valid = true; // constant time; check every entry
}
return valid;
}
}C#
using System.Security.Cryptography;
using System.Text;
public static class WebhookVerification
{
const long ReplayWindowSeconds = 300; // allowed between webhook-timestamp and your clock
/// <summary>True when the delivery is authentic and fresh; <paramref name="body"/> is the raw request body.</summary>
public static bool Verify(string secret, string? id, string? timestamp, string? signatureHeader, byte[] body,
long? nowSeconds = null)
{
if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(signatureHeader)) return false;
if (timestamp.Length > 12 || !timestamp.All(char.IsAsciiDigit)) return false;
long now = nowSeconds ?? DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (Math.Abs(now - long.Parse(timestamp)) > ReplayWindowSeconds) return false;
if (!secret.StartsWith("whsec_", StringComparison.Ordinal)) throw new ArgumentException("not a CropPath webhook secret");
byte[] key = Convert.FromBase64String(secret["whsec_".Length..]);
byte[] signed = [.. Encoding.UTF8.GetBytes(id + "." + timestamp + "."), .. body];
byte[] expected = HMACSHA256.HashData(key, signed);
bool valid = false;
foreach (string entry in signatureHeader.Split(' ', StringSplitOptions.RemoveEmptyEntries))
{
if (!entry.StartsWith("v1,", StringComparison.Ordinal)) continue;
byte[] given;
try { given = Convert.FromBase64String(entry[3..]); }
catch (FormatException) { continue; }
if (CryptographicOperations.FixedTimeEquals(expected, given)) valid = true; // constant time; check every entry
}
return valid;
}
}Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"regexp"
"strconv"
"strings"
"time"
)
const replayWindow = 300 // seconds allowed between webhook-timestamp and your clock
var unixSeconds = regexp.MustCompile(`^[0-9]{1,12}$`)
// verifyWebhook reports whether a delivery is authentic and fresh; body is the raw request body, never parsed JSON.
func verifyWebhook(secret, id, timestamp, signatureHeader string, body []byte, now time.Time) bool {
if id == "" || signatureHeader == "" || !unixSeconds.MatchString(timestamp) {
return false
}
ts, _ := strconv.ParseInt(timestamp, 10, 64)
if skew := now.Unix() - ts; skew > replayWindow || skew < -replayWindow {
return false
}
encoded, ok := strings.CutPrefix(secret, "whsec_")
key, err := base64.StdEncoding.DecodeString(encoded)
if !ok || err != nil {
return false // not a CropPath webhook secret
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(id + "." + timestamp + "."))
mac.Write(body)
expected := mac.Sum(nil)
valid := false
for _, entry := range strings.Fields(signatureHeader) {
signature, isV1 := strings.CutPrefix(entry, "v1,")
given, err := base64.StdEncoding.DecodeString(signature)
if isV1 && err == nil && hmac.Equal(expected, given) { // constant time; check every entry
valid = true
}
}
return valid
}PHP
<?php
const CROPPATH_REPLAY_WINDOW_S = 300; // seconds allowed between webhook-timestamp and your clock
/** True when the delivery is authentic and fresh; $body is the raw request body, never decoded JSON. */
function croppath_verify_webhook(string $secret, ?string $id, ?string $timestamp, ?string $signatureHeader,
string $body, ?int $now = null): bool
{
if ($id === null || $id === '' || $signatureHeader === null || $timestamp === null) return false;
if (!preg_match('/^[0-9]{1,12}$/D', $timestamp)) return false;
if (abs(($now ?? time()) - (int) $timestamp) > CROPPATH_REPLAY_WINDOW_S) return false;
if (!str_starts_with($secret, 'whsec_')) throw new InvalidArgumentException('not a CropPath webhook secret');
$key = base64_decode(substr($secret, strlen('whsec_')), true);
if ($key === false) throw new InvalidArgumentException('not a CropPath webhook secret');
$expected = base64_encode(hash_hmac('sha256', $id . '.' . $timestamp . '.' . $body, $key, true));
$valid = false;
foreach (preg_split('/ +/', trim($signatureHeader)) as $entry) {
if (str_starts_with($entry, 'v1,') && hash_equals($expected, substr($entry, 3))) {
$valid = true; // hash_equals is constant time; check every entry
}
}
return $valid;
}常见错误
- 在验证之前解析 JSON 再重新序列化:字节会改变,签名验证失败。
- 在路由之前运行了请求体解析器(
express.json()、模型参数):请改为读取原始请求体。 - 直接用密钥字符串作为 HMAC 密钥,或保留
whsec_前缀:请先做 base64 解码。 - 用
==比较签名:请使用恒定时间比较。 - 跳过时间戳检查,或服务器时钟不准:请用 NTP 同步时间。
- 与整个请求头比较:它可能包含多个签名。
重试与重复
每个事件至少投递一次:请按 webhook-id 去重,它在每次尝试和每次重新发送中都保持不变。不保证顺序。请尽快返回 2xx,之后再处理事件;负载只包含标识符、状态和时间,其余内容请通过 API 读取。
除 2xx 以外的任何响应,或 10 秒内没有响应,都会在 1、2、4……分钟后重试,间隔最长 6 小时,共 12 次(约 20.5 小时);您以 4xx 拒绝的请求同样会被重试。连续失败 50 次后订阅会被停用,在管理员重新启用之前不会为其记录任何事件。已送达和失败的投递可在 30 天内从发送记录中重新发送。
更换密钥
更换密钥(POST /v1/webhooks/<id>/rotate-secret,或管理控制台中的“更换密钥”)立即生效:此后每次尝试都只用新密钥签名。更换之前,请让端点接受一组密钥;更换后立即加入新密钥,几分钟后再删除旧密钥。期间失败的投递会被重试。
故障排查
发送记录(GET /v1/webhooks/<id>/deliveries,或管理控制台中的“发送记录”)在 last_error 中给出最近一次尝试失败的原因:
http_status:端点返回了 2xx 以外的状态(见last_status)。请检查密钥、原始请求体的读取方式和路径,并直接响应而不是重定向。tls_error:请为 URL 中的主机名安装由公共证书颁发机构签发的有效证书。timeout:请在 10 秒内响应,之后再处理事件。dns_failure、connect_failed:主机名必须能解析,端口必须能从互联网访问。blocked_address:主机名解析到了私有或其他非公网地址;请只发布公网地址。protocol_error:响应不是有效的 HTTP,或连接中途关闭。- 订阅被停用:修复端点,重新启用(管理控制台中的“重新启用”,或以
enabled: true调用PATCH),然后重新发送失败的投递。停用期间的变更不会为其生成事件:请通过 API 读取。
API 参考中的相关内容
POST /v1/webhooksGET /v1/webhooksPATCH /v1/webhooks/{id}POST /v1/webhooks/{id}/rotate-secretGET /v1/webhooks/{id}/deliveriesPOST /v1/webhooks/{id}/deliveries/{delivery}/redeliver- Webhook 事件
下载
这些文件由本门户提供,无需访问源代码仓库。