Counting revenue you can trust: signed webhooks, refunds and currencies

How Leverprice builds verified revenue webhooks: provider signatures, HMAC attribution, idempotent writes, refunds as signals, test mode and currencies.

Short answer

Leverprice moves traffic toward the price that earns the most, so its revenue numbers have to be trustworthy. A purchase counts as verified only when the payment provider's signed webhook confirms it; unverified reports never overwrite it, refunds are recomputed from stored signals, and payments in other currencies are converted back to the experiment's currency.

  • Only a webhook signed by Stripe, Polar, Lemon Squeezy or Dodo Payments marks a purchase verified, and by default, once a provider is connected, the engine learns from verified purchases only.
  • Leverprice holds your webhook signing secret, never an API key: it can confirm events but cannot move money.
  • Checkout attribution carries an HMAC tag, and a purchase whose tag fails to verify is recorded but counts toward no price.
  • Refunds are stored as signals and the refunded amount is recomputed from them, so a redelivered refund can't be subtracted twice.
  • Failed writes retry with backoff for about a day, then land in a dead-letter queue that alerts first and keeps retrying.

Leverprice moves real traffic toward whichever price earns the most revenue per visitor. Example: one fake $500 purchase attributed to your $49 price would make $49 look better and pull more of your visitors toward it. So once you connect a payment provider, the engine learns only from purchases the provider itself has signed.

Below are the rules that make that work, including the gaps we know about. The price side of the same problem, how configs are signed, is in why we sign every price config.

Why can't the engine trust what your server reports?

Because a report proves only that someone holding your secret API key sent it. The SDK's trackPurchase() is authenticated by that key, and so is every request made with a leaked copy of it.

The delivery channels add their own noise. Stripe may deliver the same event more than once (Stripe) and does not guarantee order (Stripe). Our own queue on Cloudflare delivers at least once, and on rare occasions more than once (Cloudflare).

Then there is the data itself. Visitors can edit anything that travels in a checkout link. Refunds can arrive before the purchase they belong to. Test purchases look like live ones, and a buyer in Japan may pay in yen for a price you set in dollars.

Each of those would bend the numbers the engine uses to split your traffic. The sections below take them one at a time.

What makes a purchase verified?

A signature from your payment provider over the exact webhook it sent.

You connect a provider by giving Leverprice its webhook signing secret. A signing secret can confirm that an event came from the provider, but it can't call the provider's API, so it can't move money. We never ask for an API key.

The secret is stored encrypted with AES-256-GCM and bound to its database record. Our API encrypts it and our edge decrypts it to check signatures; the engine, which holds our config-signing keys, can't read it at all.

When a webhook arrives, the edge checks the provider's signature against the raw request body. A forged webhook, even one with a body copied from a real event, gets a 401. A valid one is queued, and the purchase it creates is marked verified.

A purchase becomes verified only after the provider's signature checks out, and refunds travel the same path.
ProviderEvents Leverprice readsHow the provider signs them
Stripecheckout.session.completed, checkout.session.async_payment_succeeded, charge.refundedStripe-Signature: HMAC-SHA256 of the timestamp, a dot and the raw body (Stripe)
Polarorder.paid, order.refundedStandard Webhooks headers webhook-id, webhook-timestamp and webhook-signature (Polar)
Lemon Squeezyorder_created, order_refundedX-Signature: HMAC-SHA256 hex digest of the raw body (Lemon Squeezy)
Dodo Paymentspayment.succeeded, refund.succeededStandard Webhooks: HMAC-SHA256 of the id, the timestamp and the raw body (Dodo Payments)

What the engine learns from depends on the project's revenue mode. In the default, auto, purchases your server reports through the SDK count until a provider is connected, labeled as unverified. From the moment a provider is connected, the engine learns from verified purchases only, and the experiment screen shows whether its revenue is verified. You can also pin the mode to verified or reported.

Which source wins when two disagree about an order?

The provider, always. Three rules decide every conflict:

  1. An unverified event never changes a verified purchase. An SDK report, or a request made with a stolen API key, can't change the amount or the attribution of a purchase the provider has confirmed.
  2. A signed webhook replaces an earlier SDK report. When the provider's event arrives after your server's report, the amount, the currency and the attribution all take the provider's values.
  3. Attribution and money change together. The amount is always stored in the currency of the experiment the purchase belongs to, so moving a purchase to another experiment converts its amount in the same write.

Rule 3 exists because the alternative fails quietly. Example: amounts are stored in minor units, and the yen has none, so ¥4,500 is stored as 4500 (Stripe). If attribution moved to a dollar experiment and the amount stayed, that purchase would be read as $45.00, whatever it was actually worth in dollars.

What arrivesWhat is already storedResult
SDK reportNothingStored as an unverified purchase
Signed webhookUnverified purchaseProvider's amount, currency and attribution replace it; marked verified
SDK reportVerified purchaseChanges nothing
The same signed webhook againVerified purchaseChanges nothing
Unverified refundVerified purchaseKept as a signal, ignored when the total is recomputed
Any refundNothing yetParked until the purchase arrives, for up to 90 days

