Stripe Billing subscriptions with Checkout and the customer portal
Sell recurring plans with Stripe: Products and Prices, a subscription-mode Checkout Session, the hosted customer portal, and webhook-driven provisioning on checkout.session.completed, invoice.paid and customer.subscription.* events.
- Provider
- Stripe
- Level
- Intermediate
- Stacks
- Node.js (Express), Python (Django), React
- Code maturity
- Sandbox-ready
- Last verified
- 25 Nov 2026
Introduction
Stripe Billing handles recurring charges: it creates an invoice every billing period, tries to collect it, retries failed payments and keeps a Subscription object in sync. The fastest way to sell a plan is a Checkout Session in subscription mode: Stripe hosts the payment page, collects the card (or another supported method), creates the Customer and Subscription, and redirects back to you.
This guide builds the full loop in a sandbox: define Products and Prices, start subscription Checkout, provision access from webhooks (not from the redirect), let customers manage plans in the customer portal, and handle renewals and failed payments.
Tip: If you have not built a one-off Stripe Checkout integration yet, read the stripe-checkout-webhooks guide first; this guide reuses its webhook signature pattern.
What Billing + Checkout does
- Product = what you sell ("Pro plan"). Price = how much and how often (e.g. 1500 cents USD per month). One Product can have many Prices (monthly, yearly, per currency).
- Checkout Session (
mode: "subscription") collects payment details and creates a Customer and a Subscription for the Price you pass inline_items. - Each billing period Stripe creates an Invoice and charges it. Success sends
invoice.paid; failure sendsinvoice.payment_failed. - The customer portal is a Stripe-hosted page where customers update payment methods, switch plans, view invoices or cancel, depending on the portal configuration you choose.
- Your server listens to webhooks and keeps a local
subscriptionstable that answers one question: *does this user have access right now?*
Countries and currencies
Stripe accounts can be opened in the countries listed on Stripe's global availability page, and Billing works for accounts in those countries. Customers can usually pay from anywhere their card works. Supported currencies and per-currency minimum charge amounts are listed in Stripe's currency docs.
Country lists change; check Stripe global availability before promising a market. This guide does not list countries to avoid stale data.
Payment methods
Subscription Checkout supports cards and wallets plus a set of methods that can be reused for recurring charges (for example SEPA Direct Debit, ACH Direct Debit, Bacs). Which methods appear is controlled by your payment method settings in the Dashboard and by the currency and customer location.
Methods with delayed confirmation (bank debits) mean checkout.session.completed can arrive before the money does — provision from invoice.paid or a subscription status of active, not from the session alone.
When to use this approach
- SaaS plans (monthly/yearly), memberships, paid newsletters, seat-based plans.
- You want Stripe to handle invoices, proration, retries and dunning emails.
- You want a hosted payment page and a hosted self-service portal instead of building billing UI.
When not to use it
- One-off purchases: use Checkout in
paymentmode (see the Stripe Checkout guide). - You need a merchant of record that also files sales tax/VAT for you in many countries — Stripe Billing leaves tax liability with you (Stripe Tax can calculate it, but you remain the seller). Consider a merchant-of-record provider.
- Your customers mostly pay with methods Stripe does not support in their country (e.g. local mobile money); use a regional provider.
Example scenarios
- Indie SaaS: two Prices (Pro monthly, Pro yearly), a pricing page with two buttons, portal for upgrades and cancellations.
- Team plan: one Price with
quantity= seats; the portal (if enabled) lets admins change quantity. - Free trial:
subscription_data.trial_period_dayson the Checkout Session; listen forcustomer.subscription.trial_will_end(sent 3 days before the trial ends) to remind users.
Registration
Create a Stripe account at dashboard.stripe.com/register. You can build and test entirely in a sandbox (test mode) without activating the account. To accept live payments you activate the account with business details, a bank account for payouts and identity verification, as required in your country.
Sandbox and test mode
Sandboxes are isolated test environments: test API keys, test webhook endpoints and test data never touch live money. Use the Stripe CLI (stripe listen) to forward webhook events to localhost.
Test clocks let you advance simulated time in a sandbox to see renewals, trial endings and failed renewals without waiting a month. You can create them in the Dashboard or via the API.
Credentials you need
- Secret key (
sk_test_...): server-only. Never ship it to a browser or mobile app. - Publishable key (
pk_test_...): only needed if you embed Stripe.js. With a redirect to hosted Checkout you can skip it entirely. - Webhook signing secret (
whsec_...): one per endpoint. The secret printed bystripe listendiffers from the Dashboard endpoint's secret. - Price IDs (
price_...): created in the Dashboard or API; store them in config, not in the browser (the browser sends a plan *name*, your server maps it to a Price ID).
Security: Prefer restricted API keys for services that only need part of the API. Rotate keys if they are ever committed to git or logged.
Environment configuration
Keep every secret in environment variables. Commit only a .env.example with placeholders.
# Stripe sandbox (test mode) keys — placeholders only
STRIPE_SECRET_KEY=sk_test_replace_me
STRIPE_WEBHOOK_SECRET=whsec_replace_me
# Map plan names to Price IDs on the server
STRIPE_PRICE_PRO_MONTHLY=price_replace_me
STRIPE_PRICE_PRO_YEARLY=price_replace_me
APP_URL=http://localhost:3000Authentication
Server calls authenticate with your secret key as a bearer token (Authorization: Bearer sk_test_..., or HTTP Basic with the key as the username in curl). The official SDKs do this for you.
API versions: current Stripe SDKs pin the API version that was current when that SDK version was released; the version listed as current on 2026-11-25 was 2026-11-18.endive. Webhook payloads use the version set on the endpoint (or your account default), so create endpoints with the same version your SDK uses.
Your own users must be logged in before you create a Checkout or portal session for them — the portal session grants access to billing details for the Customer you pass.
Backend: Products, Prices and the subscription Checkout Session
Create the Product and Price once (Dashboard, CLI or a setup script). At checkout time your server looks up the logged-in user, reuses their Stripe Customer if one exists, and creates a Checkout Session in subscription mode. Store the user ↔ customer mapping so the portal and webhooks can find the user later.
Pass your own user ID in client_reference_id and/or metadata so webhook handlers can link the subscription to a user without trusting the browser.
import express from 'express';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const app = express();
const PRICES = {
pro_monthly: process.env.STRIPE_PRICE_PRO_MONTHLY,
pro_yearly: process.env.STRIPE_PRICE_PRO_YEARLY,
};
// NOTE: the webhook route (see the Webhooks section) must be registered
// BEFORE this JSON parser, because it needs the raw body.
app.use(express.json());
app.post('/api/billing/checkout', requireUser, async (req, res) => {
const price = PRICES[req.body.plan];
if (!price) return res.status(400).json({ error: 'unknown plan' });
const user = req.user; // from your auth middleware
const session = await stripe.checkout.sessions.create({
mode: 'subscription',
line_items: [{ price, quantity: 1 }],
// reuse an existing customer, otherwise let Checkout create one
...(user.stripeCustomerId ? { customer: user.stripeCustomerId } : { customer_email: user.email }),
client_reference_id: String(user.id),
subscription_data: { metadata: { userId: String(user.id) } },
success_url: `${process.env.APP_URL}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.APP_URL}/pricing`,
}, { idempotencyKey: `sub-checkout-${user.id}-${req.body.plan}-${req.body.attemptId}` });
res.json({ url: session.url });
});
app.post('/api/billing/portal', requireUser, async (req, res) => {
if (!req.user.stripeCustomerId) return res.status(400).json({ error: 'no subscription yet' });
const portal = await stripe.billingPortal.sessions.create({
customer: req.user.stripeCustomerId,
return_url: `${process.env.APP_URL}/account`,
});
res.json({ url: portal.url });
});
function requireUser(req, res, next) {
// replace with your real session/JWT check
if (!req.user) return res.status(401).end();
next();
}
app.listen(4242);import os
import stripe
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponseBadRequest
from django.views.decorators.http import require_POST
stripe.api_key = os.environ['STRIPE_SECRET_KEY']
APP_URL = os.environ['APP_URL']
PRICES = {
'pro_monthly': os.environ['STRIPE_PRICE_PRO_MONTHLY'],
'pro_yearly': os.environ['STRIPE_PRICE_PRO_YEARLY'],
}
@login_required
@require_POST
def create_checkout(request):
price = PRICES.get(request.POST.get('plan'))
if not price:
return HttpResponseBadRequest('unknown plan')
profile = request.user.billing # your model holding stripe_customer_id
params = dict(
mode='subscription',
line_items=[{'price': price, 'quantity': 1}],
client_reference_id=str(request.user.pk),
subscription_data={'metadata': {'user_id': str(request.user.pk)}},
success_url=f'{APP_URL}/billing/success?session_id={{CHECKOUT_SESSION_ID}}',
cancel_url=f'{APP_URL}/pricing',
)
if profile.stripe_customer_id:
params['customer'] = profile.stripe_customer_id
else:
params['customer_email'] = request.user.email
session = stripe.checkout.Session.create(**params)
return JsonResponse({'url': session.url})
@login_required
@require_POST
def create_portal(request):
customer = request.user.billing.stripe_customer_id
if not customer:
return HttpResponseBadRequest('no subscription yet')
portal = stripe.billing_portal.Session.create(
customer=customer, return_url=f'{APP_URL}/account')
return JsonResponse({'url': portal.url})Warning: In a Python f-string, {CHECKOUT_SESSION_ID} must be written as {{CHECKOUT_SESSION_ID}} or Python will try to interpolate it. Stripe replaces the literal placeholder after payment.
Tip: Stripe's current subscription example also sets subscription_data.billing_mode = { type: 'flexible' }. Whether you need it depends on your API version and proration needs — read the build-subscriptions page before copying it.
Frontend: pricing buttons and the portal link
With hosted Checkout the frontend is tiny: POST the chosen plan to your server, then redirect to the returned URL. The browser never sees a secret key, a Price ID choice it can tamper with, or an amount.
import { useState } from 'react';
async function postForUrl(path, body) {
const res = await fetch(path, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include', // send your session cookie
body: JSON.stringify(body),
});
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
return (await res.json()).url;
}
export function PricingButtons() {
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const go = async (path, body) => {
setBusy(true); setError(null);
try {
window.location.assign(await postForUrl(path, body));
} catch (e) {
setError(e.message); setBusy(false);
}
};
const attemptId = crypto.randomUUID();
return (
<div>
<button disabled={busy} onClick={() => go('/api/billing/checkout', { plan: 'pro_monthly', attemptId })}>
Pro — monthly
</button>
<button disabled={busy} onClick={() => go('/api/billing/checkout', { plan: 'pro_yearly', attemptId })}>
Pro — yearly
</button>
<button disabled={busy} onClick={() => go('/api/billing/portal', {})}>
Manage billing
</button>
{error && <p role="alert">{error}</p>}
</div>
);
}Starting a subscription
- User clicks a plan; your server maps the plan name to a Price ID and creates the Checkout Session.
- The browser is redirected to
session.url(Stripe-hosted). - The customer pays; Stripe creates the Customer, Subscription and first Invoice.
- Stripe sends
checkout.session.completed(and invoice/subscription events) to your webhook and redirects the customer tosuccess_url.
Confirming the subscription
Never grant access because the browser reached success_url. Anyone can type that URL. On the success page, either show "processing" until your webhook has updated the database, or retrieve the session server-side by its ID and check it belongs to the logged-in user before showing details.
The authoritative signal is a verified webhook: provision on checkout.session.completed, keep provisioning each period on invoice.paid, and read the subscription status (active, trialing, past_due, canceled, unpaid, incomplete, ...) from customer.subscription.* events.
Webhooks: verify, de-duplicate, provision
Stripe's minimum list for subscription Checkout is checkout.session.completed, invoice.paid and invoice.payment_failed. Most apps also handle:
customer.subscription.created/customer.subscription.updated— status, plan or quantity changed (renewals, upgrades, portal changes).customer.subscription.deleted— the subscription ended: revoke access.customer.subscription.trial_will_end— sent 3 days before a trial ends.
Rules: verify the Stripe-Signature header with constructEvent on the raw body; record the event ID before acting so retries are no-ops; make provisioning an *upsert keyed on subscription ID* so out-of-order events converge to the latest state; return 2xx quickly.
import express from 'express';
import Stripe from 'stripe';
import { db } from './db.js'; // your data layer
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
export const webhookRouter = express.Router();
webhookRouter.post('/webhooks/stripe', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = stripe.webhooks.constructEvent(
req.body, // Buffer — the exact bytes Stripe sent
req.headers['stripe-signature'],
process.env.STRIPE_WEBHOOK_SECRET,
);
} catch (err) {
return res.status(400).send(`Webhook signature error: ${err.message}`);
}
// Idempotency: insert-if-absent on a UNIQUE event id
const firstTime = await db.processedEvents.insertIfAbsent(event.id);
if (!firstTime) return res.sendStatus(200);
try {
const obj = event.data.object;
switch (event.type) {
case 'checkout.session.completed':
if (obj.mode === 'subscription') {
await db.users.linkCustomer(obj.client_reference_id, obj.customer);
await syncSubscription(obj.subscription);
}
break;
case 'invoice.paid':
case 'invoice.payment_failed':
case 'customer.subscription.created':
case 'customer.subscription.updated':
case 'customer.subscription.deleted': {
const subId = obj.object === 'subscription' ? obj.id : subscriptionIdFromInvoice(obj);
if (subId) await syncSubscription(subId);
if (event.type === 'invoice.payment_failed') await db.notify.paymentFailed(obj.customer);
break;
}
case 'customer.subscription.trial_will_end':
await db.notify.trialEnding(obj.customer, obj.trial_end);
break;
}
res.sendStatus(200);
} catch (err) {
await db.processedEvents.remove(event.id); // let Stripe retry
res.sendStatus(500);
}
});
// Re-read the subscription so stale/out-of-order events converge on current state.
async function syncSubscription(subscriptionId) {
const sub = await stripe.subscriptions.retrieve(subscriptionId);
await db.subscriptions.upsert({
id: sub.id,
customerId: sub.customer,
userId: sub.metadata.userId,
status: sub.status,
priceId: sub.items.data[0]?.price.id,
hasAccess: ['active', 'trialing'].includes(sub.status),
});
}
// Where the subscription id lives on an Invoice depends on the API version
// (older: invoice.subscription; newer: invoice.parent.subscription_details.subscription).
function subscriptionIdFromInvoice(inv) {
return inv.parent?.subscription_details?.subscription ?? inv.subscription ?? null;
}import os
import stripe
from django.db import IntegrityError, transaction
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from .models import ProcessedEvent, Subscription, BillingProfile
stripe.api_key = os.environ['STRIPE_SECRET_KEY']
WEBHOOK_SECRET = os.environ['STRIPE_WEBHOOK_SECRET']
SUB_EVENTS = {'invoice.paid', 'invoice.payment_failed', 'customer.subscription.created',
'customer.subscription.updated', 'customer.subscription.deleted'}
@csrf_exempt # Stripe cannot send your CSRF token; the signature protects this view
@require_POST
def stripe_webhook(request):
try:
event = stripe.Webhook.construct_event(
request.body, # raw bytes — do NOT use json.loads first
request.META.get('HTTP_STRIPE_SIGNATURE', ''),
WEBHOOK_SECRET,
)
except ValueError:
return HttpResponse(status=400) # invalid payload
except stripe.SignatureVerificationError:
return HttpResponse(status=400) # invalid signature
try:
with transaction.atomic():
ProcessedEvent.objects.create(event_id=event['id']) # unique column
handle(event)
except IntegrityError:
pass # already processed — acknowledge again
return HttpResponse(status=200)
def handle(event):
obj = event['data']['object']
etype = event['type']
if etype == 'checkout.session.completed' and obj.get('mode') == 'subscription':
BillingProfile.objects.filter(user_id=obj['client_reference_id']).update(
stripe_customer_id=obj['customer'])
sync_subscription(obj['subscription'])
elif etype in SUB_EVENTS:
if obj['object'] == 'subscription':
sub_id = obj['id']
else: # invoice: location depends on API version
parent = obj.get('parent') or {}
sub_id = (parent.get('subscription_details') or {}).get('subscription') or obj.get('subscription')
if sub_id:
sync_subscription(sub_id)
def sync_subscription(sub_id):
sub = stripe.Subscription.retrieve(sub_id)
Subscription.objects.update_or_create(
stripe_id=sub['id'],
defaults={
'customer_id': sub['customer'],
'status': sub['status'],
'price_id': sub['items']['data'][0]['price']['id'],
'has_access': sub['status'] in ('active', 'trialing'),
},
)Security: Stripe's SDKs reject signatures older than a default tolerance of 5 minutes. Never pass a tolerance of 0 — Stripe notes that disables the recency check.
Warning: The invoice → subscription field moved between API versions (invoice.subscription in older versions, invoice.parent.subscription_details.subscription in newer ones). The snippets read both; check the Invoice object reference for the version your endpoint uses.
Checking status on demand
Your app should read access from your own database (kept fresh by webhooks), not call Stripe on every page load. For reconciliation or support tooling, retrieve the subscription (stripe.subscriptions.retrieve(id)) or list a customer's subscriptions. If you missed events during an outage, Stripe retries for up to three days, and you can list recent events (last 30 days) with delivery_success=false to replay them.
Typical access rule: active or trialing → access; past_due → access with a warning banner (your choice); canceled, unpaid, incomplete_expired → no access.
Refunds, cancellations and credits
- Cancel: let customers cancel in the portal, or call
stripe.subscriptions.cancel(id)(immediate) / update withcancel_at_period_end: true(at period end). You learn the outcome fromcustomer.subscription.updated/customer.subscription.deleted. - Refund a period: refund the invoice's payment with the Refunds API (
stripe.refunds.create({ payment_intent }), optionally a partialamountin minor units). A refund does not cancel the subscription — do both if that is the intent. - Prorations on plan changes are calculated by Stripe and appear on the next invoice (or immediately, depending on
proration_behavior).
Error handling
- API errors come back as typed exceptions (
StripeCardError,StripeInvalidRequestError, ... in Node;stripe.CardError,stripe.InvalidRequestError, ... in Python). Log the request ID, show a generic message. resource_missingon a Price ID usually means you mixed sandbox and live IDs.- On
invoice.payment_failed, Stripe's retry settings (Smart Retries / your schedule) decide when the subscription becomespast_due,unpaidorcanceled; send the user to the portal to update their card. - Use idempotency keys on POSTs you might retry (keys up to 255 characters, Stripe prunes them after at least 24 hours).
Going live
- Activate the account, recreate Products/Prices in live mode (IDs differ) and swap env vars.
- Create a live webhook endpoint (HTTPS, TLS 1.2+) subscribed only to the events you handle; pin its API version to your SDK's.
- Configure the customer portal in live mode (allowed actions, products customers may switch between, cancellation policy).
- Configure retry/dunning emails and receipt emails in Billing settings.
- Consider Entitlements (Stripe maps Products to features and sends entitlement events) if you have many feature flags per plan.
Security checklist
- Secret key and webhook secret only in server env vars; never in the frontend bundle.
- Verify every webhook signature on the raw body; exempt only that route from CSRF.
- Authenticate the user before creating Checkout or portal sessions; never accept a
customerID from the browser. - Map plan names to Price IDs on the server so the client cannot pick a cheaper Price.
- Treat the
success_urlvisit as UX only. - Optionally restrict the webhook route to Stripe's published webhook IP addresses.
Testing
stripe listen --forward-to localhost:4242/webhooks/stripe(current docs show--all-snapshotfor snapshot events) and copy the printedwhsec_...intoSTRIPE_WEBHOOK_SECRET.- Subscribe with test card
4242 4242 4242 4242, any future expiry, any CVC. - Test failure paths:
4000 0000 0000 0341attaches to the customer but later charges fail (good for renewal failures);4000 0025 0000 3155requires authentication for off-session payments unless set up for future use. - Use a test clock to advance time past a renewal or trial end and watch
invoice.paid/invoice.payment_failed/customer.subscription.updatedarrive. - Open the portal, switch plans and cancel; confirm your database follows.
- Replay an event (
stripe events resend <id>) and confirm nothing is provisioned twice.
stripe login
stripe listen --forward-to localhost:4242/webhooks/stripe
# in another terminal: fire sample events
stripe trigger customer.subscription.created
stripe trigger invoice.payment_failedTip: stripe trigger creates its own sample objects that are not linked to your users, so your handler must tolerate unknown customers (log and return 200).
Common mistakes
- Webhook signature fails because the body was JSON-parsed (
express.json()registered before the webhook route, or Django code that re-serialisesjson.loads(request.body)). - Using the Dashboard endpoint's
whsec_while testing withstripe listen(or vice versa). - Granting access on the success page instead of from webhooks.
- Provisioning only on
checkout.session.completedand never revoking oncustomer.subscription.deleted. - Creating a new Customer on every checkout, so one user ends up with several subscriptions and the portal shows the wrong one.
- Hard-coding sandbox Price IDs that do not exist in live mode.
- Treating events as ordered:
invoice.paidcan arrive beforecheckout.session.completed.
Troubleshooting
No signatures found matching the expected signature for payload: wrong secret, modified body or wrong header. Print the secret your code uses (it starts withwhsec_, no whitespace) and verify on raw bytes.- Webhook delivered with 3xx: Stripe treats redirects as failures — point the endpoint at the final URL (watch trailing slashes and HTTP→HTTPS redirects).
- Timeouts: return 2xx first, then process heavy work in a queue.
- Portal error about configuration: save a portal configuration in the Dashboard (test mode) before creating sessions.
- Subscription stuck
incomplete: the first payment needs customer action (3DS) or failed; it expires toincomplete_expiredif not completed.
Further reading
- Subscription lifecycle and statuses
- Using webhooks with subscriptions
- Entitlements
- Test clocks
- Metatron guide: Stripe Checkout + webhooks (
stripe-checkout-webhooks)
Official documentation
All links checked on 2026-11-25.
Official documentation
Sources
- Stripe: Build a subscriptions integration (Checkout)
- Stripe: Subscription webhooks (event table)
- Stripe: Customer portal integration
- Stripe: Webhooks (signature checking, tolerance)
- Stripe: Manage webhook endpoints (signature errors)
- Stripe: Testing (test cards)
- Stripe: Test your Billing integration
- Stripe: API versioning
- Stripe: Idempotent requests
More payment guides
- Stripe provider profile
- Adyen Checkout: Sessions flow, Drop-in and HMAC webhooks
- Airtel Money Collections: USSD Push with the Airtel Africa Open API
- Flutterwave Checkout (Standard): hosted payment page, webhooks, verify and refunds
- M-Pesa Daraja STK Push (Lipa na M-Pesa Online)
- MTN MoMo Collections: Request to Pay with the MoMo Open API
- Mercado Pago Checkout Pro: preferences, back URLs and signed webhooks
- Mollie Payments API: hosted checkout, webhooks and refunds
- PayHero Kenya: M-Pesa STK Push via the PayHero API