Skip to content
Code Snippets$19

Stripe Subscription Handler

Set up subscription billing with Stripe Checkout, verified webhooks, customer portal links, and subscription status sync without rebuilding the billing layer from scratch.

Prerequisites

  • A Node.js, Express, or Next.js API project.
  • A Stripe account with at least one Product and recurring Price.
  • Stripe secret key, publishable key, webhook signing secret, and price IDs.
  • A user table or customer table where Stripe customer and subscription IDs can be stored.
1

Install the package

Add the billing module and Stripe SDK to your API workspace.

Checklist
  • Confirm your project runs on Node.js 18 or newer.
  • Keep the package in the server/API workspace, not a browser-only bundle.
Setup snippet
npm install @codersarts/stripe-subscription-handler stripe
2

Configure environment variables

Copy the example environment file and add your Stripe keys before starting the server.

Setup snippet
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PRICE_PRO=price_...
APP_URL=http://localhost:3000
Note: Use test keys locally and live keys only in production hosting secrets.
3

Create a checkout endpoint

  1. Import the subscription handler in your API route.
  2. Look up the signed-in user and create or reuse their Stripe customer ID.
  3. Pass the selected price ID, success URL, and cancel URL to createCheckoutSession.
  4. Return the checkout URL to the frontend and redirect the user.
4

Wire the webhook endpoint

  1. Create a raw-body endpoint at /api/stripe/webhook.
  2. Verify the Stripe signature with STRIPE_WEBHOOK_SECRET.
  3. Handle subscription.created, subscription.updated, subscription.deleted, and invoice.payment_failed.
  4. Persist the latest subscription status in your database.
Note: Webhook routes must receive the raw request body. JSON body parsing before verification will break signature checks.
5

Test the billing flow

  1. Run the Stripe CLI and forward events to your local webhook route.
  2. Complete checkout with a Stripe test card.
  3. Confirm your local database stores customer ID, subscription ID, plan, and status.
  4. Open the customer portal and verify plan changes sync back through webhooks.
6

Deploy safely

Checklist
  • Add live Stripe keys to production environment variables.
  • Create a live webhook endpoint in Stripe Dashboard.
  • Run one live low-value subscription test before launch.
  • Monitor webhook failures for the first 24 hours after release.

Need help implementing this?

CodersArts can wire this into your existing stack, adapt the flow to your product, and hand over a working implementation.

Request implementation help