How does a purchase find the price the buyer saw?

Through signed attribution that rides along with the checkout. Every quote from the SDK carries metadata with four fields: pp_exp (experiment), pp_var (variant), pp_vid (hashed visitor id) and pp_sig, a tag over the other three. You pass it whole into the checkout, and the provider hands it back in the webhook.

app/api/checkout/route.ts
import { leverprice } from "../../../lib/leverprice";
import { stripe } from "../../../lib/stripe";

export async function POST(request: Request) {
  const quote = await leverprice.getPrice("pro", { request });
  const session = await stripe.checkout.sessions.create({
    mode: "payment",
    line_items: [
      {
        quantity: 1,
        price_data: { currency: quote.currency, unit_amount: quote.price, product_data: { name: "Pro" } },
      },
    ],
    metadata: quote.metadata,
    payment_intent_data: { metadata: quote.metadata },
    success_url: "https://example.com/thanks",
    cancel_url: "https://example.com/pricing",
  });
  const response = Response.json({ url: session.url });
  for (const cookie of quote.setCookie) response.headers.append("Set-Cookie", cookie);
  return response;
}

The tag is the first 16 hex characters of an HMAC-SHA256 over pp:attr:v1: followed by the experiment, variant and visitor ids, keyed with your project's assignment key. The prefix keeps this HMAC distinct from the cookie and visitor-id HMACs made with the same key. The key itself is derived on our side from a root secret and your project id, so it is never stored and doesn't change when you rotate API keys. Visitors keep their prices through a key rotation.

A purchase whose tag doesn't verify is still recorded, but it counts toward no variant.

Why sign attribution when the provider already signs the webhook? The provider's signature proves the provider sent the event. It says nothing about where the metadata inside came from. In no-code mode, attribution travels in a checkout link the visitor can edit before paying, and the provider will faithfully sign whatever arrived.

The tag has a limit worth stating. The assignment key reaches your server inside the signed config, so anyone holding your secret API key can compute valid tags. Against key holders, the trust rules above do the work.

How do you avoid counting the same purchase twice?

By making every write idempotent, because nothing in the pipeline promises exactly-once delivery.

A purchase is unique per project, mode, provider and order id. A redelivered webhook, a retried queue message and an SDK report of the same order all land on the same row. Keying on the order id rather than the event id matters here: an SDK report and the provider's webhook for one order have different event ids, but they meet on one row. Standard Webhooks suggests its webhook-id header as an idempotency key (Standard Webhooks), which works within one provider's stream but can't match an event to a report from your server.

Visitors get the same treatment. An exposure, one person seeing an experiment price, is unique per experiment, mode and visitor. The daily counter is incremented in the same transaction and only for visitors who are new, with two set-based SQL statements per batch. Duplicates from the SDK, redelivery and parallel instances can't count a visitor twice.

Idempotency also covers replay. Lemon Squeezy signs the raw body without a timestamp (Lemon Squeezy), so a captured delivery would verify again tomorrow. Replaying order_created for an order we already have changes nothing.

How are refunds counted?

As signals, never as a running subtraction.

Each refund event is stored as its own row, keyed by the purchase and the provider's refund id and marked verified or not. Refund events come in two shapes: a single refund, or a running total. Stripe's charge.refunded carries the charge's amount_refunded, the total refunded so far (Stripe), so the SDK's trackRefund() accepts either a refundId with an amount or a refundedTotal.

The refunded amount is always recomputed from the stored signals. A redelivered refund lands on its existing row, so it can't be subtracted twice. For a verified purchase only verified refunds count, so an unverified refund recorded earlier, for example with a stolen key, stops counting the moment the provider confirms the purchase.

Refunds feed the engine directly. Each visitor ends in one of three outcomes: kept purchase, refunded purchase or no purchase.

A full refund moves the visitor from kept to refunded. Under the revenue goal that outcome is worth nothing; under the profit goal it counts as a loss of the provider fee plus your unit cost, since the model assumes the fee isn't returned. A partial refund lowers the amount and the purchase stays kept.

A refund that arrives before its purchase, or for an order placed before you connected the integration, doesn't fail its batch. It is parked and applied the moment the purchase arrives, or deleted after 90 days if it never does. Exposures and purchases from the same queue message are counted right away.

Two known gaps. Purchases are counted without tax, while Stripe and Dodo refund amounts include it, so a full refund zeroes a purchase exactly but a partial refund is overstated by the tax share. And in the profit model, the fee on a partially refunded purchase is computed from the amount after the refund; if your provider keeps the full fee, profit reads slightly high.

How are test and live purchases kept apart?

By putting the mode into the purchase's unique key. A test purchase and a live purchase are different rows even when they share an order id, so a test key can't touch live sales. If your server reports an order with a test key and the same order later arrives through a live webhook, you get two rows, and only the live one is verified.

