Verify Sendcloud webhooks

Sendcloud puts a signature in the Sendcloud-Signature header of every webhook request, so you can tell it came from Sendcloud and wasn't changed on the way. It's a lowercase hex HMAC-SHA256 of the raw request body, keyed with your Secret Key or Webhook Signature Key. No timestamp is signed, so it doesn't stop a replay, and Sendcloud's docs show the check in PHP and Python rather than pointing to an SDK.

These pages cover webhooks set on an integration. Sendcloud's beta Event Subscriptions API is a separate route: it sends parcels.event.created and parcel.created, names them in event_type, offers bearer, Basic or API key auth rather than this signature, and retries up to 5 times.

The facts

Signature header
Sendcloud-Signature

Format: <lowercase hex>

Scheme
HMAC-SHA256
Signed material
{raw body}

The entire request body, exactly as received and before any parsing. Nothing else is signed.

What to build
Recompute a digest over the raw body and compare
Key
shared secret

Sendcloud webhook secret

The integration's Secret Key (API integrations) or Webhook Signature Key, depending on the integration type. Keep it in an environment variable, not in source code.

  • Sendcloud signs with the Secret Key or the Webhook Signature Key, depending on your integration type. The webhook docs don't list which types use which key.
  • A Sendcloud API integration's Secret Key is generated with its Public Key when you create the integration.
  • Webhooks are configured per integration, so keep track of which key belongs to which integration.
  • To test your check, the docs give a known result: the body {"key": "value"} with the secret secretkey gives 1eed4b3d41f4653ac64fd56f1bf1cbfd349e4482cbc11dff7134bd93e5da4b0a.
  • The webhook docs don't cover rotating the key.

Source: Sendcloud docs ↗

Code

express/src/index.js
javascript
// Generated with: sendcloud-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config({ quiet: true });
const crypto = require('crypto');
const express = require('express');

const app = express();

