SvelteKit + Stripe Subscriptions
Example of using Stripe Subscriptions & PaymentElement with SvelteKit.
Note: Stripe Checkout is an alternative approach if you want to use pre-built payment forms. Need help choosing?
Payment Flow
To complete a subscription payment:
- The User enters their e-mail address and name. View code
- A Stripe Customer record is created and
customer.idis stored in a cookie. View code - A Stripe Subscription record is created based on a
priceId. Then the Payment Intent's secret is returned. View code - The User is presented with the
<PaymentElement>to enter their payment info. View code - The User submits the form, and
stripe.confirmPayment()is called. View code - Stripe redirects the User to the thank you page. View code
- Stripe sends webhook
customer.subscription.created. View code
Note: Steps 6 and 7 may happen in reverse order. Make sure to provision the subscription from the thank you page and the webhook handler.
Setup
Clone the repo:
gh repo clone joshnuss/sveltekit-stripe-subscriptionsConfigure environment variables in .env:
cp .env.example .envPUBLIC_STRIPE_KEY: Your public Stripe key.SECRET_STRIPE_KEY: Your private Stripe key.SECRET_STRIPE_WEBHOOK_KEY: Stripe's secret used to sign webhooks.STRIPE_PRICE_ID: ThepriceIdfor the subscription product. You might want to store this in your database.DOMAIN: The site's domain. Used for creating redirect URLs. Default ishttp://localhost:5173
Install dependecies:
pnpm installUsage
Tunnel Stripe events:
stripe listen --forward-to localhost:5173/stripe/webhooksRun the dev server:
SECRET_STRIPE_WEBHOOK_KEY=whsec_.... pnpm devLicense
MIT