Esc
  • Jump to
  • The board
  • All launchesSort and filter by week or category
  • Open statsEvery number, in public
  • Maker storiesApps that stopped hiding
  • Submit a launch
  • AICategory
  • AnalyticsCategory
  • API & BackendCategory
  • Audio & VoiceCategory
  • AutomationCategory
  • CommunityCategory
↑↓ to move↵ to openPress / anywhere
Sign in

How to Set Up SaaS Payments Without Broken Billing States (2026)

How to wire hosted checkouts, idempotency keys, webhook signature checks, subscription state machines, dunning, refunds, and sandboxes without granting free access or double-charging users.

By Pritam Ghosh, founder of HauntboardUpdated 7 min read

Hosted Checkout and Idempotency Keys

Most early billing bugs happen for two predictable reasons: trusting a browser redirect to grant access, and retrying failed network calls without an idempotency key.

Start with a hosted checkout page (Stripe Checkout, Paddle Checkout, Dodo Checkout, or Polar Checkout) unless you have a strong compliance reason to build custom card forms. Hosted checkouts handle card validation, Apple Pay and Google Pay, 3D Secure challenges, local payment methods, and tax fields without sending raw card numbers through your backend. Create the checkout session on your server using your own database user or workspace ID in the session metadata, never trusting a price ID or customer tier sent blindly from the browser without server validation.

When your server sends mutating POST requests to your billing provider, such as creating a checkout session, customer, or refund, attach an idempotency key. According to Stripe's idempotent requests documentation:

  • Use high-entropy random values: Generate a V4 UUID or random string up to 255 characters long, and never put sensitive data such as email addresses or user names inside the key.
  • Keep parameters identical on retries: Stripe's idempotency layer compares incoming parameters against the first request and returns an error if they differ. In API v1, saved responses are stored for at least 24 hours after execution begins, so a network timeout retry returns the original result instead of creating a duplicate charge or customer.
  • Only attach keys to mutating requests: Send idempotency keys on POST calls, never on GET or DELETE requests, which are already idempotent by definition.

Even before writing code, check how your pricing tiers and fixed fees affect net revenue per order with our payment fee calculator and micro-SaaS pricing guide.

Verifying Webhook Signatures and Deduplicating Events

Never unlock a paid plan inside your /checkout/success redirect route. A user can close their browser tab right after paying, or someone can visit /checkout/success?session_id=... before an asynchronous bank debit clears. Your source of truth must be verified webhooks sent directly from your billing provider to a public HTTPS endpoint on your backend.

Every major provider enforces cryptographic signature verification over the unparsed raw request body. Parsing JSON first and re-stringifying it changes whitespace or key order and breaks verification:

  • Stripe: Read the raw request bytes and pass them alongside the Stripe-Signature header and your endpoint secret to stripe.webhooks.constructEvent(), as documented in Stripe's webhooks guide.
  • Paddle: Read the Paddle-Signature header, extract ts and h1, compute an HMAC-SHA256 digest of ts:rawBody, and check timestamp freshness. Per Paddle's signature verification docs, official Paddle SDKs enforce a five-second timestamp tolerance by default to block replay attacks.
  • Dodo Payments: Dodo Payments webhooks follow the open Standard Webhooks specification and support secret rotation where the previous signing secret remains valid for 24 hours so zero-downtime deploys do not drop events.

Treat webhook delivery as at-least-once and potentially out of order. As Stripe's webhook management docs note, Stripe retries failed deliveries automatically for up to three days. Follow four defensive habits in every handler:

  1. Verify first, parse second: Reject invalid signatures with HTTP 400 immediately.
  2. Store processed event IDs: Insert the provider's unique event ID into a database table with a unique index inside the same transaction as your entitlement update so duplicate deliveries become safe no-ops.
  3. Return HTTP 200 quickly: Acknowledge receipt fast and hand off slow side effects (such as generating PDFs or calling third-party APIs) to a background job so your endpoint never times out.
  4. Fetch fresh state when ordering is ambiguous: When an event arrives out of sequence, query the provider's subscription endpoint (or compare timestamps) rather than blindly overwriting newer local state with an older payload.

Designing Your Subscription State Machine

Treating billing as a single boolean column like isPro: true breaks the moment you add free trials, failed renewals, grace periods, or canceled-at-period-end plans. Store the provider's customer ID, subscription ID, current price/plan ID, currentPeriodEnd timestamp, and explicit status on your workspace or user record.

Look at how Stripe's Subscription object models its eight lifecycle states, and how Paddle's subscription lifecycle events mirror them:

