Gareth Wilson Gareth Wilson

Guide to Flexprice Webhooks: Features and Best Practices

Published


Flexprice is an open-source billing platform for usage-based pricing. You send it usage events, it meters them against plans, and it handles subscriptions, invoices, payments, prepaid wallets and feature entitlements. Its webhooks tell your product when billing state changes: an invoice is finalised or paid, a payment fails, a subscription changes plan, a wallet's credit runs low, a customer exhausts a feature grant, or a usage event is rejected because it matched no meter. That is how your app grants or removes access in step with billing.

What are Flexprice webhooks?

You register endpoints in the Flexprice dashboard and choose events for each. How they are delivered depends on where Flexprice runs:

  • Flexprice Cloud always delivers through Svix. Every request is signed and carries svix-id, svix-timestamp and svix-signature.
  • Self-hosted Flexprice uses Svix only if you enable it in configuration. Its default native delivery sends the JSON body with headers set for the tenant and no signature.

This guide's verification applies to Cloud and to self-hosted instances with Svix enabled.

Flexprice webhook features

FeatureDetails
MethodPOST, JSON body
SuccessAny 2xx within 5 seconds
DeliveryAt least once, sent in order but may arrive out of order
ConfigurationDashboard, Developers > Webhooks, or flexprice open webhooks
EnvironmentsSandbox and production endpoints are separate
SignatureStandard Webhooks HMAC-SHA256 (Cloud, or self-hosted with Svix)
Signature headersvix-signature, with svix-id and svix-timestamp
SecretPer endpoint, whsec_..., on the endpoint's page
RotationGrace period with two v1, signatures
Event routingBody field event_type
Retries (Cloud)Immediately, 5 s, 5 min, 30 min, 2 h, 5 h, 10 h, 10 h
Retries (self-hosted native)3 within 2 minutes
Auto-disableAfter several days of failures. 410 doesn't disable
Source IPsNot published

Events and payloads

Flexprice documents 60 events. These are the ones a billing integration usually handles first:

EventTriggered WhenCommon Use Cases
customer.createdA customer is createdMirror customers into your app
customer.updatedA customer is updatedKeep records in sync
customer.deletedA customer is deletedDeprovision
subscription.createdA subscription is createdProvision access
subscription.activatedA draft subscription is activatedProvision access
subscription.updatedQuantity, billing anchor or metadata changesSync plan state
subscription.plan_changedA subscription moves to another plan in placeChange entitlements
subscription.cancelledA subscription is cancelledDeprovision
invoice.update.finalizedAn invoice is finalized and locked for paymentSend or sync the invoice
invoice.update.paymentAn invoice's payment status changesMark paid / unpaid
invoice.update.voidedAn invoice is voidedReverse bookkeeping
invoice.payment.overdueAn invoice is past its due dateDunning
payment.successA payment succeedsConfirm fulfilment
payment.failedA payment failsNotify the customer
wallet.credit_balance.droppedA wallet's credit balance drops below an alert thresholdLow-credit warning
checkout.session.completedPayment confirmed; subscription active, invoice finalizedComplete the signup
event.rejectedA usage event matched no meter and was droppedCatch metering mistakes

The full list, by family:

  • Customer: customer.created, customer.updated, customer.deleted
  • Subscription: subscription.created, subscription.draft.created, subscription.activated, subscription.updated, subscription.paused, subscription.cancelled, subscription.resumed, subscription.plan_changed, subscription.phase.created, subscription.phase.updated, subscription.phase.deleted, subscription.spend.threshold_reached, subscription.spend.threshold_recovered, subscription.line_item_spend.threshold_reached, subscription.line_item_spend.threshold_recovered, subscription.group_spend.threshold_reached, subscription.group_spend.threshold_recovered, subscription.renewal.due
  • Invoice: invoice.update.finalized, invoice.update.payment, invoice.update.voided, invoice.update, invoice.payment.overdue, invoice.communication.triggered
  • Payment and refund: payment.created, payment.updated, payment.failed, payment.success, payment.pending, refund.created, refund.succeeded, refund.failed
  • Credit note: credit_note.created, credit_note.updated
  • Wallet: wallet.created, wallet.updated, wallet.terminated, wallet.transaction.created, wallet.transaction.updated, wallet.credit_balance.dropped, wallet.credit_balance.recovered, wallet.ongoing_balance.dropped, wallet.ongoing_balance.recovered, wallet.ongoing_balance.updated
  • Feature and entitlement: feature.created, feature.updated, feature.deleted, feature.wallet_balance.alert, entitlement.created, entitlement.updated, entitlement.deleted, entitlement.grant.exhausted
  • Checkout: checkout.session.initiated, checkout.session.completed, checkout.session.failed, checkout.session.expired
  • Usage ingestion: event.rejected

