Advanced Webhooks

Webhooks

Receive signed ExtensionBill events on your own server when orders, subscriptions, licenses, installs and disputes change.

Webhooks push ExtensionBill events (an order was paid, a subscription renewed, a license was activated) to an HTTPS endpoint on your server. You only need them when your own backend must react to billing changes: provisioning a web app, syncing a CRM or mailing list, posting sales to a team chat, or keeping accounting records in step.

Your extension never needs a webhook. The SDK refreshes the user’s state by itself (see Checking access), and ExtensionBill receives and verifies PayPal’s webhooks for you. To ask “does this user have access right now?” from your backend, call the Server API instead: webhooks tell you that something changed, the Server API tells you the current state.

Quick setup

  1. Pick the environment with the Sandbox/Live toggle in the dashboard’s top bar. Each environment has its own endpoints and secrets.

  2. Add an endpoint. Open Developers → Webhooks, click Add endpoint and enter a https:// URL. In sandbox, http://localhost (any port and path) is also accepted.

  3. Choose events. Select the types you want, or leave the selection empty to receive every event, including types added in the future.

  4. Copy the signing secret. The whsec_… secret is shown once after saving. Store it in your server’s environment as EXTENSIONBILL_WEBHOOK_SECRET. ExtensionBill stores it encrypted and never displays it again.

  5. Deploy a handler that verifies the signature and handles events, like the one below.

  6. Send a test event. Click Send test on the endpoint. The signed event appears in the deliveries log with the status and body your server returned.

Example handler (Node.js and Express)

// server.js
import crypto from 'node:crypto'
import express from 'express'

const WEBHOOK_SECRET = process.env.EXTENSIONBILL_WEBHOOK_SECRET // whsec_…
const TOLERANCE_SECONDS = 300

function parseSignatureHeader(header) {
  let timestamp = null
  const signatures = []
  for (const part of header.split(',')) {
    const index = part.indexOf('=')
    if (index === -1) continue
    const key = part.slice(0, index).trim()
    const value = part.slice(index + 1).trim()
    if (key === 't') timestamp = Number(value)
    if (key === 'v1') signatures.push(value)
  }
  return { timestamp, signatures }
}

function verifyExtensionBillSignature(rawBody, header, secret) {
  if (typeof header !== 'string' || header.length === 0) return false
  const { timestamp, signatures } = parseSignatureHeader(header)
  if (!Number.isInteger(timestamp) || signatures.length === 0) return false

  const now = Math.floor(Date.now() / 1000)
  if (Math.abs(now - timestamp) > TOLERANCE_SECONDS) return false

  const expected = Buffer.from(
    crypto
      .createHmac('sha256', secret)
      .update(`${timestamp}.`)
      .update(rawBody)
      .digest('hex'),
    'utf8',
  )

  return signatures.some((signature) => {
    const received = Buffer.from(signature, 'utf8')
    // timingSafeEqual throws when lengths differ, so check first.
    return received.length === expected.length && crypto.timingSafeEqual(received, expected)
  })
}

// Event ids already handled. With more than one server instance, store these in
// your database with a unique index on the event id instead of in memory.
const processedEventIds = new Map()
const DEDUPE_WINDOW_MS = 3 * 24 * 60 * 60 * 1000

function markProcessed(eventId) {
  const now = Date.now()
  for (const [id, at] of processedEventIds) {
    if (now - at > DEDUPE_WINDOW_MS) processedEventIds.delete(id)
  }
  if (processedEventIds.has(eventId)) return false
  processedEventIds.set(eventId, now)
  return true
}

