Verify Adyen webhooks

Adyen signs Standard webhooks inside the message: once you add an HMAC key to the webhook, each NotificationRequestItem carries a base64 HMAC-SHA256 in additionalData.hmacSignature, so you confirm it came from Adyen unchanged. The signature covers eight of the item's values rather than the raw body, so you parse the JSON first, and Adyen's server libraries include a validator. Some other webhook types, such as Recurring tokens life cycle events, sign the raw body and send the signature in an hmacsignature header instead.

The facts

Signature field
notificationItems[].NotificationRequestItem.additionalData.hmacSignature

Not every delivery is signed: check your setup.

Scheme
HMAC-SHA256, base64
Signed material
{pspReference}:{originalReference}:{merchantAccountCode}:{merchantReference}:{value}:{currency}:{eventCode}:{success}

Eight values from the item, in this order, joined with colons. value and currency come from amount, and an empty field stays as an empty string.

What to build
Recompute the HMAC over eight fields from each notification item, not the raw body, and compare
Key
shared secret

Adyen webhook secret

The signature uses an HMAC key you generate or enter on the webhook in your Customer Area. It's separate from your API key, and from any Basic auth or OAuth credentials on the same webhook. Keep it in an environment variable, not in source code.

  • In your Customer Area, go to Developers > Webhooks, edit the webhook and generate or enter a key under Security.
  • The key is a hexadecimal string. Convert it to binary before you compute the HMAC.
  • Each key belongs to one webhook endpoint, so generate one per endpoint.
  • Your test and live Customer Areas have different keys. Generate a new one when you go live.
  • After you generate a new key, keep accepting events signed with the old one for a while, because the change takes time to propagate.

Source: Adyen docs ↗

Code

express/src/index.js
javascript
// Generated with: adyen-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const { hmacValidator } = require('@adyen/api-library');

const app = express();

// Adyen's official HMAC validator. It builds the ':'-delimited signing string
// from the NotificationRequestItem fields, hex-decodes the key, computes
// HMAC-SHA256/base64, and timing-safe compares against additionalData.hmacSignature.
const validator = new hmacValidator();

const HMAC_KEY = process.env.ADYEN_HMAC_KEY;

/**
 * Optional Basic Auth check. Adyen can send Basic Auth credentials alongside
 * HMAC. Only enforced when both env vars are configured.
 * @returns {boolean} true if auth passes (or is not configured)
 */
function checkBasicAuth(authHeader) {
  const user = process.env.ADYEN_WEBHOOK_USERNAME;
  const pass = process.env.ADYEN_WEBHOOK_PASSWORD;
  if (!user || !pass) return true; // Basic Auth not configured

  if (!authHeader || !authHeader.startsWith('Basic ')) return false;
  const decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf8');
  const sep = decoded.indexOf(':');
  return decoded.slice(0, sep) === user && decoded.slice(sep + 1) === pass;
}

/**
 * Handle a single verified NotificationRequestItem.
 * `success` is a string ("true"/"false") and reflects the business outcome.
 */
function handleNotification(item) {
  const { eventCode, success, pspReference, merchantReference } = item;
  const ok = success === 'true';

  switch (eventCode) {
    case 'AUTHORISATION':
      // A successful AUTHORISATION means the payment was authorised.
      // success === 'false' means it was REFUSED.
      console.log(`AUTHORISATION ${ok ? 'succeeded' : 'refused'} for ${merchantReference} (${pspReference})`);
      // Your code: fulfil the order on success, notify the shopper on refusal.
      break;

    case 'CAPTURE':
      console.log(`CAPTURE ${ok ? 'succeeded' : 'failed'} for ${pspReference}`);
      // Your code: mark funds settled.
      break;

    case 'CAPTURE_FAILED':
      console.log(`CAPTURE_FAILED for ${pspReference}`);
      // Your code: retry capture or alert operations.
      break;

    case 'REFUND':
      console.log(`REFUND ${ok ? 'succeeded' : 'failed'} for ${pspReference}`);
      // Your code: update refund status.
      break;

    case 'REFUND_FAILED':
      console.log(`REFUND_FAILED for ${pspReference}`);
      // Your code: alert support, retry refund.
      break;

    case 'CANCELLATION':
      console.log(`CANCELLATION ${ok ? 'succeeded' : 'failed'} for ${pspReference}`);
      // Your code: release held inventory.
      break;

    case 'CANCEL_OR_REFUND':
      console.log(`CANCEL_OR_REFUND ${ok ? 'succeeded' : 'failed'} for ${pspReference}`);
      // Your code: reverse fulfilment.
      break;

    case 'CHARGEBACK':
      console.log(`CHARGEBACK for ${pspReference}`);
      // Your code: revoke access, update accounting.
      break;

    case 'NOTIFICATION_OF_CHARGEBACK':
      console.log(`NOTIFICATION_OF_CHARGEBACK for ${pspReference}`);
      // Your code: gather evidence to defend the dispute.
      break;

    case 'REPORT_AVAILABLE':
      console.log(`REPORT_AVAILABLE: ${item.reason || ''}`);
      // Your code: download the report.
      break;

    default:
      console.log(`Unhandled eventCode: ${eventCode} (${pspReference})`);
  }
}