Threshold events come in pairs. A threshold_reached or dropped event fires when a value crosses the line, and the matching recovered event fires when it crosses back.

Every body has event_type and one key named after the resource, such as invoice, holding the object as the API returns it, with its id and updated_at. Flexprice prints only that envelope fragment; the per-event pages are schemas.

Setting up Flexprice webhooks

  1. In the dashboard, go to Developers > Webhooks, or run flexprice open webhooks from the Flexprice CLI.
  2. Click Add Endpoint and enter a public HTTPS URL.
  3. Choose events. A typical start is invoice.update.finalized, invoice.update.payment, payment.success, payment.failed, subscription.created, subscription.updated, subscription.cancelled and wallet.credit_balance.dropped.
  4. Copy the endpoint's signing secret, which starts with whsec_, into FLEXPRICE_WEBHOOK_SECRET.

Repeat in the other environment: sandbox and production each need their own endpoint and secret.

For a self-hosted instance, enable Svix in the webhook configuration if you want signed deliveries. Otherwise, configure a static secret header in the tenant's webhook settings and check it in your own handler.

To use Hookdeck, create a source with the Flexprice type, paste the endpoint secret, and register the source URL. Hookdeck's configuration alert for this source notes that only Flexprice Cloud signs webhooks and that unsigned self-hosted deliveries fail verification. If you run self-hosted without Svix, leave verification off on the source. Forward events locally with the Hookdeck CLI:

npx hookdeck-cli listen 3000 flexprice --path /webhooks/flexprice

To rotate a secret, use the endpoint's page. For a grace period, deliveries carry two v1, entries, one for each secret, so deploy the new value during that window.

Securing Flexprice webhooks

Flexprice's verification page spells out the Svix scheme: strip whsec_, base64-decode the rest as the key, sign <svix-id>.<svix-timestamp>.<raw body> with HMAC-SHA256, and compare in constant time with each v1, entry. The function below does that and also reads webhook-* headers if svix-id is missing:

const crypto = require('node:crypto');

function decodeBase64(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null;
  const bytes = Buffer.from(value, 'base64');
  return bytes.length > 0 && bytes.toString('base64').replace(/=+$/, '') === value.replace(/=+$/, '')
    ? bytes : null;
}

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const prefix = headers['svix-id'] ? 'svix' : 'webhook';
  const id = headers[`${prefix}-id`];
  const timestamp = headers[`${prefix}-timestamp`];
  const signature = headers[`${prefix}-signature`];
  if (typeof id !== 'string' || !id || typeof timestamp !== 'string' ||
      !/^[0-9]+$/.test(timestamp) || typeof signature !== 'string') return false;
  const key = decodeBase64(secret.replace(/^whsec_/, ''));
  if (!key) return false;
  const message = Buffer.concat([Buffer.from(`${id}.${timestamp}.`, 'utf8'), rawBody]);
  const candidates = signature.split(/\s+/).filter((item) => item.startsWith('v1,')).map((item) => item.slice(3));
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    const received = decodeBase64(candidate);
    if (!received) return false;
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

Flexprice also tells you to reject a svix-timestamp more than five minutes from now. That's sound for a direct receiver. If Hookdeck sits in front, leave it out or widen it: Hookdeck applies no timestamp tolerance and keeps the original timestamp when it retries or replays an event.

Cloud gives you five seconds to answer. The receiver writes the event and responds; provisioning happens in a worker:

const express = require('express');

