Verify Zuora webhooks

Zuora defines no signature for callouts, so there's no standard one to check. With Username/Password authentication and Enable Preemptive Authentication ticked, every callout carries Authorization: Basic with your credentials, and your endpoint compares them in constant time. That authenticates the sender, but it doesn't protect the body or stop a replay. For body integrity, a template can add an HMAC whose algorithm, signed data and header you define yourself.

The facts

Signature header
None (unsigned)
What to build
Compare the Basic username and password with your stored values
Key
shared secret

Zuora webhook secret

You choose the username and password and enter them on the callout template. Zuora generates no secret. Keep it in an environment variable, not in source code.

  • Enter them under Request Authentication on the callout template, with Authentication Type set to Username/Password.
  • Authentication is set per template, so each template can have its own credentials.
  • Tick Enable Preemptive Authentication so they're sent on the first request. Zuora doesn't send them first by default.
  • The optional HMAC's Secret Key, Algorithm, Data and Header Key are on the same template, and Zuora defines none of them for you.
  • The docs don't describe rotation. To change the credentials, update the template and your stored values together.

Source: Zuora docs ↗

Code

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

const app = express();

// The callout HTTP method is set on the template (POST by default).
const ALLOWED_METHODS = ['POST', 'PUT', 'PATCH', 'GET', 'DELETE'];

/**
 * Constant-time comparison of two Buffers. Hashing both sides first gives
 * equal-length buffers, so timingSafeEqual never throws and length isn't leaked.
 */
function safeEqual(a, b) {
  const ha = crypto.createHash('sha256').update(a).digest();
  const hb = crypto.createHash('sha256').update(b).digest();
  return crypto.timingSafeEqual(ha, hb);
}

/**
 * Parse "Authorization: Basic base64(username:password)".
 * Scheme is case-insensitive; the credentials split on the FIRST colon, so the
 * password may contain colons. Returns { username, password } as Buffers, or null.
 */
function parseBasicAuth(header) {
  if (typeof header !== 'string') return null;
  const parts = header.trim().split(/\s+/);
  if (parts.length !== 2 || parts[0].toLowerCase() !== 'basic') return null;
  if (!/^[A-Za-z0-9+/]+={0,2}$/.test(parts[1])) return null;

  const decoded = Buffer.from(parts[1], 'base64');
  const colon = decoded.indexOf(0x3a); // ':'
  if (colon === -1) return null;
  return { username: decoded.subarray(0, colon), password: decoded.subarray(colon + 1) };
}

/**
 * Zuora callouts are not signed. The template's Username/Password authentication
 * (with Enable Preemptive Authentication) sends HTTP Basic credentials on every request.
 * Both values are compared before deciding, so a wrong username and a wrong password
 * take the same time.
 */
function verifyZuoraRequest(
  headers,
  username = process.env.ZUORA_WEBHOOK_USERNAME,
  password = process.env.ZUORA_WEBHOOK_PASSWORD
) {
  if (!username || !password) return false; // never accept when unconfigured
  const creds = parseBasicAuth(headers.authorization);
  if (!creds) return false;

  const userOk = safeEqual(creds.username, Buffer.from(username, 'utf8'));
  const passOk = safeEqual(creds.password, Buffer.from(password, 'utf8'));
  return userOk && passOk;
}

/**
 * Zuora adds no event field: the body is whatever merge fields the callout template
 * defines. This handler assumes an illustrative JSON body such as
 * {"event": "PaymentProcessed", "accountId": "..."} that you write into the template.
 */
function handleCallout(payload) {
  const { event } = payload;

  switch (event) {
    case 'PaymentProcessed':
      console.log(`Payment processed for account ${payload.accountId}`);
      // Your code: mark the invoice paid, then fetch full details from the Zuora API
      break;

    case 'InvoicePosted':
      console.log(`Invoice posted for account ${payload.accountId}`);
      // Your code: email the invoice, then fetch full details from the Zuora API
      break;

    default:
      console.log(`Unhandled callout: ${event}`);
  }
}

