Blog | How to Build a Subscription SaaS with Stripe (AI Tutorial) | 07 Jun, 2026

How to Build a Subscription SaaS with Stripe (AI Tutorial)

Build subscription SaaS with Stripe — products, prices, webhooks, billing portal, entitlements

Building a subscription SaaS with Stripe via AI app builders is approachable in a weekend if you understand the core pieces — Products and Prices in Stripe, the Customer-Subscription relationship, webhooks for state syncing, the billing portal for self-service, and the entitlement logic that gates features by plan. Modern AI app builders handle the bulk of the integration; the discipline is in webhook handling, plan changes, dunning, and the operational pieces that determine whether your billing scales cleanly or causes 3 AM support tickets. This guide covers the full build with exact prompts and the patterns that work.

Stripe is the default payment infrastructure for indie SaaS in 2026. Subscription billing, one-time charges, metered usage, marketplace payments, tax calculation — Stripe handles all of it with mature APIs that AI app builders integrate cleanly. The basic integration takes 30 minutes; the production-ready version takes 4–8 hours. The gap between the two determines whether your billing scales without 3 AM support tickets.

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Stripe Vocabulary You Actually Need

ConceptWhat It IsWhy It Matters
ProductWhat you sell (e.g., 'Pro Plan')Top-level container for pricing options
PriceSpecific cost for a product (monthly, annual, tier)Different prices for the same product (e.g., monthly vs annual)
CustomerPerson or business paying youStripe's record of a paying user
SubscriptionRecurring billing relationshipActive subscription = active access
Subscription ItemSpecific Price within a subscriptionUsed for tiered or per-seat billing
InvoiceBill issued to a customerAuto-generated by subscriptions
Payment MethodHow customer pays (card, ACH, etc.)Attached to Customer; used for subscriptions
Checkout SessionHosted checkout page Stripe providesEasiest way to take initial payment
Billing PortalHosted self-service portalCustomers manage their own subscriptions
WebhookStripe-to-your-app notificationSync subscription state to your database

The Integration Architecture

Three things you store in your database: stripe_customer_id on the User table (links your user to Stripe Customer), subscription state on the User table or separate Subscription table (plan, status, current period end), and Stripe price IDs in environment config or a Plans table (links your plan tiers to specific Stripe Prices).

Five flows you build: sign-up flow (user creates account; you create Stripe Customer; store the Customer ID), checkout flow (user selects a plan; you create Checkout Session; redirect to Stripe; redirect back on completion), webhook handler (Stripe events update your database), billing portal flow (user manages own subscription via Stripe-hosted portal), and entitlement check (backend checks active subscription status before serving paid features).

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Step 1: Stripe Account Setup

  • Create Stripe account at stripe.com — Personal account is fine to start
  • Activate account for live mode (requires business info, bank account, tax ID)
  • Stay in test mode during development — Test cards (4242 4242 4242 4242) work without real charges
  • Get API keys: Settings → Developers → API keys → Test mode shows test keys; switch to Live mode for production keys
  • Two key types: Publishable key (frontend; safe to expose) and Secret key (backend only; never expose)

Step 2: Create Products and Prices in Stripe

  • Stripe Dashboard → Products → Add product
  • Create one Product per plan tier (e.g., 'Pro Plan', 'Team Plan')
  • Add Prices to each Product — typically monthly and annual prices
  • Note the Price IDs (start with 'price_') — these go in your code
  • Optional: add lookup keys to Prices for cleaner references (e.g., 'pro_monthly', 'pro_annual')

Pricing Model Patterns

  • Tiered subscription — Free / Pro / Team / Enterprise. Most common.
  • Per-seat (Per-user) — Charged per active user (Slack-style)
  • Per-feature — Base plan + add-ons for specific features
  • Usage-based — Charge based on usage (API calls, storage, etc.)
  • Hybrid — Base subscription + usage-based overages
  • Annual discount — 15–20% discount for annual prepay

Step 3: The Integration Prompt

Tell your AI app builder: "Integrate Stripe Subscriptions. Add stripe_customer_id to the User table. On user signup, create a Stripe Customer and store the ID. Build a pricing page showing Free, Pro ($X/mo), and Team ($Y/mo) tiers. On Pro/Team selection, create a Stripe Checkout Session and redirect to Stripe; redirect back to /billing/success on completion. Add a webhook handler at /api/webhooks/stripe that processes customer.subscription.created, customer.subscription.updated, customer.subscription.deleted, and invoice.payment_failed events."

What the AI builder typically generates: database schema additions (stripe_customer_id, subscription_status, plan, current_period_end), server function createCheckoutSession(userId, priceId), pricing page UI with plan selection, webhook endpoint at /api/webhooks/stripe, webhook signature verification, and event handlers for the four critical events.

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Step 4: Webhooks — The Most Important Part

Webhooks are how Stripe tells your app what happened. Stripe is the source of truth for subscription state; your database is a mirror. Webhooks keep them in sync. Get webhooks wrong and your app shows stale subscription state — users who paid see they don't have access; users who cancelled still have access.