async function handleEvent(event) {
  switch (event.type) {
    case 'order.paid': {
      const order = event.data
      console.log(`Order ${order.number} paid by ${order.customer?.email}: ${order.amounts.total} ${order.amounts.currency}`)
      break
    }
    case 'order.refunded': {
      const order = event.data
      console.log(`Order ${order.number} refunded: ${order.refundedAmount} ${order.amounts.currency}`)
      break
    }
    case 'subscription.canceled': {
      const subscription = event.data
      console.log(`Subscription ${subscription.id} canceled, access until ${subscription.cancelAt}`)
      break
    }
    case 'entitlement.revoked': {
      const entitlement = event.data
      console.log(`Access to ${entitlement.entitlementKey} revoked (${entitlement.revokedReason})`)
      break
    }
    default:
      // Ignore event types you don't use.
      break
  }
}

const app = express()

// express.raw keeps the body as a Buffer so the signature can be checked
// against the exact bytes ExtensionBill sent. Register it on this route only,
// before any global express.json() middleware touches the request.
app.post('/webhooks/extensionbill', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.get('ExtensionBill-Signature')
  if (!Buffer.isBuffer(req.body) || !verifyExtensionBillSignature(req.body, signature, WEBHOOK_SECRET)) {
    return res.status(400).json({ error: 'invalid_signature' })
  }

  const event = JSON.parse(req.body.toString('utf8'))
  const eventId = req.get('ExtensionBill-Event-Id') ?? event.id

  // Acknowledge first, then do the work: ExtensionBill waits at most 10 seconds.
  res.status(200).json({ received: true })

  if (!markProcessed(eventId)) return
  setImmediate(() => {
    handleEvent(event).catch((err) => {
      console.error(`Failed to handle ${event.type} ${eventId}`, err)
    })
  })
})

app.listen(3000, () => {
  console.log('Listening for ExtensionBill webhooks on http://localhost:3000/webhooks/extensionbill')
})

Return a 2xx as soon as the signature checks out, then do the work (in-process as above, or in a job queue). Handlers slower than 10 seconds count as failures and are retried, which causes duplicate work.

Verifying signatures

Every delivery is a POST with these headers:

HeaderValue
Content-Typeapplication/json
ExtensionBill-Signaturet=<unix seconds>,v1=<hex signature>
ExtensionBill-Event-IdSame value as the payload’s id (evt_…)
User-AgentExtensionBill-Webhooks/1.0

The signature is an HMAC-SHA256, keyed with your endpoint secret, over `${t}.${rawBody}` (the header timestamp, a literal dot, then the exact raw body bytes), encoded as lowercase hex. To verify:

  1. Read the raw body. Parsing and re-serializing JSON changes whitespace or key order and breaks the signature.
  2. Split ExtensionBill-Signature on , and read the t= and v1= values.
  3. Reject the request if t is more than 300 seconds (5 minutes) from your server’s clock. This stops replays.
  4. Compute the HMAC over `${t}.${rawBody}` and compare it with v1 in constant time.
  5. Only then parse the JSON and handle the event.

Serverless and edge (Web Crypto)

For runtimes that hand you a standard Request, expect a Response and ship Web Crypto instead of node:crypto. No dependencies; crypto.subtle.verify does the constant-time comparison.

// extensionbill-webhook.js
const TOLERANCE_SECONDS = 300
const encoder = new TextEncoder()

function hexToBytes(hex) {
  if (!/^[0-9a-f]{64}$/i.test(hex)) return null
  const bytes = new Uint8Array(32)
  for (let i = 0; i < 32; i++) bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16)
  return bytes
}

async function verifySignature(rawBody, header, secret) {
  if (!header) return false
  let timestamp = null
  const signatures = []
  for (const part of header.split(',')) {
    const index = part.indexOf('=')
    if (index === -1) continue
    const key = part.slice(0, index).trim()
    const value = part.slice(index + 1).trim()
    if (key === 't') timestamp = Number(value)
    if (key === 'v1') signatures.push(value)
  }
  if (!Number.isInteger(timestamp) || signatures.length === 0) return false
  if (Math.abs(Math.floor(Date.now() / 1000) - timestamp) > TOLERANCE_SECONDS) return false

  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['verify'],
  )

  // Signed content: `${t}.` followed by the exact raw body bytes.
  const prefix = encoder.encode(`${timestamp}.`)
  const signed = new Uint8Array(prefix.length + rawBody.byteLength)
  signed.set(prefix, 0)
  signed.set(new Uint8Array(rawBody), prefix.length)

  for (const signature of signatures) {
    const bytes = hexToBytes(signature)
    if (bytes && (await crypto.subtle.verify('HMAC', key, bytes, signed))) return true
  }
  return false
}

