CropPath 开发者

全部指南

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。请在解析或信任每个请求之前先验证它:

  1. 取请求体的原始字节,在任何 JSON 解析之前。
  2. 当 webhook-timestamp 与您的时钟相差超过 300 秒(无论早晚)时,拒绝该请求。
  3. 拼出被签名的内容 <webhook-id>.<webhook-timestamp>.<原始请求体>:事件 ID、一个点、原样的时间戳、一个点,然后是请求体字节。
  4. HMAC 密钥:去掉签名密钥的 whsec_ 前缀,再对其余部分做 base64 解码。
  5. 用该密钥计算被签名内容的 HMAC-SHA256,并做 base64 编码。
  6. 使用恒定时间比较,将其与 webhook-signature 中的每个 v1,… 条目(以空格分隔)比较;只要有一个匹配即可。
  7. 按 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 valid

Node.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;
}

常见错误

重试与重复

每个事件至少投递一次:请按 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 中给出最近一次尝试失败的原因:

API 参考中的相关内容

下载

这些文件由本门户提供,无需访问源代码仓库。