// Adyen posts JSON. The HMAC is over reconstructed fields (not the raw body),
// so parsing JSON before verifying is correct for Adyen.
app.post('/webhooks/adyen', express.json(), (req, res) => {
  // 1. Optional Basic Auth
  if (!checkBasicAuth(req.headers['authorization'])) {
    return res.status(401).send('Unauthorized');
  }

  const items = req.body && req.body.notificationItems;
  if (!Array.isArray(items)) {
    return res.status(400).send('Invalid notification');
  }

  // 2. Verify the HMAC signature on every item before processing any of them.
  for (const entry of items) {
    const item = entry && entry.NotificationRequestItem;
    // validateHMAC throws if the item has no additionalData/hmacSignature —
    // treat any failure as an invalid signature.
    let valid = false;
    try {
      valid = Boolean(item) && validator.validateHMAC(item, HMAC_KEY);
    } catch {
      valid = false;
    }
    if (!valid) {
      console.error('HMAC signature verification failed');
      return res.status(401).send('Invalid HMAC signature');
    }
  }

  // 3. All items verified — process them.
  for (const entry of items) {
    handleNotification(entry.NotificationRequestItem);
  }

  // 4. Acknowledge with the literal body Adyen expects.
  res.status(200).send('[accepted]');
});

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

module.exports = { app, validator, checkBasicAuth, handleNotification };

// Start server only when run directly (not when imported for testing)
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: POST http://localhost:${PORT}/webhooks/adyen`);
  });
}
nextjs/app/webhooks/adyen/route.ts
typescript
// Generated with: adyen-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { hmacValidator } from '@adyen/api-library';

// Adyen's official HMAC validator builds the ':'-delimited signing string from
// the NotificationRequestItem fields, hex-decodes the key, computes
// HMAC-SHA256/base64, and timing-safe compares against additionalData.hmacSignature.
const validator = new hmacValidator();

interface NotificationRequestItem {
  eventCode: string;
  success: string;
  pspReference: string;
  originalReference?: string;
  merchantAccountCode?: string;
  merchantReference?: string;
  amount?: { value: number; currency: string };
  reason?: string;
  additionalData?: { hmacSignature?: string };
}

/**
 * Optional Basic Auth check. Only enforced when both env vars are configured.
 */
function checkBasicAuth(authHeader: string | null): boolean {
  const user = process.env.ADYEN_WEBHOOK_USERNAME;
  const pass = process.env.ADYEN_WEBHOOK_PASSWORD;
  if (!user || !pass) return true; // Basic Auth not configured

  if (!authHeader || !authHeader.startsWith('Basic ')) return false;
  const decoded = Buffer.from(authHeader.slice(6), 'base64').toString('utf8');
  const sep = decoded.indexOf(':');
  return decoded.slice(0, sep) === user && decoded.slice(sep + 1) === pass;
}

/** Verify a single item; returns false instead of throwing on malformed input. */
function isValid(item: NotificationRequestItem): boolean {
  try {
    // The SDK type is stricter than the parsed JSON, so cast at the boundary.
    return validator.validateHMAC(item as never, process.env.ADYEN_HMAC_KEY as string);
  } catch {
    return false;
  }
}