// Read the body raw (any content type) so the request is authenticated before parsing.
app.all('/webhooks/zuora', express.raw({ type: '*/*' }), (req, res) => {
  if (!ALLOWED_METHODS.includes(req.method)) {
    res.set('Allow', ALLOWED_METHODS.join(', '));
    return res.status(405).json({ error: 'Method not allowed' });
  }

  if (!verifyZuoraRequest(req.headers)) {
    res.set('WWW-Authenticate', 'Basic realm="zuora"');
    return res.status(401).json({ error: 'Invalid or missing Basic credentials' });
  }

  // GET (and any empty body) carries its merge fields in the URL, if at all.
  const raw = Buffer.isBuffer(req.body) ? req.body.toString('utf8') : '';
  let payload;
  if (raw.trim() === '') {
    payload = { ...req.query };
  } else {
    try {
      payload = JSON.parse(raw);
    } catch {
      return res.status(400).json({ error: 'Invalid JSON body' });
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
      return res.status(400).json({ error: 'Expected a JSON object' });
    }
  }

  try {
    handleCallout(payload);
  } catch (err) {
    console.error('Error handling Zuora callout:', err);
    return res.status(500).json({ error: 'Handler error' });
  }

  // Zuora needs a 200; "success" satisfies the optional "Confirm success by parsing response content".
  res.status(200).json({ received: true, success: true });
});

app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = app;
module.exports.verifyZuoraRequest = verifyZuoraRequest;
module.exports.parseBasicAuth = parseBasicAuth;

if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: http://localhost:${PORT}/webhooks/zuora (POST, PUT, PATCH, GET, DELETE)`);
  });
}
nextjs/app/webhooks/zuora/route.ts
typescript
// Generated with: zuora-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { verifyZuoraRequest } from '../../../lib/verify-zuora';

// Callouts are never cacheable, including GET.
export const dynamic = 'force-dynamic';

interface ZuoraPayload {
  event?: string;
  accountId?: string;
  [key: string]: unknown;
}

/**
 * Zuora adds no event field: the body is whatever merge fields the callout template
 * defines. This handler assumes an illustrative JSON body such as
 * {"event": "PaymentProcessed", "accountId": "..."} that you write into the template.
 */
function handleCallout(payload: ZuoraPayload): void {
  const { event } = payload;

  switch (event) {
    case 'PaymentProcessed':
      console.log(`Payment processed for account ${payload.accountId}`);
      // Your code: mark the invoice paid, then fetch full details from the Zuora API
      break;

    case 'InvoicePosted':
      console.log(`Invoice posted for account ${payload.accountId}`);
      // Your code: email the invoice, then fetch full details from the Zuora API
      break;

    default:
      console.log(`Unhandled callout: ${event}`);
  }
}

// The callout HTTP method is set on the template (POST by default), so one handler serves all five.
async function handle(request: NextRequest) {
  // Authenticate before reading or parsing the body.
  if (!verifyZuoraRequest(request.headers)) {
    return NextResponse.json(
      { error: 'Invalid or missing Basic credentials' },
      { status: 401, headers: { 'WWW-Authenticate': 'Basic realm="zuora"' } }
    );
  }

  // Read as text so any content type is accepted. GET carries no body.
  const raw = await request.text();
  let payload: unknown;
  if (raw.trim() === '') {
    // Merge fields placed in the URL arrive as query parameters.
    payload = Object.fromEntries(request.nextUrl.searchParams);
  } else {
    try {
      payload = JSON.parse(raw);
    } catch {
      return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
      return NextResponse.json({ error: 'Expected a JSON object' }, { status: 400 });
    }
  }

  try {
    handleCallout(payload as ZuoraPayload);
  } catch (err) {
    console.error('Error handling Zuora callout:', err);
    return NextResponse.json({ error: 'Handler error' }, { status: 500 });
  }

  // Zuora needs a 200; "success" satisfies the optional "Confirm success by parsing response content".
  return NextResponse.json({ received: true, success: true });
}

export { handle as POST, handle as PUT, handle as PATCH, handle as GET, handle as DELETE };
fastapi/main.py
python
# Generated with: zuora-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hashlib
import hmac
import json
import os
import re

from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

# The callout HTTP method is set on the template (POST by default).
ALLOWED_METHODS = ["POST", "PUT", "PATCH", "GET", "DELETE"]

_BASE64 = re.compile(r"^[A-Za-z0-9+/]+={0,2}$")


def safe_equal(a: bytes, b: bytes) -> bool:
    """Constant-time comparison (compare_digest on equal-length digests of bytes)."""
    return hmac.compare_digest(hashlib.sha256(a).digest(), hashlib.sha256(b).digest())


