Stripe Integration & Testing
This guide covers everything you need to know about integrating Stripe payments into your LaunchKit SaaS, including webhook setup and comprehensive testing procedures.
Overview
Section titled “Overview”LaunchKit’s Stripe integration handles:
- One-time payments for products and licenses
- Recurring subscriptions with automatic billing
- Customer portal for subscription management
- Webhook processing for real-time updates
- Invoice generation and payment tracking
Stripe Account Setup
Section titled “Stripe Account Setup”1. Create and Configure Stripe Account
Section titled “1. Create and Configure Stripe Account”- Go to Stripe Dashboard
- Complete your business profile
- Enable payment methods (cards, wallets, etc.)
- Set up your branding and customer emails
2. Get Your API Keys
Section titled “2. Get Your API Keys”# Test keys (for development)
STRIPE_PUBLIC_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec...
# Live keys (for production)
STRIPE_PUBLIC_KEY=pk_live_...
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec...
3. Configure Webhook Endpoint
Section titled “3. Configure Webhook Endpoint”-
In Stripe Dashboard, go to Developers → Webhooks
-
Click “Add endpoint”
-
Set endpoint URL:
https://yourdomain.com/api/webhook/stripe
-
Select these events to listen for:
checkout.session.completed
checkout.session.expired
customer.subscription.updated
customer.subscription.deleted
invoice.paid
invoice.payment_failed
-
Copy the webhook secret:
whsec_...
Environment Configuration
Section titled “Environment Configuration”Add your Stripe keys to .env.local
:
# Stripe Configuration
STRIPE_PUBLIC_KEY=pk_test_your_publishable_key
STRIPE_SECRET_KEY=sk_test_your_secret_key
STRIPE_WEBHOOK_SECRET=whsec_your_webhook_secret
Understanding the Webhook Handler
Section titled “Understanding the Webhook Handler”The webhook handler at /app/api/webhook/stripe/route.ts
processes Stripe events:
Key Event Handlers
Section titled “Key Event Handlers”case 'checkout.session.completed': {
// ✅ First payment successful
// - Create purchase record
// - Grant user access
// - Send confirmation email
// - Create user account if needed
}
case 'checkout.session.expired': {
// ⏰ User abandoned checkout
// - Send reminder email
// - Track conversion data
}
case 'customer.subscription.updated': {
// 🔄 Subscription changed
// - Update user access level
// - Handle plan changes
}
case 'customer.subscription.deleted': {
// ❌ Subscription cancelled
// - Revoke access
// - Send cancellation email
}
case 'invoice.paid': {
// ✅ Recurring payment successful
// - Extend access period
// - Send receipt email
}
case 'invoice.payment_failed': {
// ❌ Payment failed
// - Send payment failure notice
// - Handle retry logic
}
Product Management
Section titled “Product Management”1. Create Products in Stripe
Section titled “1. Create Products in Stripe”In your Stripe Dashboard:
-
Go to Products → Add Product
-
Enter product details:
- Name: “LaunchKit Pro License”
- Description: “Complete NextJS SaaS boilerplate”
- Price: $99 (one-time) or $29/month (subscription)
-
Copy the Price ID (starts with
price_
)
2. Add Products to Database
Section titled “2. Add Products to Database”Use your admin panel at /dashboard/admin/products
or directly insert:
INSERT INTO products (
name,
description,
price,
stripe_price_id,
type,
billing_type,
billing_interval,
is_active,
is_featured
) VALUES (
'LaunchKit Pro License',
'Complete NextJS SaaS boilerplate with authentication, payments, and deployment',
99.00,
'price_1234567890', -- Your Stripe price ID
'github', -- 'github' or 'link'
'one_time', -- 'one_time' or 'subscription'
NULL, -- NULL for one-time, 'month'/'year' for subscriptions
true,
true
);
Local Development Testing
Section titled “Local Development Testing”1. Install Stripe CLI
Section titled “1. Install Stripe CLI”brew install stripe/stripe-cli/stripe
# Download from https://github.com/stripe/stripe-cli/releases
# Or use Chocolatey
choco install stripe-cli
# Download and install from GitHub releases
wget https://github.com/stripe/stripe-cli/releases/latest/download/stripe_linux_x86_64.tar.gz
tar -xzf stripe_linux_x86_64.tar.gz
sudo mv stripe /usr/local/bin/stripe
2. Login to Stripe CLI
Section titled “2. Login to Stripe CLI”stripe login
This opens your browser to authenticate with your Stripe account.
3. Forward Events to Local Server
Section titled “3. Forward Events to Local Server”stripe listen --forward-to localhost:3000/api/webhook/stripe
Important: Keep this running in a separate terminal while testing!
The CLI will display:
- Webhook signing secret (starts with
whsec_
) - Real-time event logs
- HTTP request/response details
4. Update Local Environment
Section titled “4. Update Local Environment”Copy the webhook secret from the CLI output to your .env.local
:
STRIPE_WEBHOOK_SECRET=whsec_1234567890abcdef
Testing Payment Flows
Section titled “Testing Payment Flows”1. Test One-Time Payments
Section titled “1. Test One-Time Payments”- Start your local server:
bun dev
- Start Stripe CLI forwarding:
stripe listen --forward-to localhost:3000/api/webhook/stripe
- Navigate to your pricing page:
http://localhost:3000/#pricing
- Click a “Purchase” button
- Use Stripe test cards:
Card Number: 4242424242424242
Expiry: 12/34
CVC: 123
ZIP: 12345
Card Number: 4000000000000002
Expiry: 12/34
CVC: 123
ZIP: 12345
Card Number: 4000002500003155
Expiry: 12/34
CVC: 123
ZIP: 12345
2. Verify Webhook Processing
Section titled “2. Verify Webhook Processing”After completing a test payment, check:
Stripe CLI Output:
2025-01-15 10:30:15 --> checkout.session.completed [evt_1234567890]
2025-01-15 10:30:15 <-- [200] POST http://localhost:3000/api/webhook/stripe [evt_1234567890]
Database Changes:
-- Check purchase was created
SELECT * FROM purchases WHERE stripe_session_id = 'cs_test_...';
-- Check user access was granted
SELECT has_access FROM profiles WHERE customer_id = 'cus_...';
Server Logs:
Purchase record created for user abc-123 and product def-456
Purchase confirmation email sent to [email protected]
3. Test Subscription Flows
Section titled “3. Test Subscription Flows”For subscription products:
- Complete a subscription checkout
- In Stripe Dashboard, go to Customers → find your test customer
- Cancel the subscription to test cancellation flow
- Change the subscription to test update flow
4. Test Email Notifications
Section titled “4. Test Email Notifications”Each webhook event should trigger an email. Check your email service logs or use the test email endpoint to verify templates.
Advanced Testing Scenarios
Section titled “Advanced Testing Scenarios”1. Simulate Webhook Events
Section titled “1. Simulate Webhook Events”Use Stripe CLI to trigger specific events:
# Simulate successful payment
stripe trigger checkout.session.completed
# Simulate failed payment
stripe trigger invoice.payment_failed
# Simulate subscription cancellation
stripe trigger customer.subscription.deleted
2. Test Customer Portal
Section titled “2. Test Customer Portal”- Complete a subscription purchase
- Navigate to
/dashboard/settings/billing
- Click “Manage Billing” to open Stripe Customer Portal
- Test subscription changes, payment method updates, etc.
3. Test GitHub Repository Access
Section titled “3. Test GitHub Repository Access”For GitHub-type products:
- Complete purchase
- Navigate to
/dashboard/products
- Provide GitHub username
- Verify repository invitation is sent
Production Deployment
Section titled “Production Deployment”1. Update Webhook Endpoint
Section titled “1. Update Webhook Endpoint”In Stripe Dashboard:
- Update webhook endpoint to your production URL
- Copy the new webhook secret
- Update production environment variables
2. Switch to Live Keys
Section titled “2. Switch to Live Keys”Replace test keys with live keys:
STRIPE_WEBHOOK_SECRET=pk_live_your_live_key
STRIPE_SECRET_KEY=sk_live_your_live_secret
STRIPE_WEBHOOK_SECRET=whsec_your_live_webhook_secret
3. Test Production Webhooks
Section titled “3. Test Production Webhooks”Use Stripe CLI to test production webhooks:
stripe listen --forward-to https://yourdomain.com/api/webhook/stripe --live
Webhook Security
Section titled “Webhook Security”The webhook handler includes several security measures:
1. Signature Verification
Section titled “1. Signature Verification”try {
event = stripe.webhooks.constructEvent(body, signature, webhookSecret);
} catch (err) {
console.error(`Webhook signature verification failed. ${err.message}`);
return NextResponse.json({ error: err.message }, { status: 400 });
}
2. Idempotency
Section titled “2. Idempotency”Webhooks are idempotent - processing the same event multiple times won’t cause issues.
3. Service Role Database Access
Section titled “3. Service Role Database Access”Webhooks use the Supabase service role key to bypass RLS policies:
const supabase = new SupabaseClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.SUPABASE_SERVICE_ROLE_KEY
);
Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”Webhook Not Receiving Events:
- Check webhook URL is correct and accessible
- Verify webhook secret matches
- Check firewall settings
Database Errors:
- Ensure service role key has correct permissions
- Check RLS policies allow webhook operations
- Verify foreign key relationships
Email Not Sending:
- Check Resend API key is configured
- Verify email templates are valid
- Check rate limits and quotas
Debug Tools
Section titled “Debug Tools”Stripe Dashboard:
- View all webhook attempts and responses
- See detailed event data
- Check customer and payment status
Stripe CLI:
# View recent events
stripe events list
# Get specific event details
stripe events retrieve evt_1234567890
# Resend webhook
stripe events resend evt_1234567890
Server Logs: Add detailed logging to your webhook handler for debugging.