Critical Webhook Events to Handle

  • customer.subscription.created — New subscription; update user's plan and status to 'active'
  • customer.subscription.updated — Plan change, cancellation scheduled; update accordingly
  • customer.subscription.deleted — Subscription ended; set status to 'cancelled' and downgrade user to free
  • invoice.payment_failed — Payment failed; flag user for dunning; consider grace period before downgrading
  • invoice.paid — Successful payment; nothing usually needed (subscription.updated handles state)
  • customer.subscription.trial_will_end — 3 days before trial ends; trigger email reminder

Webhook Security: Signature Verification

  • Stripe signs every webhook with your endpoint's signing secret
  • Your webhook handler must verify the signature before processing the event
  • Without verification, anyone can POST fake events to your endpoint
  • Stripe SDK has a verifyWebhookSignature function; use it on every webhook

Webhook Testing During Development

  • Stripe CLI — Forwards live webhook events to your localhost during development
  • Command: stripe listen --forward-to localhost:3000/api/webhooks/stripe
  • Triggers test events: stripe trigger customer.subscription.created
  • Essential for local development; production webhooks point to your live domain

Step 5: The Billing Portal

Stripe Customer Portal is hosted by Stripe. Customers update payment methods, change plans, view invoices, and cancel subscriptions there. Building this yourself takes weeks; Stripe gives it to you free.

  • Stripe Dashboard → Settings → Billing → Customer portal → Configure
  • Choose what customers can do: update payment, change plan, cancel, view invoices
  • Choose which plans are upgradeable/downgradeable through the portal
  • Customize branding (logo, colors)

Integration prompt: Tell your AI app builder: "Add a Manage Billing button on the user account page. On click, create a Customer Portal Session via Stripe API and redirect to the URL it returns. After the customer finishes in the portal, they'll be redirected back to /billing."

Step 6: Entitlement Logic

Entitlements are the rules that determine which features each user has access to based on their plan. The pattern: check subscription_status and plan on every paid feature.

Backend Entitlement Checks

  • Every paid API endpoint checks the user's plan
  • Pattern: const user = await getUser(req); if (user.plan !== 'pro' && user.plan !== 'team') return 403
  • Centralize the check in a hasAccess(user, feature) helper
  • Don't trust the frontend — backend is the gate

Frontend Entitlement Display

  • Frontend shows/hides paid features based on plan
  • Locked features show upgrade prompts (not error messages)
  • Pricing page hosts the upgrade CTA
  • But: frontend isn't security; backend enforces

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Step 7: Plan Changes (Upgrade, Downgrade, Cancellation)

Upgrade Flow

  • Customer selects higher tier in your app or in the billing portal
  • Stripe upgrades immediately; charges prorated difference for current period
  • customer.subscription.updated webhook fires; your app updates the user's plan
  • User has access to new tier features immediately

Downgrade Flow

  • Customer selects lower tier in billing portal
  • Stripe downgrades; typically takes effect at end of current period
  • Until period ends, user retains old tier access
  • At period end, subscription updates and downgrade applies

Cancellation Flow

  • Customer cancels in billing portal
  • Stripe schedules cancellation at end of current period
  • customer.subscription.updated fires with cancel_at_period_end = true
  • At period end, customer.subscription.deleted fires; your app downgrades to free
  • Show banner during cancellation period explaining when access ends

Step 8: Dunning — Handling Failed Payments

Dunning is the process of retrying failed payments and notifying customers. Stripe handles most of this automatically with Smart Retries, but you build the integration logic.

  • Enable Smart Retries in Stripe Dashboard → Settings → Billing → Subscriptions
  • Stripe retries failed payments multiple times over 2 weeks with optimal timing
  • On each failure, invoice.payment_failed fires — send email to customer
  • After max retries, customer.subscription.deleted fires — user downgrades
  • Email patterns: 1st failure ('Your payment failed, update card'), 2nd failure ('Final reminder'), cancellation ('Your subscription was cancelled')

Step 9: Tax Handling

Tax on SaaS subscriptions varies by jurisdiction. Stripe Tax handles most of the complexity if you enable it.

  • Stripe Tax — Auto-calculates tax based on customer location
  • Activate at Settings → Tax → Get started
  • Costs 0.5% of revenue where tax is collected
  • Handles US sales tax, EU VAT, UK VAT, GST in various countries
  • Reverse charge for B2B EU customers handled automatically
  • Tax registration in jurisdictions still required (varies by tax nexus)
  • Consult tax counsel for specific obligations

Step 10: Operational Patterns That Scale

Sync Drift Recovery

  • Webhooks fail occasionally — network issues, app downtime, code bugs
  • Build a reconciliation job that syncs Stripe state to your database periodically
  • Run nightly: fetch each customer's subscriptions from Stripe; compare to your database; fix mismatches
  • Critical for keeping state accurate over time

Idempotency

  • Webhooks can fire multiple times for the same event
  • Your handlers must be idempotent — processing the same event twice should produce the same result
  • Track processed event IDs; skip if already processed
  • Avoid side effects that compound (e.g., 'increment credit by 100' is dangerous; 'set credit to plan default' is safe)