export async function handleExtensionBillWebhook(request, secret) {
  if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 })

  const rawBody = await request.arrayBuffer()
  const valid = await verifySignature(rawBody, request.headers.get('ExtensionBill-Signature'), secret)
  if (!valid) return new Response('Invalid signature', { status: 400 })

  const event = JSON.parse(new TextDecoder().decode(rawBody))

  if (event.type === 'order.paid') {
    console.log(`Order ${event.data.number} paid by ${event.data.customer?.email}`)
  }

  return new Response(null, { status: 204 })
}

export default {
  async fetch(request, env) {
    return handleExtensionBillWebhook(request, env.EXTENSIONBILL_WEBHOOK_SECRET)
  },
}

Adapt the default export to your platform’s entry point. handleExtensionBillWebhook(request, secret) works anywhere Request, Response and crypto.subtle exist (including Node 20+). Serverless functions usually share no memory between invocations, so deduplicate by ExtensionBill-Event-Id in your database or key-value store.

Event types

Event type strings are stable. Each event’s data is the affected record as returned by the API, plus a customer object (id, email, name, country) when the record belongs to a customer.

EventSent whendata
checkout.completedA buyer finished a hosted checkout (one-time payment captured or subscription approved).Checkout session
order.paidA one-time purchase was captured, or a subscription renewal payment completed.Order
order.refundedAn order was fully or partially refunded, from the dashboard or directly in PayPal.Order
order.payment_failedPayPal denied a payment capture.Order
subscription.createdThe buyer approved a subscription at PayPal.Subscription
subscription.activatedThe subscription became active (also when a free trial starts or after a reactivation).Subscription
subscription.renewedA recurring payment succeeded and the billing period advanced.Subscription
subscription.updatedThe plan, price or billing dates changed.Subscription
subscription.canceledCanceled by the buyer, by you or by PayPal. Access runs until cancelAt.Subscription
subscription.suspendedPaused (suspended at PayPal). Access is off while suspended.Subscription
subscription.expiredThe subscription reached its end and access ended.Subscription
subscription.payment_failedA recurring payment failed; the subscription is past_due and PayPal will retry.Subscription
license.createdA license key was issued (after a purchase or manually). Only keyLast4 is included, never the full key.License
license.activatedA license key was activated on an install.License
license.deactivatedA license key was removed from an install.License
license.revokedA license key was revoked (manually or by a full refund).License
entitlement.grantedA customer or install gained access to a product (purchase, subscription, license or manual grant).Entitlement
entitlement.revokedAccess to a product was removed.Entitlement
install.createdThe SDK registered a new install of your extension.Install
install.uninstalledA user uninstalled your extension (the uninstall link was opened).Install
trial.startedAn install started a free trial.Install
dispute.createdA buyer opened a PayPal dispute or chargeback.Dispute
dispute.updatedThe dispute’s status or stage changed.Dispute
dispute.resolvedThe dispute was closed.Dispute

Payload