Status What happened App access rule
trialing Customer started a free or carded trial Grant plan features until trial end date; prompt for payment method if missing
active Initial invoice or renewal payment succeeded Full access to subscribed tier limits and seats
incomplete / incomplete_expired Initial checkout needs payment or 3DS; expires after 23 hours unpaid on Stripe Do not grant paid access; prompt user to complete payment or start a fresh checkout
past_due Renewal payment failed; provider is retrying or awaiting card update Keep workspace readable during your grace window and show a billing portal banner
paused Trial ended without a card or subscription was paused explicitly Freeze paid features while preserving stored data and configuration
canceled / unpaid User canceled (at period end) or all dunning retries exhausted Keep access until currentPeriodEnd on voluntary cancel, then downgrade to free or read-only

Always tie feature gating to a helper like hasPaidAccess(subscription) that checks status === "active" || status === "trialing" || status === "past_due" (during your grace window), combined with currentPeriodEnd. Listen to Stripe's subscription webhook events (customer.subscription.created, updated, deleted, paused, resumed, plus invoice.paid and invoice.payment_failed) so upgrades, downgrades, and customer-portal cancellations sync automatically.

Failed Payments, Dunning, and Clean Refunds

Once recurring billing runs in production, expired cards and bank soft declines quietly create involuntary churn. Configure your billing provider's built-in dunning before writing custom retry scripts.

Per Stripe's Smart Retries documentation, Smart Retries is enabled by default for new Stripe accounts and schedules retries dynamically based on timing signals. Keep two important exclusions in mind from Stripe's docs: Stripe does not automatically retry when no payment method exists, when the issuer returns a hard decline code, on India-issued cards, or on unsupported local methods such as Cash App Pay or Amazon Pay. Also remember Stripe's payment method priority order: if a subscription has its own default_payment_method, updating only the customer-level default will not update retries on that subscription unless you update the subscription or link customers through the Billing Portal.

Pair automated retries with clear customer notifications (you can adapt our failed payment dunning email template) and a one-click Billing Portal link. For deeper recovery tactics, see our guide on reducing SaaS churn.

Wire refund webhooks at the same time you build checkout. According to Stripe's refunds documentation, refunds return only to the original payment method, original processing fees are not returned, and if your available Stripe balance is too low to cover a card refund, Stripe holds the refund as pending for up to 45 days before failing with insufficient_funds. Handle charge.refunded (Stripe), adjustment.updated (Paddle), or refund events on Dodo and Polar so full refunds revoke seats or credits cleanly while partial refunds leave the account intact.

Testing Webhooks and Edge Cases in Sandboxes

Do not ship payments after testing only one happy-path card payment. Every provider gives you an isolated sandbox (Stripe test mode with Stripe CLI forwarding to localhost, Paddle Sandbox, Dodo test mode, and Polar's sandbox.polar.sh) where no real money moves.

Run through this pre-launch verification checklist in test mode before flipping to live API keys:

  1. Duplicate webhook delivery: Replay the exact same checkout-completed event twice and verify your database creates one subscription, one invoice row, and one credit grant.
  2. Invalid signature check: Send a modified JSON body with an old signature header and confirm your endpoint returns HTTP 400 without touching user state.
  3. 3D Secure / incomplete checkout: Trigger a test card requiring authentication, abandon the modal, and confirm the user stays on the free tier.
  4. Failed renewal and recovery: Simulate an invoice.payment_failed event followed by invoice.paid to verify your in-app warning banner appears and disappears automatically.
  5. Plan upgrade, downgrade, and cancel at period end: Confirm prorations, seat limits, and access expiration timestamps update accurately without locking out a customer who paid through month-end.

Finally, keep separate environment variables for test and live webhook secrets and product IDs, and verify that live product IDs in production point to real prices rather than sandbox placeholders.

Frequently Asked Questions

Should I grant paid access on the checkout success redirect URL?

No. Browser redirects can fail if a user closes the tab early, and asynchronous bank payments confirm later. Only provision paid entitlements after verifying a signed webhook from your payment provider (or safely polling your own server after the webhook updates your database).

What should my webhook handler return if my database is temporarily down?

Return an HTTP 500 error rather than HTTP 200. Returning 200 tells Stripe, Paddle, or Dodo that your server processed the event successfully, stopping automatic retries. Returning 5xx triggers exponential backoff retries so you do not silently lose paid signups.

Do I need separate webhook endpoints for dev, staging, and production?

Yes. Each environment should have its own endpoint URL and its own signing secret stored in environment variables. Using the Stripe CLI or provider replay tools locally prevents test events from polluting staging or production databases.

How long should I keep a customer's workspace active during past_due retries?

Most SaaS teams keep workspace access open for the duration of their dunning window (typically 7 to 14 days) while displaying a clear banner linking to the billing portal. Locking out a paying customer immediately on a single soft bank decline turns recoverable card hiccups into angry cancellations.

Share

in

Pritam Ghosh runs Hauntboard and writes these guides.

Published · Updated

Got no audience? Start here.

A person reviews every launch, and every view and visit it gets is public. Launching is free.

Launch free →

Keep reading

All guides →

On the board

All →

Still hiding your app?

Put it on the board. Reviewed by a person, free to launch.

Launch free
Submit a launch