No. 08SaaS7 min read1,926 words
Implementing subscription billing: for SaaS the right way
How to implement SaaS subscription billing: Stripe vs merchant of record, webhooks, proration, dunning, tax, testing, and a realistic timeline for the build.
- Written by
- Lazy Devs
- Published
- Updated
- Sources
- Cited inline

Key takeaways · 05
The short version
- 01Buy the parts that touch money (checkout, card storage, retries, invoices) from a billing provider and build only the glue: your own subscription table, entitlements and webhook handlers.
- 02Choose between Stripe and a merchant of record (Paddle, Lemon Squeezy) based on tax exposure first: with Stripe you remain responsible for registering, collecting and filing sales tax and VAT; a merchant of record takes that on for a higher fee.
- 03Webhook handlers must verify the signature, be idempotent on the event ID, and tolerate out-of-order delivery, because Stripe can send the same event more than once and does not guarantee order.
- 04Turn on automatic payment retries and reminder emails early. Stripe recommends Smart Retries, with a default of 8 attempts within 2 weeks.
- 05A basic subscription billing build (one or two plans, hosted checkout and portal, webhooks, dunning) is roughly two to four weeks of focused work once pricing is settled; unsettled pricing is what blows up estimates.
On this page · 10
To implement subscription billing well, let a billing provider handle everything that touches money (checkout, card storage, charging, retries, invoices) and build only the glue yourself: a subscription table in your own database, kept in sync by idempotent webhook handlers, plus the entitlement logic that decides what each customer can use. The happy path takes an afternoon. Proration, failed payments, plan changes, tax, refunds and invoices an accountant will accept are where teams quietly lose a month. This guide is about scoping that work honestly.
Do not build the money parts yourself
The most important decision is to use a billing provider for anything involving card data and charging. Hosted checkout pages keep raw card numbers off your servers, which keeps most of the PCI DSS burden with the provider. If anyone proposes handling card numbers in-house for a typical SaaS, treat it as a red flag.
The real choice is which kind of provider.
Stripe versus a merchant of record
With Stripe Billing, you are the merchant. You collect the payment, and you are responsible for registering, collecting and filing sales tax and VAT wherever you have obligations. Stripe Tax calculates and collects the right amounts and tracks where you may need to register, but filing and remitting remain your responsibility, either yourself or through a partner.
With a merchant of record such as Paddle or Lemon Squeezy, the provider is the legal seller. It calculates, collects and remits tax globally, handles the invoices, and pays you out as a single customer. In exchange, you pay a higher percentage per transaction than Stripe's standard card pricing and give up some flexibility in checkout and billing logic. Compare the current Stripe pricing page with your merchant of record's published fees before deciding.
| Stripe Billing | Merchant of record (Paddle, Lemon Squeezy) | |
|---|---|---|
| Who is the seller | You | The provider |
| Sales tax and VAT | You register, collect and file (Stripe Tax helps calculate and collect) | Provider handles calculation, collection and filing |
| Fees | Lower per-transaction cost | Higher, includes tax and compliance handling |
| Flexibility | High: custom flows, enterprise invoicing, usage pricing | More constrained checkout and billing models |
| Best for | Mostly domestic sales, custom billing, enterprise contracts | Small teams selling internationally from day one |
Our rule of thumb: if you are a small team selling into many countries and do not want to own tax compliance, start with a merchant of record. If you are mostly domestic, need custom logic or will negotiate enterprise contracts, Stripe gives you more room. Either way, decide on day one; moving from one model to the other later is a real migration.
This is engineering guidance, not tax or legal advice. Confirm your obligations with an accountant who knows your markets.
The data model you own
The provider is the system of record for payments. Your database should still mirror the parts your app needs, so you are not calling the provider on every page load and you keep working when it is slow.
- Billing customer: the provider's customer ID, stored on your tenant or account (in B2B, the organization pays, not the user).
- Subscription: status (
trialing,active,past_due,canceledand so on), current plan and price IDs, quantity, current period end, and whether it cancels at period end. - Entitlements: what the account can actually use (seats, projects, features), derived from the plan, with explicit overrides for special deals.
- Processed events: the IDs of every webhook event you have handled, for idempotency.
Your app checks entitlements, never plan names. "Can this account create another project?" should be one function, not a comparison against "pro" scattered through the codebase. When pricing changes, and it will, you change the plan-to-entitlement mapping in one place.
Webhooks: the part everyone gets wrong
The provider charges the card; your app learns what happened through webhooks: customer.subscription.updated, invoice.paid, invoice.payment_failed and so on. Stripe's documentation is clear about three behaviours you must design for: events can be delivered more than once, they are not guaranteed to arrive in order, and failed deliveries are retried for up to three days in live mode.
That means every handler must:
- Verify the signature using the raw request body, so nobody can forge an event.
- Be idempotent, recording the event ID so a redelivery does nothing.
- Not trust ordering, re-reading the latest object from the API when state matters.
- Return quickly, pushing slow work to a background job.
Here is a Next.js route handler that does all four. The unique constraint on the event ID does the idempotency work inside the same transaction as the update, so there is no race between "have we seen this?" and "record that we saw it."
// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { db } from "@/lib/db";
import { syncSubscription, markPastDue } from "@/lib/billing";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(request: Request) {
const body = await request.text(); // the raw body is required for signature checks
const signature = request.headers.get("stripe-signature");
if (!signature) return new Response("Missing signature", { status: 400 });
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!,
);
} catch {
return new Response("Invalid signature", { status: 400 });
}
// Events can arrive out of order, so fetch the latest subscription state
// instead of trusting the snapshot inside the event.
let latest: Stripe.Subscription | null = null;
if (event.type.startsWith("customer.subscription.")) {
const { id } = event.data.object as Stripe.Subscription;
latest = await stripe.subscriptions.retrieve(id);
}
await db.transaction(async (tx) => {
// Primary key on id: a redelivered event inserts nothing and we stop.
const inserted = await tx.query(
"insert into stripe_events (id, type) values ($1, $2) on conflict (id) do nothing returning id",
[event.id, event.type],
);
if (inserted.rowCount === 0) return;
if (latest) await syncSubscription(tx, latest);
if (event.type === "invoice.payment_failed") {
await markPastDue(tx, event.data.object as Stripe.Invoice);
}
});
return new Response(null, { status: 200 });
}Missing idempotency is one of the billing bugs we see most often when we take over an existing codebase: customers upgraded twice, emailed twice or provisioned twice because a webhook was redelivered. Our guide to webhooks done right covers the general pattern.
Plan changes and proration
When someone moves from a small plan to a bigger one on day 12 of a 30-day cycle, what do they pay today? Proration answers that. Stripe computes the numbers; you decide the policy, which it exposes through proration_behavior:
create_prorations(the default): credit and charge adjustments are added to the next invoice.always_invoice: the adjustment is invoiced and charged immediately.none: no adjustment; the new price applies from the next period.
A common, defensible policy is: upgrades take effect immediately and are charged now, downgrades take effect at the end of the current period, and annual plans upgrade with proration but never refund on downgrade. These are product decisions, not engineering ones. Get them in writing before anyone codes, because they also shape your plan-change UI and your support macros.
Access rules, trials and the boring correctness work
Trials, cancellations and access
Decide each of these explicitly:
- Trials: card upfront or not? Card-upfront trials convert differently from no-card trials, and the right choice depends on your sales motion. Stripe supports both, including what happens when a trial ends without a payment method.
- Cancellation: immediately, or at the end of the paid period? Most SaaS products cancel at period end so customers keep what they paid for.
- Past due: does a customer with a failed payment keep full access, drop to read-only, or lose access after a grace period?
- Data after cancellation: how long do you keep it, and can a returning customer pick up where they left off?
Invoices, receipts and the customer portal
Invoices that match what was actually charged. Receipts. A way for customers to update their card, download invoices and see their history: Stripe's hosted customer portal saves days here, and it pairs well with your own customer portal for everything else. Refunds and credits. Cancellation that revokes access at the right moment. None of it is glamorous, and all of it generates support tickets when it is wrong.
Failed payments and dunning
Cards expire, banks decline and limits get hit. Recovering those payments is called dunning, and it is usually the highest-value hour in the whole billing project. Stripe recommends Smart Retries, which picks retry times automatically, with a recommended default of 8 attempts within 2 weeks. Pair it with reminder emails, an in-app banner for admins, and a hosted page where the customer can update their card.
Do not leave this until after launch. Every failed renewal you do not retry is revenue you already earned and then gave up.
Testing billing without waiting a month
Billing bugs hide in time: renewals, trial endings, retries, period boundaries. Stripe's test clocks let you advance a test customer's time to trigger those events in minutes. Before launch, script these scenarios and run them end to end:
- New signup on each plan, monthly and annual.
- Upgrade and downgrade mid-cycle.
- Trial ending with and without a card.
- Failed renewal, retries, then recovery after a card update.
- Failed renewal that never recovers, ending in cancellation.
- Cancel at period end, then reactivate before the period ends.
- A duplicate webhook delivery for each event type you handle.
If a vendor cannot show you renewals being tested without waiting a month, push back.
Realistic timeline and budget
These are our rough planning ranges, not quotes.
| Scope | What is included | Rough effort |
|---|---|---|
| Basic subscriptions | One or two flat plans, monthly and annual, hosted checkout and portal, webhooks, entitlements, dunning | 2 to 4 weeks |
| Plus seats and trials | Per-seat quantities synced from team membership, trials, coupons | Add 1 to 2 weeks |
| Plus usage-based pricing | Metering pipeline, aggregation, reconciliation, usage visibility | Can double the timeline |
| Plus enterprise | Invoiced customers on payment terms, custom contracts, multiple currencies | Scoped per contract |
The thing that blows up estimates is not code. It is unsettled pricing. If the plan structure changes halfway through, the billing logic changes with it. Lock the pricing model before the build starts, or agree that changes mid-build reset the clock. If you are heading toward per-unit pricing, read usage-based billing for SaaS before you commit.
What to watch out for
- Testing in production by accident. Keep test and live keys, webhooks and products strictly separate.
- No reconciliation. On a schedule, compare what the provider charged with what your database believes. Drift between the two is how money goes quietly missing.
- Treating tax as an afterthought. Decide your merchant-of-record stance on day one.
- Hardcoded price IDs. Prices change. Keep plan and price IDs in configuration.
- Seat drift. In B2B, derive the billed quantity from active memberships, as we describe in how to build a multi-tenant SaaS.
The short version
Buy the money parts, build the glue. Pick your provider based on tax exposure, not only fees. Settle pricing before anyone writes code, make webhook handlers verified and idempotent, mirror state into your own database, gate features on entitlements, and turn on dunning early. Do those things and subscription billing becomes a predictable project instead of an open-ended one. The same rules apply to membership sites and online course platforms, where billing is the business model.
We build billing as part of our Stripe integration work, from first checkout to usage-based and enterprise pricing. If you want a second pair of eyes on your billing plan before you commit, tell us how you want to charge.
FAQ · 06 questions
Frequently asked questions
Should I use Stripe or Paddle for SaaS subscriptions?
Use Stripe if you mainly sell domestically, need flexible billing logic or expect enterprise contracts, and are prepared to handle tax registration and filing. Use a merchant of record such as Paddle or Lemon Squeezy if you are a small team selling into many countries and want someone else to own global sales tax and VAT, accepting a higher fee and less flexibility.
How do I handle failed subscription payments?
Turn on your provider's automatic retries and reminder emails, decide what access a customer keeps while a payment is past due, and let customers update their card through a hosted portal. Listen for the invoice.payment_failed event to update your own records and show an in-app banner. Most failed payments are recoverable if you retry and tell the customer.
What is proration in subscription billing?
Proration is the adjustment made when a customer changes plans partway through a billing period: they get credit for unused time on the old plan and are charged for the remaining time on the new one. Stripe calculates it for you; your job is to decide the policy, such as charging upgrades immediately and applying downgrades at the end of the period.
Do I need to store credit card numbers to run subscriptions?
No, and you should not. Hosted checkout pages and payment elements from providers like Stripe collect card details directly, so raw card numbers never touch your servers. That keeps most of the PCI DSS burden with the provider; you store only the provider's customer and subscription IDs.
How do I test subscription renewals without waiting a month?
Use your provider's test mode and simulation tools. Stripe's test clocks let you move a test customer's time forward to trigger renewals, trial endings, failed payments and cancellations in minutes, so you can test a year of billing events in an afternoon.
How long does it take to build subscription billing?
A basic version with one or two flat plans, monthly and annual billing, hosted checkout, a hosted customer portal, webhooks syncing to your database and dunning switched on is typically two to four weeks of focused work. Usage-based pricing, multiple currencies, coupons and enterprise invoicing each add meaningful time.