def parse_basic_auth(header):
    """Parse "Authorization: Basic base64(username:password)".

    Scheme is case-insensitive; the credentials split on the FIRST colon, so the
    password may contain colons. Returns (username, password) as bytes, or None.
    """
    if not isinstance(header, str):
        return None
    parts = header.strip().split()
    if len(parts) != 2 or parts[0].lower() != "basic" or not _BASE64.match(parts[1]):
        return None
    try:
        decoded = base64.b64decode(parts[1], validate=True)
    except (binascii.Error, ValueError):
        return None
    username, sep, password = decoded.partition(b":")
    return (username, password) if sep else None


def verify_zuora_request(headers, username=None, password=None) -> bool:
    """Zuora callouts are not signed. The template's Username/Password authentication
    (with Enable Preemptive Authentication) sends HTTP Basic credentials on every request.
    Both values are compared before deciding, so a wrong username and a wrong password
    take the same time.
    """
    username = username if username is not None else os.environ.get("ZUORA_WEBHOOK_USERNAME")
    password = password if password is not None else os.environ.get("ZUORA_WEBHOOK_PASSWORD")
    if not username or not password:
        return False  # never accept when unconfigured
    creds = parse_basic_auth(headers.get("authorization"))
    if creds is None:
        return False

    # Encode both sides to bytes: compare_digest raises on non-ASCII str.
    user_ok = safe_equal(creds[0], username.encode("utf-8"))
    pass_ok = safe_equal(creds[1], password.encode("utf-8"))
    return user_ok and pass_ok


async def require_basic_auth(request: Request) -> None:
    """FastAPI dependency: reject the request before the body is parsed."""
    if not verify_zuora_request(request.headers):
        raise HTTPException(
            status_code=401,
            detail="Invalid or missing Basic credentials",
            headers={"WWW-Authenticate": 'Basic realm="zuora"'},
        )


def handle_callout(payload: dict) -> None:
    """Zuora adds no event field: the body is whatever merge fields the callout template
    defines. This handler assumes an illustrative JSON body such as
    {"event": "PaymentProcessed", "accountId": "..."} that you write into the template.
    """
    event = payload.get("event")

    if event == "PaymentProcessed":
        print(f"Payment processed for account {payload.get('accountId')}")
        # Your code: mark the invoice paid, then fetch full details from the Zuora API

    elif event == "InvoicePosted":
        print(f"Invoice posted for account {payload.get('accountId')}")
        # Your code: email the invoice, then fetch full details from the Zuora API

    else:
        print(f"Unhandled callout: {event}")


@app.api_route("/webhooks/zuora", methods=ALLOWED_METHODS, dependencies=[Depends(require_basic_auth)])
async def zuora_webhook(request: Request):
    # Read the raw body so any content type is accepted. GET carries no body.
    raw_body = await request.body()

    if not raw_body.strip():
        # Merge fields placed in the URL arrive as query parameters.
        payload = dict(request.query_params)
    else:
        try:
            payload = json.loads(raw_body)
        except (json.JSONDecodeError, UnicodeDecodeError):
            raise HTTPException(status_code=400, detail="Invalid JSON body")
        if not isinstance(payload, dict):
            raise HTTPException(status_code=400, detail="Expected a JSON object")

    try:
        handle_callout(payload)
    except Exception as err:  # noqa: BLE001
        print(f"Error handling Zuora callout: {err}")
        raise HTTPException(status_code=500, detail="Handler error")

    # Zuora needs a 200; "success" satisfies the optional "Confirm success by parsing response content".
    return {"received": True, "success": True}


@app.get("/health")
async def health():
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

From hookdeck/webhook-skills ↗

Or install the Zuora webhooks skill:

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

Common failures

Enable Preemptive Authentication isn't ticked

The first request then has no Authorization header, and Zuora sends credentials only after a 401 with WWW-Authenticate. Tick the setting, or send that challenge from your own endpoint.

Credentials changed on one side

Editing the username or password on the template doesn't change your stored values, and each template has its own. Update both together.

Password split on the wrong colon

Decode the base64 and split on the first colon only, because a password can contain one.

The HMAC header holds more than the signature

If you add the HMAC, the header value can have text around {{Request.HMAC.Signed}}, as in Zuora's own example, and Data can cover more than {{Request.Body}}. Parse the header and rebuild Data exactly as the template defines them.

From Hookdeck's Zuora guide

Let Event Gateway check Zuora's Basic credentials.

Tick Enable Preemptive Authentication on the template, and Event Gateway checks its username and password on each callout before it reaches your service, then queues it and retries failures on your schedule.

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