Stripe Payments Tutorial
Stripe payments, including one-time payments, subscriptions, and webhook configuration.
This tutorial covers one-time payments, subscriptions, tax handling, and webhook event processing. Let's start by setting up your environment.
Environment Setup
To get started, set up your Stripe account and copy your API keys.
If you are using subscriptions, also create a webhook endpoint (api/webhook/stripe
)
In .env.local
, add your Stripe secret and public keys (as well as the webhook secret if subscriptions are used):
bash
1NEXT_PUBLIC_STRIPE_SECRET_KEY=sk_live_... 2NEXT_PUBLIC_STRIPE_PUBLIC_KEY=pk_live_... 3NEXT_PUBLIC_STRIPE_WEBHOOK_SECRET=whsec_...
Creating Checkout Sessions
We use a dedicated API endpoint to create Checkout Sessions. This endpoint accepts the plan type and mode (payment or subscription) and creates a session with automatic tax enabled.
jsx
1// Example: Creating a Checkout Session
2const session = await createCheckoutSession({
3planType: "starter", // or "pro"
4mode: "payment", // use "subscription" for recurring payments
5successUrl: "https://your-app.com/thank-you",
6cancelUrl: "https://your-app.com/",
7});
This session is then used on the client to redirect users to Stripe’s secure, hosted payment page.
Configuring Webhooks
Stripe sends payment events via webhooks. Set up your local environment to listen to these events:
- Local Testing: Use the Stripe CLI to forward events to your endpoint:
bash
1stripe listen --forward-to localhost:3000/api/webhook/stripe
- Webhook Endpoint: Our endpoint (api/webhook/stripe/route.js) verifies the signature and then routes the event to custom handlers. Customize these handlers in libs/stripe/webhookHandlers.js to, for example, update subscription statuses or send confirmation emails.
jsx
1// Example: Verifying webhook events
2const event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
3await handleStripeWebhookEvent(event);
Testing Your Integration
- One-Time Payments: Use test card number 4242 4242 4242 4242 for a successful charge.
- Subscriptions: Create subscriptions using your test pricing IDs and verify that recurring billing works.
- Webhook Testing: Ensure your local webhook endpoint receives and processes events correctly. Check your logs for messages from our custom event handlers.
Additional Tips
Customize your Checkout Session by setting different modes, adding metadata, or adjusting tax settings directly in the session creation options.
Always secure your endpoints. Verify webhook signatures and store your API keys in environment variables.
In production, double-check your Stripe Dashboard settings—like authorized domains and redirect URLs—to ensure a seamless payment experience.
That’s it! With this guide, you have a full Stripe payment system that’s modular, secure, and ready for production. Enjoy building your app without the hassle of setting up payments from scratch.
Happy coding!