Verify PayPal webhooks

PayPal signs each delivery with its private key, so you can confirm it came from PayPal and that the body wasn't changed. There's no shared secret: you build a string from two request headers, your Webhook ID and a CRC32 of the raw body, then check paypal-transmission-sig against it with the public key in the certificate at paypal-cert-url. PayPal can run the check for you through POST /v1/notifications/verify-webhook-signature, but that adds a call per delivery and PayPal prefers that you verify yourself.

The facts

Signature header
paypal-transmission-sig

Also sent: paypal-transmission-id, paypal-transmission-time, paypal-cert-url, paypal-auth-algo.

Scheme
RSA, SHA-256, base64

Asymmetric: verify with the vendor's public key.

Signed material
{paypal-transmission-id}|{paypal-transmission-time}|{webhook ID}|{CRC32 of raw body}

The two header values as sent, your listener URL's Webhook ID, and the CRC32 of the raw body in decimal, joined by pipes with no spaces.

Send timestamp
paypal-transmission-time
What to build
Verify with the vendor's public key
Key
public key

PayPal webhook public key

There's no shared secret. PayPal signs with its private key, and you verify with the public key in the certificate named by paypal-cert-url. What you store is the listener URL's Webhook ID, which is part of the signed string.

  • Webhook ID: PayPal assigns one when you subscribe a listener URL. Find it in Application management under the app's settings, or in the id the create webhook API returns.
  • It's not in the request: the ID doesn't come in the headers or the body, so store it in your configuration.
  • Not your client ID: the signed string needs the Webhook ID, and PayPal lists using the wrong one as a cause of failed validation.
  • Certificate: read its URL from paypal-cert-url, then download and cache the file. PayPal's example URLs are on api.paypal.com and api.sandbox.paypal.com.
  • Webhooks simulator: mock events belong to no app, so use the literal string WEBHOOK_ID as the ID.
  • Postback: POST /v1/notifications/verify-webhook-signature needs an OAuth access token, as well as the Webhook ID.

Source: PayPal docs ↗

Code

Docs discrepancy · read before the code

PayPal's Invoicing webhooks page describes a different signed string, with a SHA-256 hex digest of the body and a hex signature, and its Expanded Checkout best practices page says to verify HMAC signatures. Follow the integration guide's CRC32 and base64 scheme, which is what PayPal's signatures match.

PayPal docs ↗
express/src/index.js
javascript
// Generated with: paypal-webhooks skill
// https://github.com/hookdeck/webhook-skills

require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const zlib = require('zlib');
const https = require('https');

const app = express();

// Cert cache — keyed by paypal-cert-url. PayPal rotates by changing the URL,
// so a cache miss == new cert == fetch once. Exported for tests to preload.
const certCache = new Map();

function fetchCert(certUrl) {
  // SECURITY: Only trust certificates served from paypal.com hosts.
  // Both sandbox (api.sandbox.paypal.com) and live (api.paypal.com) end in .paypal.com.
  const host = new URL(certUrl).hostname;
  if (host !== 'paypal.com' && !host.endsWith('.paypal.com')) {
    return Promise.reject(new Error(`Untrusted cert URL host: ${host}`));
  }
  if (certCache.has(certUrl)) {
    return Promise.resolve(certCache.get(certUrl));
  }
  return new Promise((resolve, reject) => {
    https
      .get(certUrl, (res) => {
        let data = '';
        res.on('data', (chunk) => (data += chunk));
        res.on('end', () => {
          certCache.set(certUrl, data);
          resolve(data);
        });
      })
      .on('error', reject);
  });
}

async function verifyPayPalWebhook(headers, rawBody, webhookId) {
  const transmissionId = headers['paypal-transmission-id'];
  const transmissionTime = headers['paypal-transmission-time'];
  const transmissionSig = headers['paypal-transmission-sig'];
  const certUrl = headers['paypal-cert-url'];

  if (!transmissionId || !transmissionTime || !transmissionSig || !certUrl) {
    return false;
  }

  // CRC-32 of the raw body as an unsigned decimal integer.
  const crc = zlib.crc32(rawBody);
  const message = `${transmissionId}|${transmissionTime}|${webhookId}|${crc}`;

  let cert;
  try {
    cert = await fetchCert(certUrl);
  } catch {
    return false;
  }

  const verifier = crypto.createVerify('SHA256');
  verifier.update(message);
  verifier.end();
  try {
    return verifier.verify(cert, transmissionSig, 'base64');
  } catch {
    return false;
  }
}