Exposures are keyed by mode too, and rate limits are counted separately for live and test traffic, so a leaked test key can't use up the limit your live traffic needs.

What happens when a buyer pays in another currency?

The purchase still counts for the price that buyer saw, converted into the experiment's currency.

An experiment runs in its product's currency. A buyer may still pay in their own: Lemon Squeezy and Dodo can localize the charge, you may sell with multi-currency prices, or your server may report a purchase in local currency.

We take the provider's own conversion first; Lemon Squeezy, for example, reports USD totals, so the amount becomes total_usd - tax_usd. Otherwise we use a reference rate. The original amount and currency are kept alongside, in presentment_amount and presentment_currency.

Stripe Adaptive Pricing needs no conversion. Stripe says the Checkout Session and its PaymentIntent reflect the amount in your integration currency, with the local amount reported separately in presentment_details (Stripe). That is exactly the price the SDK quoted.

Reference rates come from Frankfurter, a free, open-source API covering 219 currencies with rates from 112 central banks and official sources, the ECB among them, and no API key (Frankfurter, providers). The engine stores them in D1 and refreshes them once a day. If a refresh fails, yesterday's rates stay.

The ECB publishes its own euro reference rates around 16:00 CET on working days, for information purposes only (ECB), and that is the role these rates play for us too: accounting, plus the Free plan's $500 monthly limit. No money moves at them.

Refunds arrive in the order's currency and are converted at the same ratio as the purchase itself, so a full refund zeroes it exactly. A refund in a third currency uses the reference rate.

We don't guess. A purchase in a currency we have no rate for is stored without attribution. If there are no rates at all, as in the first minutes after a fresh deploy, the event goes back to the queue and is retried.

What happens when a write fails?

It is retried, then dead-lettered with an alert, then retried again. Nothing is dropped silently.

The engine writes each batch of up to 100 queue messages in one D1 transaction, and an error in one event doesn't fail the others. When D1 itself fails, messages are retried with exponential backoff from 10 seconds up to an hour, for up to 30 attempts, which is about a day. Only then does a message reach the dead-letter queue.

The dead-letter consumer sends an alert first, through a channel that doesn't depend on D1, and only then writes the message to a dead_letters table. If D1 is still down, the message stays in the dead-letter queue with a delay instead of being deleted. Our queues keep messages for 14 days, the longest retention Cloudflare offers (Cloudflare).

Stored dead letters are retried on their own clock, with pauses growing from 5 minutes to 6 hours, so one old permanent error doesn't block newer ones. After 40 attempts a dead letter is marked failed and a second alert goes out. Each project's health check in the dashboard shows whether any of its events are stuck.

What did we choose not to do?

We never ask for provider API keys. The price of that choice is that we can't call your provider's API to fetch an event we missed, so we rely on the provider's retries: up to three days in live mode for Stripe (Stripe), up to 10 retries for Polar (Polar) and up to 8 attempts for Dodo (Dodo Payments). Past that, Stripe's dashboard can resend an event for up to 15 days (Stripe).

We don't count money from sampled data. Cloudflare's Analytics Engine keeps our raw event stream for future reports, but it samples on write and on query (Cloudflare), so purchases and refunds live only in D1.

We don't treat subscription renewals as new purchases. With Polar, the first payment of a subscription counts as the purchase at the price shown, and renewals don't.

A checklist for your own revenue webhooks

  1. Verify the provider's signature on the raw body before parsing anything.
  2. Key purchases by the provider's order id plus live or test mode, not by event id.
  3. Never let an unverified source overwrite a verified one.
  4. Store refunds as signals and recompute totals; park refunds that arrive before their purchase.
  5. Store the amount in the reporting currency next to the original, and change amount and attribution in one write.
  6. Prefer the provider's own conversion, fall back to reference rates, and never guess a currency.
  7. Retry with backoff, alert before you write a dead letter, and keep retrying dead letters on a slower clock.

Our security page lists what else we store and how, and the webhook signature glossary entry covers the signature schemes in general.

Frequently asked questions

Do I have to give Leverprice my Stripe API key?

No. You connect the webhook signing secret, which can confirm events but can't create charges or refunds. Your server keeps creating every checkout with its own keys.

What if I never connect a webhook?

Purchases your server reports with trackPurchase() still count, labeled unverified. When you connect a provider later, the default auto mode switches the engine to verified purchases only.

How soon does a verified purchase affect traffic?

The purchase is stored as soon as the queue delivers it. It starts moving traffic at the next five-minute recompute after its visitor is more than 30 minutes old, because the engine only counts visitors whose cohort has had time to buy.

Can I use a payment provider that isn't on the list?

Only Stripe, Polar, Lemon Squeezy and Dodo Payments can verify revenue. With any other provider, your server can still report purchases through trackPurchase() with the provider set to "other", and they count as unverified.

Can I see which purchases were verified?

Yes. The purchase log in the dashboard flags every purchase as verified or not, and test and live mode have separate logs.