# Guide to Flexprice Webhooks: Features and Best Practices

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

| Feature | Details |
| --- | --- |
| Method | `POST`, JSON body |
| Success | Any `2xx` within 5 seconds |
| Delivery | At least once, sent in order but may arrive out of order |
| Configuration | Dashboard, **Developers > Webhooks**, or `flexprice open webhooks` |
| Environments | Sandbox and production endpoints are separate |
| Signature | Standard Webhooks HMAC-SHA256 (Cloud, or self-hosted with Svix) |
| Signature header | `svix-signature`, with `svix-id` and `svix-timestamp` |
| Secret | Per endpoint, `whsec_...`, on the endpoint's page |
| Rotation | Grace period with two `v1,` signatures |
| Event routing | Body 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-disable | After several days of failures. `410` doesn't disable |
| Source IPs | Not published |

## Events and payloads

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

| Event | Triggered When | Common Use Cases |
| --- | --- | --- |
| `customer.created` | A customer is created | Mirror customers into your app |
| `customer.updated` | A customer is updated | Keep records in sync |
| `customer.deleted` | A customer is deleted | Deprovision |
| `subscription.created` | A subscription is created | Provision access |
| `subscription.activated` | A draft subscription is activated | Provision access |
| `subscription.updated` | Quantity, billing anchor or metadata changes | Sync plan state |
| `subscription.plan_changed` | A subscription moves to another plan in place | Change entitlements |
| `subscription.cancelled` | A subscription is cancelled | Deprovision |
| `invoice.update.finalized` | An invoice is finalized and locked for payment | Send or sync the invoice |
| `invoice.update.payment` | An invoice's payment status changes | Mark paid / unpaid |
| `invoice.update.voided` | An invoice is voided | Reverse bookkeeping |
| `invoice.payment.overdue` | An invoice is past its due date | Dunning |
| `payment.success` | A payment succeeds | Confirm fulfilment |
| `payment.failed` | A payment fails | Notify the customer |
| `wallet.credit_balance.dropped` | A wallet's credit balance drops below an alert threshold | Low-credit warning |
| `checkout.session.completed` | Payment confirmed; subscription active, invoice finalized | Complete the signup |
| `event.rejected` | A usage event matched no meter and was dropped | Catch 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](https://docs.flexprice.io/docs/getting-started/configuration#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](/docs/cli):

```bash
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:

```javascript
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:

```javascript
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](/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](/docs/destinations#set-a-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](/webhooks/guides/implement-webhook-idempotency) 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](https://hookdeck.com) can sit in front of either: verifying Cloud signatures, buffering self-hosted deliveries, and giving your service time to process. [Sign up for free](https://dashboard.hookdeck.com/signup).