{
  "id": "evt_9mQ2xVb7LkP4sTn8RwYc3HdZ",
  "type": "order.paid",
  "created": "2026-10-12T14:03:27.512Z",
  "env": "live",
  "appId": "66f1c2a9e4b0d3a1c8f7e210",
  "data": {
    "id": "6703a7f1c9e4b2d5a1f0c388",
    "appId": "66f1c2a9e4b0d3a1c8f7e210",
    "env": "live",
    "number": "EB-M1Q8Z4K7",
    "receiptNumber": "EB-M1Q8Z4K7",
    "customerId": "6703a7e0c9e4b2d5a1f0c381",
    "installId": "3f0b8f1e-6c1d-4f7a-9a52-1e7d0c4b9a21",
    "checkoutSessionId": "cs_Q7mN2pXv8LkR4tBz9WcY1HdF",
    "productId": "66f1c3b2e4b0d3a1c8f7e2a4",
    "priceId": "66f1c3b2e4b0d3a1c8f7e2a6",
    "productName": "Pro",
    "priceType": "one_time",
    "amounts": {
      "subtotal": 1900,
      "discount": 0,
      "tax": 0,
      "total": 1900,
      "currency": "USD"
    },
    "paypalFee": 85,
    "net": 1815,
    "status": "paid",
    "paypalOrderId": "5O190127TN364715T",
    "paypalCaptureId": "3C679366HH908993F",
    "refunds": [],
    "refundedAmount": 0,
    "discountCode": null,
    "customFields": {},
    "paidAt": "2026-10-12T14:03:26.980Z",
    "createdAt": "2026-10-12T14:02:51.104Z",
    "updatedAt": "2026-10-12T14:03:27.301Z",
    "customer": {
      "id": "6703a7e0c9e4b2d5a1f0c381",
      "email": "ada@example.com",
      "name": "Ada Lovelace",
      "country": "GB"
    }
  }
}
  • id is unique per event. Retries of the same event reuse the same id.
  • created is when the change happened (ISO 8601, UTC).
  • Money is an integer in minor units plus an uppercase ISO currency: 1900 + USD is $19.00. Zero-decimal currencies (JPY, HUF, TWD) have no minor unit.
  • Ignore unknown fields and unknown event types; new ones may be added.

Retries and failures

A delivery succeeds when your endpoint answers with any 2xx status within 10 seconds. Anything else (a non-2xx status including redirects, a timeout, a TLS or connection error) is a failed attempt. Failed deliveries are retried with backoff, each delay counted from the previous failed attempt:

AttemptDelay
1immediately
21 minute
35 minutes
430 minutes
52 hours
66 hours
712 hours

After the 7th failed attempt the delivery is marked failed; you can still retry it manually. Retries run from a job that ticks every minute, so an attempt may happen up to a minute after its nominal time.

Deliveries log

Each endpoint lists every event sent to it with:

  • status: pending (waiting for its next attempt), succeeded or failed (all attempts used),
  • number of attempts and the time of the next attempt,
  • the last HTTP status your server returned, the first 1 KB of the response body, and the last network error, if any.

Click Retry on any delivery to send it again right away, for example after fixing a bug in your handler.

Ordering and idempotency

  • Ordering is not guaranteed. A retry of an older event can arrive after a newer one, and related events (for example order.paid, entitlement.granted and checkout.completed) can arrive in any order. Use the record’s updatedAt, or fetch the current state from the Server API.
  • Deliveries can repeat. A timeout after your server already processed the event, or a manual retry, sends the same event again with the same ExtensionBill-Event-Id. Store processed event ids (a unique index works well) and skip duplicates.
  • Make handlers idempotent. “Set the customer’s plan to Pro” is safe to run twice; “add one month of credit” is not, unless guarded by the event id.
  • Treat events as hints for critical decisions. Before granting something valuable, re-read the record from the Server API.

Testing

  • Send test on an endpoint delivers a signed test event immediately. Check the result in the deliveries log.
  • Local server: in sandbox, point an endpoint at http://localhost:<port>/<path> and run the example handler.
  • Real flows: purchases made with pk_test_… keys and PayPal sandbox accounts reach sandbox endpoints only (see Testing with PayPal sandbox).
  • Going live: live purchases reach live endpoints only. Before going live, switch the dashboard to Live and add your production endpoint there; it gets its own whsec_… secret.