CropPath for developers

All guides

Webhooks

Available

Receive signed events at your HTTPS endpoint when a lot is sealed, recalled or withdrawn, its displayed trust tier changes, a lab result is recorded, a shipment departs, or a consumer files a report on one of your fruits.

This page has the essentials. The full partner guide, webhooks.md (linked at the end of this page), has the body of every event type, complete receivers in Python, Node.js, Java, C#, Go and PHP, the SDK verifiers, a fixed test delivery to check your code against and the complete troubleshooting table.

Set up

A tenant admin registers your endpoint in the admin console (Settings, API tokens, Webhooks section) or through POST /v1/webhooks, and chooses the event types. Your system can also manage its endpoint through the API, with an API token of the role tenant_admin or an OAuth2 token with the scope webhook_admin. A tenant has at most 20 subscriptions, disabled ones included.

The endpoint must use https:// with a valid certificate for its host name from a public certificate authority, and every address its host name resolves to must be public (checked again before every attempt). CropPath does not follow redirects: a 3xx answer counts as a failure. Answer 2xx within 10 seconds.

The signing secret (whsec_…) is shown once, when the subscription is created or its secret replaced. Put it in a secret manager at once; never in source code, logs or e-mail.

Verify every request

Anyone can send a POST to your address. Verify every request before you parse or trust it:

  1. Take the raw bytes of the request body, before any JSON parsing.
  2. Refuse the request when webhook-timestamp is more than 300 seconds away from your clock, earlier or later.
  3. Build the signed content <webhook-id>.<webhook-timestamp>.<raw body>: the id, a dot, the timestamp exactly as received, a dot, then the body bytes.
  4. The HMAC key: remove the whsec_ prefix from the secret and base64-decode the rest.
  5. Compute the HMAC-SHA256 of the signed content with that key and base64-encode it.
  6. Compare it with each v1,… entry of webhook-signature (entries are separated by spaces) using a constant-time comparison; one match is enough.
  7. Deduplicate on webhook-id, then process the event.

Each sample below uses only its language's standard library and was run against the fixed test delivery webhook-test-vector.json (signed by the backend itself, linked at the end of this page). The Java, .NET and Go SDKs have a WebhookVerifier; the Python and TypeScript SDKs have none.

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

Common mistakes

Retries and duplicates

Each event is delivered at least once: deduplicate on webhook-id, which stays the same on every attempt and every redelivery. Order is not guaranteed. Answer 2xx quickly and process the event afterwards; the payload carries identifiers, states and times only, so read the rest through the API.

Any answer other than 2xx, or none within 10 seconds, is retried after 1, 2, 4 … minutes, at most 6 hours apart, 12 attempts in all (about 20.5 hours); a request you refuse with a 4xx is retried too. After 50 failed attempts in a row the subscription is disabled, and no events are recorded for it until an admin enables it again. Delivered and failed deliveries can be sent again from the delivery log for 30 days.

Replacing the secret

Replacing the secret (POST /v1/webhooks/<id>/rotate-secret, or Replace secret in the admin console) takes effect at once: from then on every attempt is signed with the new secret only. Before you replace it, make your endpoint accept a list of secrets; add the new secret as soon as you replace it, and remove the old one a few minutes later. Attempts that fail in between are retried.

Troubleshooting

The delivery log (GET /v1/webhooks/<id>/deliveries, or Delivery log in the admin console) gives the reason for the last attempt in last_error:

In the API reference

Downloads

This portal serves these files: you do not need access to the source repository.