function handleNotification(item: NotificationRequestItem): void {
  const ok = item.success === 'true';
  switch (item.eventCode) {
    case 'AUTHORISATION':
      // success === 'false' means the payment was REFUSED.
      console.log(`AUTHORISATION ${ok ? 'succeeded' : 'refused'} for ${item.merchantReference} (${item.pspReference})`);
      // Your code: fulfil the order on success, notify the shopper on refusal.
      break;
    case 'CAPTURE':
      console.log(`CAPTURE ${ok ? 'succeeded' : 'failed'} for ${item.pspReference}`);
      break;
    case 'CAPTURE_FAILED':
      console.log(`CAPTURE_FAILED for ${item.pspReference}`);
      break;
    case 'REFUND':
      console.log(`REFUND ${ok ? 'succeeded' : 'failed'} for ${item.pspReference}`);
      break;
    case 'REFUND_FAILED':
      console.log(`REFUND_FAILED for ${item.pspReference}`);
      break;
    case 'CANCELLATION':
      console.log(`CANCELLATION ${ok ? 'succeeded' : 'failed'} for ${item.pspReference}`);
      break;
    case 'CANCEL_OR_REFUND':
      console.log(`CANCEL_OR_REFUND ${ok ? 'succeeded' : 'failed'} for ${item.pspReference}`);
      break;
    case 'CHARGEBACK':
      console.log(`CHARGEBACK for ${item.pspReference}`);
      break;
    case 'NOTIFICATION_OF_CHARGEBACK':
      console.log(`NOTIFICATION_OF_CHARGEBACK for ${item.pspReference}`);
      break;
    case 'REPORT_AVAILABLE':
      console.log(`REPORT_AVAILABLE: ${item.reason || ''}`);
      break;
    default:
      console.log(`Unhandled eventCode: ${item.eventCode} (${item.pspReference})`);
  }
}

export async function POST(request: NextRequest) {
  // 1. Optional Basic Auth
  if (!checkBasicAuth(request.headers.get('authorization'))) {
    return new NextResponse('Unauthorized', { status: 401 });
  }

  // Adyen posts JSON. HMAC is over reconstructed fields (not the raw body),
  // so parsing the JSON before verifying is correct for Adyen.
  let body: { notificationItems?: Array<{ NotificationRequestItem: NotificationRequestItem }> };
  try {
    body = await request.json();
  } catch {
    return new NextResponse('Invalid JSON', { status: 400 });
  }

  const items = body.notificationItems;
  if (!Array.isArray(items)) {
    return new NextResponse('Invalid notification', { status: 400 });
  }

  // 2. Verify every item before processing any of them.
  for (const entry of items) {
    const item = entry?.NotificationRequestItem;
    if (!item || !isValid(item)) {
      console.error('HMAC signature verification failed');
      return new NextResponse('Invalid HMAC signature', { status: 401 });
    }
  }

  // 3. All items verified — process them.
  for (const entry of items) {
    handleNotification(entry.NotificationRequestItem);
  }

  // 4. Acknowledge with the literal body Adyen expects.
  return new NextResponse('[accepted]', { status: 200 });
}
fastapi/main.py
python
# Generated with: adyen-webhooks skill
# https://github.com/hookdeck/webhook-skills
import base64
import binascii
import hashlib
import hmac
import os
import secrets

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

load_dotenv()

app = FastAPI()

HMAC_KEY = os.environ.get("ADYEN_HMAC_KEY", "")

# Fields that make up the HMAC signing string, in the exact order Adyen uses.
# (amount is flattened into value + currency.)
_SIGNED_FIELDS = (
    "pspReference",
    "originalReference",
    "merchantAccountCode",
    "merchantReference",
    "value",
    "currency",
    "eventCode",
    "success",
)


def calculate_hmac(item: dict, hex_key: str) -> str:
    """Compute the base64 HMAC-SHA256 signature for a NotificationRequestItem.

    Adyen signs a ':'-delimited string of specific fields (NOT the raw body).
    Empty/missing fields become empty strings. The Customer Area HMAC key is a
    hex string that must be hex-decoded before use.
    """
    amount = item.get("amount") or {}
    values = {
        **{k: item.get(k, "") for k in _SIGNED_FIELDS if k not in ("value", "currency")},
        "value": amount.get("value", ""),
        "currency": amount.get("currency", ""),
    }
    # Values are joined as-is: Adyen does not escape ':' or backslashes in a value.
    signing_string = ":".join(str(values[field]) for field in _SIGNED_FIELDS)

    key = binascii.unhexlify(hex_key)  # hex string -> raw bytes
    digest = hmac.new(key, signing_string.encode("utf-8"), hashlib.sha256).digest()
    return base64.b64encode(digest).decode("utf-8")