// Returns the parsed body when it is a JSON object, otherwise null.
function parseJsonObject(rawBody) {
  try {
    const value = JSON.parse(rawBody.toString('utf8'));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch {
    return null;
  }
}

// billingEvents.insert(svixId, event) stores the event and resolves once durable.
function createFlexpriceReceiver(billingEvents) {
  const app = express();
  app.post('/webhooks/flexprice', express.raw({ type: '*/*' }), async (req, res) => {
    const secret = process.env.FLEXPRICE_WEBHOOK_SECRET;
    if (!secret) return res.sendStatus(500);
    if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(401);

    const event = parseJsonObject(req.body);
    if (!event) return res.sendStatus(400); // signed, but not a JSON object
    try {
      await billingEvents.insert(req.headers['svix-id'], event);
    } catch {
      return res.sendStatus(503);
    }
    return res.sendStatus(200); // also for event types you don't handle
  });
  return app;
}

A Hookdeck Flexprice source returns 200 to Flexprice on every request. Signature failures are recorded in Hookdeck as failed verification and aren't forwarded.

Make Flexprice webhooks production-ready. Hookdeck Event Gateway verifies Flexprice Cloud's Svix signatures, stores every invoice, payment and wallet event, and gives your provisioning service more than five seconds to do its work.

Flexprice webhook limitations and pain points

Self-hosted deliveries are unsigned by default

The Problem: Requests from your own Flexprice instance have no signature headers, and every verifier rejects them.

Why It Happens: Native delivery, the self-hosted default, sends the body with tenant-configured headers and no signature. Only Svix-based delivery signs.

Workarounds:

  • Enable Svix in the self-hosted configuration.
  • Or check a static secret header from the tenant's webhook settings in your handler, and keep the endpoint private.

How Hookdeck Can Help: For unsigned self-hosted deliveries, leave verification off on the Hookdeck source and restrict who knows its URL. You still get storage, retries and replay.

A five-second response window

The Problem: A handler that provisions access or calls your database slowly gets retried, and the same event runs twice.

Why It Happens: Flexprice Cloud counts anything slower than five seconds as a failure and retries.

Workarounds:

  • Store, respond, then process.
  • Deduplicate on svix-id and keep the record for at least three days, which covers the retry schedule.

How Hookdeck Can Help: Hookdeck answers Flexprice immediately and lets you set a longer delivery timeout towards your own service.

Order isn't guaranteed

The Problem: An invoice.update.payment arrives before the invoice.update.finalized for the same invoice, and your state goes backwards.

Why It Happens: Flexprice sends events in order, but retries and at-least-once delivery mean they can arrive out of order.

Workarounds:

  • Read status from the object (invoice.invoice_status, invoice.payment_status), not from the event name.
  • Compare updated_at before overwriting what you've stored.

How Hookdeck Can Help: Hookdeck's event log shows the payload of each delivery, so you can check which version of an object arrived when.

Short retries on self-hosted

The Problem: A brief outage loses events from a self-hosted instance.

Why It Happens: Native delivery retries three times within two minutes, compared with about 28 hours on Cloud.

Workarounds:

  • Enable Svix delivery, or keep the receiver highly available.

How Hookdeck Can Help: Pointing native delivery at a Hookdeck source means the first attempt lands somewhere that is always up, and Hookdeck retries your service from there.

Best practices

Return 200 for events you ignore

Flexprice retries anything that isn't 2xx. If you subscribed broadly, acknowledge event types you don't handle so they don't retry for a day.

Act on event.rejected

A rejected usage event matched no meter and was dropped. Alert on it, because that usage won't be billed until you fix whatever made it miss the meter.

Watch wallet and entitlement thresholds

wallet.credit_balance.dropped and entitlement.grant.exhausted are the signals to warn a customer or restrict a feature. Clear the warning on the matching recovered event.

Make processing idempotent

Use svix-id as the key. The idempotency walkthrough shows how to store it.

Conclusion

Flexprice reports the billing lifecycle in 60 events, signed by Svix on Cloud. Self-hosted delivery is unsigned by default, so if you run your own instance, decide early between Svix and native delivery.

Hookdeck Event Gateway can sit in front of either: verifying Cloud signatures, buffering self-hosted deliveries, and giving your service time to process. Sign up for free.


Gareth Wilson

Gareth Wilson

Product Marketing

Multi-time founding marketer, Gareth is PMM at Hookdeck and author of the newsletter, Community Inc.