// CRITICAL: express.raw() — PayPal verification needs the exact raw bytes
// because the CRC-32 of the body is part of the signed message.
app.post(
  '/webhooks/paypal',
  express.raw({ type: 'application/json' }),
  async (req, res) => {
    const webhookId = process.env.PAYPAL_WEBHOOK_ID;
    if (!webhookId) {
      console.error('PAYPAL_WEBHOOK_ID is not set');
      return res.status(500).send('Server misconfigured');
    }

    const valid = await verifyPayPalWebhook(req.headers, req.body, webhookId);
    if (!valid) {
      return res.status(400).send('Invalid signature');
    }

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

    switch (event.event_type) {
      case 'PAYMENT.CAPTURE.COMPLETED':
        console.log('Capture completed:', event.resource?.id);
        // Your code: fulfill order, send receipt
        break;
      case 'PAYMENT.CAPTURE.REFUNDED':
        console.log('Capture refunded:', event.resource?.id);
        // Your code: reverse fulfillment
        break;
      case 'PAYMENT.SALE.COMPLETED':
        console.log('Sale completed:', event.resource?.id);
        break;
      case 'CHECKOUT.ORDER.APPROVED':
        console.log('Order approved:', event.resource?.id);
        // Your code: capture payment server-side
        break;
      case 'BILLING.SUBSCRIPTION.CREATED':
        console.log('Subscription created:', event.resource?.id);
        break;
      case 'BILLING.SUBSCRIPTION.ACTIVATED':
        console.log('Subscription activated:', event.resource?.id);
        // Your code: provision access
        break;
      case 'BILLING.SUBSCRIPTION.CANCELLED':
        console.log('Subscription cancelled:', event.resource?.id);
        // Your code: revoke access at period end
        break;
      case 'CUSTOMER.DISPUTE.CREATED':
        console.log('Dispute opened:', event.resource?.dispute_id);
        // Your code: alert ops
        break;
      default:
        console.log(`Unhandled event type: ${event.event_type}`);
    }

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

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

module.exports = { app, certCache, verifyPayPalWebhook };

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/paypal`);
  });
}
nextjs/app/webhooks/paypal/route.ts
typescript
// Generated with: paypal-webhooks skill
// https://github.com/hookdeck/webhook-skills

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

// Cert cache — keyed by paypal-cert-url. Exported so tests can preload.
export const certCache = new Map<string, string>();

async function fetchCert(certUrl: string): Promise<string> {
  // SECURITY: only trust certificates served from paypal.com hosts.
  const host = new URL(certUrl).hostname;
  if (host !== 'paypal.com' && !host.endsWith('.paypal.com')) {
    throw new Error(`Untrusted cert URL host: ${host}`);
  }
  const cached = certCache.get(certUrl);
  if (cached) return cached;
  const res = await fetch(certUrl);
  if (!res.ok) throw new Error(`Failed to fetch cert: ${res.status}`);
  const pem = await res.text();
  certCache.set(certUrl, pem);
  return pem;
}

export async function verifyPayPalWebhook(
  headers: Headers,
  rawBody: Buffer,
  webhookId: string
): Promise<boolean> {
  const transmissionId = headers.get('paypal-transmission-id');
  const transmissionTime = headers.get('paypal-transmission-time');
  const transmissionSig = headers.get('paypal-transmission-sig');
  const certUrl = headers.get('paypal-cert-url');

  if (!transmissionId || !transmissionTime || !transmissionSig || !certUrl) {
    return false;
  }

  const crc = zlib.crc32(rawBody);
  const message = `${transmissionId}|${transmissionTime}|${webhookId}|${crc}`;

  let cert: string;
  try {
    cert = await fetchCert(certUrl);
  } catch {
    return false;
  }

  const verifier = crypto.createVerify('SHA256');
  verifier.update(message);
  verifier.end();
  try {
    return verifier.verify(cert, transmissionSig, 'base64');
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  const webhookId = process.env.PAYPAL_WEBHOOK_ID;
  if (!webhookId) {
    console.error('PAYPAL_WEBHOOK_ID is not set');
    return NextResponse.json({ error: 'Server misconfigured' }, { status: 500 });
  }

  // CRITICAL: read raw bytes — CRC-32 of the body is part of the signed message.
  const rawBody = Buffer.from(await request.arrayBuffer());

  const valid = await verifyPayPalWebhook(request.headers, rawBody, webhookId);
  if (!valid) {
    return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
  }

  let event: { event_type?: string; id?: string; resource?: { id?: string; dispute_id?: string } };
  try {
    event = JSON.parse(rawBody.toString('utf8'));
  } catch {
    return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 });
  }

  switch (event.event_type) {
    case 'PAYMENT.CAPTURE.COMPLETED':
      console.log('Capture completed:', event.resource?.id);
      break;
    case 'PAYMENT.CAPTURE.REFUNDED':
      console.log('Capture refunded:', event.resource?.id);
      break;
    case 'PAYMENT.SALE.COMPLETED':
      console.log('Sale completed:', event.resource?.id);
      break;
    case 'CHECKOUT.ORDER.APPROVED':
      console.log('Order approved:', event.resource?.id);
      break;
    case 'BILLING.SUBSCRIPTION.CREATED':
      console.log('Subscription created:', event.resource?.id);
      break;
    case 'BILLING.SUBSCRIPTION.ACTIVATED':
      console.log('Subscription activated:', event.resource?.id);
      break;
    case 'BILLING.SUBSCRIPTION.CANCELLED':
      console.log('Subscription cancelled:', event.resource?.id);
      break;
    case 'CUSTOMER.DISPUTE.CREATED':
      console.log('Dispute opened:', event.resource?.dispute_id);
      break;
    default:
      console.log(`Unhandled event type: ${event.event_type}`);
  }

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

import base64
import os
import zlib
from urllib.parse import urlparse

import httpx
from cryptography import x509
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Request

load_dotenv()

app = FastAPI()

# Cert cache — keyed by paypal-cert-url. PayPal rotates by changing the URL,
# so a cache miss == new cert == fetch once. Exposed for tests to preload.
cert_cache: dict[str, bytes] = {}


def fetch_cert(cert_url: str) -> bytes:
    """Fetch the PEM cert for a PayPal cert URL, with host allowlist + caching."""
    host = (urlparse(cert_url).hostname or "").lower()
    # SECURITY: only trust certs served from paypal.com hosts.
    if host != "paypal.com" and not host.endswith(".paypal.com"):
        raise ValueError(f"Untrusted cert URL host: {host}")

    cached = cert_cache.get(cert_url)
    if cached is not None:
        return cached

    response = httpx.get(cert_url, timeout=10)
    response.raise_for_status()
    pem = response.content
    cert_cache[cert_url] = pem
    return pem


def verify_paypal_webhook(headers, raw_body: bytes, webhook_id: str) -> bool:
    transmission_id = headers.get("paypal-transmission-id")
    transmission_time = headers.get("paypal-transmission-time")
    transmission_sig = headers.get("paypal-transmission-sig")
    cert_url = headers.get("paypal-cert-url")

    if not all([transmission_id, transmission_time, transmission_sig, cert_url]):
        return False

    # CRC-32 of the raw body as an UNSIGNED decimal integer.
    crc = zlib.crc32(raw_body) & 0xFFFFFFFF
    message = f"{transmission_id}|{transmission_time}|{webhook_id}|{crc}".encode()

    try:
        pem = fetch_cert(cert_url)
    except (ValueError, httpx.HTTPError):
        return False

    try:
        cert = x509.load_pem_x509_certificate(pem)
    except ValueError:
        return False

    try:
        cert.public_key().verify(
            base64.b64decode(transmission_sig),
            message,
            padding.PKCS1v15(),
            hashes.SHA256(),
        )
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


@app.post("/webhooks/paypal")
async def paypal_webhook(request: Request):
    webhook_id = os.environ.get("PAYPAL_WEBHOOK_ID")
    if not webhook_id:
        raise HTTPException(status_code=500, detail="Server misconfigured")

    # CRITICAL: read raw bytes — CRC-32 of the body is part of the signed message.
    raw_body = await request.body()

    if not verify_paypal_webhook(request.headers, raw_body, webhook_id):
        raise HTTPException(status_code=400, detail="Invalid signature")

    try:
        event = await request.json()
    except Exception:
        raise HTTPException(status_code=400, detail="Invalid JSON")

    event_type = event.get("event_type")
    resource = event.get("resource") or {}

    if event_type == "PAYMENT.CAPTURE.COMPLETED":
        print(f"Capture completed: {resource.get('id')}")
    elif event_type == "PAYMENT.CAPTURE.REFUNDED":
        print(f"Capture refunded: {resource.get('id')}")
    elif event_type == "PAYMENT.SALE.COMPLETED":
        print(f"Sale completed: {resource.get('id')}")
    elif event_type == "CHECKOUT.ORDER.APPROVED":
        print(f"Order approved: {resource.get('id')}")
    elif event_type == "BILLING.SUBSCRIPTION.CREATED":
        print(f"Subscription created: {resource.get('id')}")
    elif event_type == "BILLING.SUBSCRIPTION.ACTIVATED":
        print(f"Subscription activated: {resource.get('id')}")
    elif event_type == "BILLING.SUBSCRIPTION.CANCELLED":
        print(f"Subscription cancelled: {resource.get('id')}")
    elif event_type == "CUSTOMER.DISPUTE.CREATED":
        print(f"Dispute opened: {resource.get('dispute_id')}")
    else:
        print(f"Unhandled event type: {event_type}")

    return {"received": True}


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

From hookdeck/webhook-skills ↗

Or install the PayPal webhooks skill:

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

Common failures

Body parsed before verification

The CRC32 covers the bytes PayPal sent, and re-serialized JSON gives a different value. Calculate it from the raw body. The postback API also needs the event exactly as you received it.

Wrong ID in the signed string

Use the Webhook ID of the listener URL that received the delivery, not your client ID. Simulator events use the literal string WEBHOOK_ID.

CRC32 in the wrong form

The signed string needs the checksum as a decimal number, so a hex value fails. So do spaces around the pipes, which PayPal's written template shows but its sample code leaves out.

Reusing IPN validation

If you're moving from Instant Payment Notifications, replace that logic. PayPal says the two validation models are different.

From Hookdeck's PayPal guide

Let Event Gateway verify PayPal signatures.

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

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