// Sendcloud signs the entire raw body: HMAC-SHA256, bare hex, Sendcloud-Signature header
function verifySendcloudSignature(rawBody, signature, secret) {
  if (!signature || !secret) return false;
  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

// express.raw with '*/*' so the body is a Buffer whatever the content type is
app.post('/webhooks/sendcloud', express.raw({ type: '*/*' }), (req, res) => {
  const secret = process.env.SENDCLOUD_WEBHOOK_SECRET;
  if (!secret) {
    console.error('SENDCLOUD_WEBHOOK_SECRET is not set');
    return res.status(500).send('Webhook secret not configured');
  }

  const signature = req.get('Sendcloud-Signature');
  if (!signature) {
    return res.status(400).send('Missing Sendcloud-Signature header');
  }

  const rawBody = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
  if (!verifySendcloudSignature(rawBody, signature, secret)) {
    return res.status(400).send('Invalid signature');
  }

  let event;
  try {
    event = JSON.parse(rawBody.toString('utf8'));
  } catch {
    return res.status(400).send('Invalid JSON');
  }

  switch (event.action) {
    case 'parcel_status_changed':
      // Webhooks can arrive out of order: compare event.timestamp before overwriting state
      console.log(`Parcel ${event.parcel?.id} -> ${event.parcel?.status?.message}`);
      break;
    case 'return_created':
      console.log(`Return ${event.data?.id} created for order ${event.data?.order_number}`);
      break;
    case 'integration_connected':
    case 'integration_updated':
    case 'integration_deleted':
      console.log(`${event.action}: integration ${event.integration?.id}`);
      break;
    default:
      console.log(`Unhandled action: ${event.action}`);
  }

  res.status(200).json({ received: true });
});

if (require.main === module) {
  const port = process.env.PORT || 3000;
  app.listen(port, () => console.log(`Server listening on http://localhost:${port}`));
}

module.exports = { app, verifySendcloudSignature };
nextjs/app/webhooks/sendcloud/route.ts
typescript
// Generated with: sendcloud-webhooks skill
// https://github.com/hookdeck/webhook-skills

import { NextRequest, NextResponse } from 'next/server';
import crypto from 'crypto';

// Sendcloud signs the entire raw body: HMAC-SHA256, bare hex, Sendcloud-Signature header
function verifySendcloudSignature(rawBody: Buffer, signature: string, secret: string): boolean {
  const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(signature);
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

export async function POST(request: NextRequest) {
  const secret = process.env.SENDCLOUD_WEBHOOK_SECRET;
  if (!secret) {
    console.error('SENDCLOUD_WEBHOOK_SECRET is not set');
    return NextResponse.json({ error: 'Webhook secret not configured' }, { status: 500 });
  }

  const signature = request.headers.get('sendcloud-signature');
  if (!signature) {
    return NextResponse.json({ error: 'Missing Sendcloud-Signature header' }, { status: 400 });
  }

  // Read the raw bytes: never parse before verifying, whatever the content type
  const rawBody = Buffer.from(await request.arrayBuffer());
  if (!verifySendcloudSignature(rawBody, signature, secret)) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let event: any;
  try {
    event = JSON.parse(rawBody.toString('utf8'));
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  switch (event.action) {
    case 'parcel_status_changed':
      // Webhooks can arrive out of order: compare event.timestamp before overwriting state
      console.log(`Parcel ${event.parcel?.id} -> ${event.parcel?.status?.message}`);
      break;
    case 'return_created':
      console.log(`Return ${event.data?.id} created for order ${event.data?.order_number}`);
      break;
    case 'integration_connected':
    case 'integration_updated':
    case 'integration_deleted':
      console.log(`${event.action}: integration ${event.integration?.id}`);
      break;
    default:
      console.log(`Unhandled action: ${event.action}`);
  }

  return NextResponse.json({ received: true });
}
fastapi/main.py
python
# Generated with: sendcloud-webhooks skill
# https://github.com/hookdeck/webhook-skills

import hashlib
import hmac
import json
import os

from dotenv import load_dotenv
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse

load_dotenv()

app = FastAPI()


def verify_sendcloud_signature(raw_body: bytes, signature: str, secret: str) -> bool:
    """Sendcloud signs the entire raw body: HMAC-SHA256, bare hex, Sendcloud-Signature header."""
    if not signature or not secret:
        return False
    expected = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), signature.encode())


@app.post("/webhooks/sendcloud")
async def sendcloud_webhook(request: Request):
    secret = os.getenv("SENDCLOUD_WEBHOOK_SECRET")
    if not secret:
        return JSONResponse({"error": "Webhook secret not configured"}, status_code=500)

    signature = request.headers.get("sendcloud-signature")
    if not signature:
        return JSONResponse({"error": "Missing Sendcloud-Signature header"}, status_code=400)

    # Raw bytes, whatever the content type: never parse before verifying
    raw_body = await request.body()
    if not verify_sendcloud_signature(raw_body, signature, secret):
        return JSONResponse({"error": "Invalid signature"}, status_code=400)

    try:
        event = json.loads(raw_body)
    except ValueError:
        return JSONResponse({"error": "Invalid JSON"}, status_code=400)
    if not isinstance(event, dict):
        return JSONResponse({"error": "Invalid payload"}, status_code=400)

    action = event.get("action")
    if action == "parcel_status_changed":
        # Webhooks can arrive out of order: compare event["timestamp"] before overwriting state
        parcel = event.get("parcel") or {}
        print(f"Parcel {parcel.get('id')} -> {(parcel.get('status') or {}).get('message')}")
    elif action == "return_created":
        data = event.get("data") or {}
        print(f"Return {data.get('id')} created for order {data.get('order_number')}")
    elif action in ("integration_connected", "integration_updated", "integration_deleted"):
        print(f"{action}: integration {(event.get('integration') or {}).get('id')}")
    else:
        print(f"Unhandled action: {action}")

    return {"received": True}

From hookdeck/webhook-skills ↗

Or install the Sendcloud webhooks skill:

npx skills add hookdeck/webhook-skills --skill sendcloud-webhooks

Common failures

The body was parsed first

Sendcloud signs the bytes exactly as sent. Hashing re-encoded JSON, or PHP's $_POST, gives a different digest, so read the raw body before any parser runs.

The wrong key

Sendcloud signs with the Secret Key or the Webhook Signature Key, depending on your integration type, and each integration has its own webhook configuration. If you answer a failed check with a 401, Sendcloud doesn't retry, so a wrong key loses updates until you fix it.

The wrong encoding

The header is a bare hex digest with no prefix. A base64 digest or a sha256= prefix won't match. Test your code with the example on this page.

From Hookdeck's Sendcloud guide

Let Event Gateway verify Sendcloud signatures.

Event Gateway verifies the signature on each Sendcloud delivery before it reaches your service, then queues it and retries failures on your schedule.

Not affiliated with Sendcloud. Facts are compiled from public sources and linked inline.