def is_valid_hmac(item: dict, hex_key: str) -> bool:
    """Timing-safe check of an item's additionalData.hmacSignature."""
    received = (item.get("additionalData") or {}).get("hmacSignature", "")
    if not received:
        return False
    try:
        expected = calculate_hmac(item, hex_key)
    except (binascii.Error, ValueError):
        return False
    return hmac.compare_digest(expected, received)


def check_basic_auth(auth_header: str | None) -> bool:
    """Optional Basic Auth. Only enforced when both env vars are configured."""
    user = os.environ.get("ADYEN_WEBHOOK_USERNAME")
    password = os.environ.get("ADYEN_WEBHOOK_PASSWORD")
    if not user or not password:
        return True  # Basic Auth not configured

    if not auth_header or not auth_header.startswith("Basic "):
        return False
    try:
        decoded = base64.b64decode(auth_header[6:]).decode("utf-8")
    except (binascii.Error, ValueError):
        return False
    got_user, _, got_pass = decoded.partition(":")
    return secrets.compare_digest(got_user, user) and secrets.compare_digest(got_pass, password)


def handle_notification(item: dict) -> None:
    """Process a single verified NotificationRequestItem."""
    event_code = item.get("eventCode")
    ok = item.get("success") == "true"  # success is a string "true"/"false"
    psp = item.get("pspReference")

    if event_code == "AUTHORISATION":
        # success == "false" means the payment was REFUSED.
        state = "succeeded" if ok else "refused"
        print(f"AUTHORISATION {state} for {item.get('merchantReference')} ({psp})")
        # Your code: fulfil the order on success, notify the shopper on refusal.
    elif event_code == "CAPTURE":
        print(f"CAPTURE {'succeeded' if ok else 'failed'} for {psp}")
    elif event_code == "CAPTURE_FAILED":
        print(f"CAPTURE_FAILED for {psp}")
    elif event_code == "REFUND":
        print(f"REFUND {'succeeded' if ok else 'failed'} for {psp}")
    elif event_code == "REFUND_FAILED":
        print(f"REFUND_FAILED for {psp}")
    elif event_code == "CANCELLATION":
        print(f"CANCELLATION {'succeeded' if ok else 'failed'} for {psp}")
    elif event_code == "CANCEL_OR_REFUND":
        print(f"CANCEL_OR_REFUND {'succeeded' if ok else 'failed'} for {psp}")
    elif event_code == "CHARGEBACK":
        print(f"CHARGEBACK for {psp}")
    elif event_code == "NOTIFICATION_OF_CHARGEBACK":
        print(f"NOTIFICATION_OF_CHARGEBACK for {psp}")
    elif event_code == "REPORT_AVAILABLE":
        print(f"REPORT_AVAILABLE: {item.get('reason', '')}")
    else:
        print(f"Unhandled eventCode: {event_code} ({psp})")


@app.post("/webhooks/adyen")
async def adyen_webhook(request: Request):
    # 1. Optional Basic Auth
    if not check_basic_auth(request.headers.get("authorization")):
        raise HTTPException(status_code=401, detail="Unauthorized")

    # Adyen posts JSON. HMAC is over reconstructed fields (not the raw body),
    # so parsing the JSON before verifying is correct for Adyen.
    try:
        body = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    items = body.get("notificationItems") if isinstance(body, dict) else None
    if not isinstance(items, list):
        raise HTTPException(status_code=400, detail="Invalid notification")

    # 2. Verify the HMAC signature on every item before processing any of them.
    for entry in items:
        item = entry.get("NotificationRequestItem") if isinstance(entry, dict) else None
        if not item or not is_valid_hmac(item, HMAC_KEY):
            raise HTTPException(status_code=401, detail="Invalid HMAC signature")

    # 3. All items verified — process them.
    for entry in items:
        handle_notification(entry["NotificationRequestItem"])

    # 4. Acknowledge with the literal body Adyen expects.
    return Response(content="[accepted]", media_type="text/plain")


@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 Adyen webhooks skill:

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

Common failures

Hashing the raw body

Standard webhooks sign eight values joined with colons, not the body. Keep empty values, so a missing originalReference leaves two colons in a row.

Using the key as text

The HMAC key is a hexadecimal string. Convert it to binary before you compute the signature.

Wrong key

Each key belongs to one webhook endpoint, and your test and live Customer Areas have different keys.

Key changed recently

A new key takes time to propagate, so keep accepting events signed with the previous key for a while.

From Hookdeck's Adyen guide

Let Event Gateway verify Adyen signatures.

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

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