Logging and Monitoring

  • Log every webhook received with timestamp and event ID
  • Log every Stripe API call with response status
  • Monitor for unusual patterns — sudden spike in subscription.deleted events
  • Alert on payment_failed rate exceeding baseline

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

AI-Specific Subscription Patterns

For SaaS with AI features (chatbots, generation, AI agents), subscription billing needs to account for AI cost variance.

  • Token quotas per plan tier — Free: 10K tokens/month, Pro: 100K, Team: unlimited (with fair use)
  • Track per-user AI usage; warn at 80% of quota
  • Overage billing — Charge for usage beyond quota; or simply pause AI features at quota
  • Plan unit economics around AI cost ratio — AI cost should be 5–20% of revenue

Pricing Strategy That Actually Works

  • Free tier — Useful but limited; converts to paid as usage grows
  • Pro tier — $15–$50/month — Solo users and small teams
  • Team tier — $30–$200/month — Multi-seat for collaboration
  • Enterprise — Custom — Larger orgs with specific needs
  • Annual discount — 15–20% off — Increases LTV and reduces churn
  • Anchor pricing — Show Team plan first; Pro looks reasonable by comparison
  • Don't underprice — Real value commands real prices; $5/month SaaS is hard to make work

Common Mistakes Building Subscription SaaS with Stripe

  • Skipping webhook signature verification — Without it, anyone can POST fake events to your endpoint.
  • Trusting frontend for entitlements — Frontend can be manipulated. Backend enforces.
  • Not handling failed payments — Dunning is real. Customers fail payments; you lose revenue silently without proper handling.
  • Hardcoding price IDs in code — Use environment variables or a Plans table; price IDs change as you experiment with pricing.
  • Forgetting test mode vs live mode — Webhook secrets, API keys, customer data all differ. Keep environments cleanly separated.
  • Skipping the billing portal — Building self-service billing yourself takes weeks. The portal is free; use it.
  • Not building reconciliation jobs — Webhooks fail occasionally. Nightly sync from Stripe catches drift.
  • Ignoring idempotency — Webhooks can fire multiple times. Handlers must be idempotent.
  • Mishandling plan changes — Upgrade prorations and downgrade timing have nuances. Test thoroughly before launch.
  • Forgetting tax — Tax varies by jurisdiction. Stripe Tax simplifies; consult counsel for nexus obligations.

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Frequently Asked Questions

How long does the full Stripe integration take?

Basic integration via AI app builder: 30 minutes. Production-ready with webhooks, billing portal, dunning, entitlements: 4–8 hours. Worth doing properly; cleanup later is more expensive than building correctly upfront.

Should I use Stripe Checkout or build custom checkout UI?

Stripe Checkout for almost everything. It's PCI-compliant, mobile-optimized, handles 3D Secure automatically, supports Apple Pay/Google Pay/PayPal. Custom checkout only when you have specific reasons (which most SaaS don't).

What about Stripe alternatives (Paddle, Lemonsqueezy, Chargebee)?

Paddle and Lemonsqueezy handle sales tax as Merchant of Record — useful if you want to skip your own tax compliance. Chargebee adds advanced subscription management. For most indie SaaS, Stripe + Stripe Tax is the simplest path. Paddle/Lemonsqueezy are reasonable choices if tax MoR matters.

How do I handle annual contracts with custom pricing?

Stripe Subscriptions support annual prices. For custom enterprise contracts, use Stripe Invoicing — send invoices manually with custom terms; payment marks invoice paid. Subscriptions for self-service tiers; Invoicing for enterprise.

What about metered/usage-based billing?

Stripe supports it via Subscription Items with usage-based pricing. Report usage to Stripe via API; Stripe handles invoice generation. More complex than flat-rate; only do when business model truly demands it.

How do I implement free trials?

Subscription with trial_period_days. Customer enters payment method upfront; isn't charged until trial ends. Trial subscriptions still create subscription objects; check trial_end to know when trial ends. Alternative: free tier with upgrade path (no payment method required upfront).

How do I handle refunds?

Stripe Dashboard → Payments → Find payment → Refund. Partial or full refund supported. For subscription refunds, also cancel the subscription if appropriate. Set clear refund policy in your terms before customers ask.

Building a subscription SaaS with Stripe via AI app builders is approachable in a weekend if you understand the core pieces — Products and Prices, Customers and Subscriptions, webhooks, billing portal, entitlements. The 30-minute basic integration is easy. The 4–8 hour production-ready integration is where unit economics live. Don't skip the dunning, reconciliation, and operational discipline. Webhooks are the most important part. Stripe is the source of truth; your database is a mirror. The billing portal saves weeks of work — use it, customize the branding, let customers self-serve subscription changes.

Got an idea? Build it now!
Just start with a simple Prompt

Get Started Today

left-gradient
left-gradient

Ready to be a
10x Marketer?

See it in action

left-gradient
left-gradient
Questera Logo
SOC 2 Type II Cert.
SOC 2 Type II Cert.
AI Security Framework
AI Security Framework
Enterprise Encryption
Enterprise Encryption
Security Monitoring
Security Monitoring

Subscribe for weekly valuable resources.

Please enter a valid email address

© 2026 Questera