Payments (Stripe)
Implement payments and subscriptions in your application using Stripe.
This template uses Stripe for payments and subscriptions. For more information, visit the Stripe documentation.
Setup
Prerequisites
Stripe Account
Products & Prices
Webhook Setup
Installation
Install the required packages:
Environment Variables
Add the following variables to your .env.local
file:
Never commit your Stripe secret key or webhook secret to version control. Always use environment variables.
Implementation
Stripe Client Setup
Configure the Stripe client in lib/stripe.ts
:
Payment Button Component
Reusable component for initiating Stripe checkout:
Stripe Redirect Handler
Server action to create Stripe checkout sessions:
Features
Multiple Plans
🔢 Support for different pricing tiers and subscription plans
Secure Checkout
🔒 PCI-compliant payment processing with Stripe Checkout
User Context
👤 Different flows for authenticated and anonymous users
Metadata Tracking
📊 Track plan types and user information in payments
Webhooks
Webhooks are essential for receiving payment events from Stripe and updating your application's state accordingly.
Webhook Handler
Create a webhook handler to process Stripe events:
Testing Webhooks Locally
Use the Stripe CLI to test webhooks during development:
Payment Flow
Payment Process
The payment flow integrates Stripe Checkout for secure, PCI-compliant payment processing.
- Initiate Payment: User clicks payment button, triggering
stripeRedirect
server action - Create Session: Server creates Stripe checkout session with plan details
- Redirect to Checkout: User is redirected to Stripe's hosted checkout page
- Process Payment: Stripe handles payment processing and security
- Handle Result: User is redirected back with success or cancel status
Subscription Management
Checking Subscription Status
Check if a user has an active subscription:
Customer Portal
Allow users to manage their subscriptions through Stripe Customer Portal:
Best Practices
Security
- Never log sensitive payment data
- Use webhook signatures for verification
- Implement proper error handling
- Validate payment status server-side
User Experience
- Show clear pricing information
- Handle loading states properly
- Provide clear error messages
- Implement proper success/cancel flows
Pricing Plans Configuration
Define your pricing plans in a configuration file: