nextjs-stripe-integration
БесплатноБез исполняемых скриптовНе проверенAdd Stripe payment processing to Next.js projects. Implement checkout sessions, payment handling, subscriptions, webhooks, and customer management. Use when…
от Microck★ 417 звёзд на GitHubОб этом скилле
Next.js + Stripe Integration
This Skill teaches Claude how to implement Stripe payment processing in Next.js projects, including one-time payments, subscriptions, webhooks, and customer management. Based on real-world implementation experience with modern Stripe APIs and authentication frameworks.
⚠️ CRITICAL: Breaking Changes in Modern Stripe.js
stripe.redirectToCheckout() is DEPRECATED and no longer works!
Modern Stripe implementations use the checkout session URL directly:
// ❌ OLD (BROKEN)
const { error } = await stripe.redirectToCheckout({ sessionId });
// ✅ NEW (CORRECT)
const session = await stripe.checkout.sessions.create({...});
window.location.href = session.url; // Use the URL directly!
Quick Start Checklist
When implementing Stripe in a Next.js project:
- Install dependencies:
stripeand@stripe/stripe-js - Configure environment: Add
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEYandSTRIPE_SECRET_KEYto.env.local - Access env vars correctly: Load inside functions, NOT at module level (critical for runtime)
- Create API routes: Build endpoints for checkout sessions, webhooks, and customer portal
- Build UI: Create checkout forms and payment pages
- Handle webhooks: Set up secure webhook handlers for payment events
- Update middleware: Add payment routes to
unauthenticatedPathsif using auth middleware - Test locally: Use Stripe CLI for webhook testing
Core Implementation Patterns
1. Environment Setup & Runtime Loading
# .env.local
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
CRITICAL: Access environment variables inside API route functions, NOT at module initialization:
// ❌ WRONG - Fails at build/startup
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST() { ... }
// ✅ CORRECT - Variables loaded at runtime
export async function POST(request: NextRequest) {
const stripeSecretKey = process.env.STRIPE_SECRET_KEY;
if (!stripeSecretKey) {
return NextResponse.json({ error: 'API key not configured' }, { status: 500 });
}
const stripe = new Stripe(stripeSecretKey);
// ... rest of function
}
Important: Only use NEXT_PUBLIC_ prefix for publishable keys. Secret keys stay server-side only.
2. One-Time Payments (Checkout) - Modern Approach
API Route (app/api/checkout/route.ts):
- Load Stripe with secret key inside the function
- Create a Stripe checkout session with
mode: 'payment' - Return the full session URL (not just session ID)
- Verify webhook signatures on payment success
// ✅ CORRECT: Load env vars inside function
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const session = await stripe.checkout.sessions.create({...});
return NextResponse.json({ url: session.url }); // Return URL directly
Client Side (Simplified):
- NO need to load Stripe.js for basic checkout
- Call checkout API route
- Redirect to
session.urldirectly from response - Handle success/cancel redirects via query parameters
3. Subscriptions
Differences from one-time payments:
- Create products in Stripe Dashboard with recurring pricing
- Use
mode: 'subscription'when creating checkout sessions - Manage customer subscriptions in database
- Handle multiple lifecycle events via webhooks
Key workflow:
- Fetch available subscription tiers from Stripe API
- Display pricing page with subscription options
- Create checkout session with subscription mode
- Handle
customer.subscription.createdwebhook - Sync subscription status to your database
4. Webhook Handling
Critical security requirements:
- Verify webhook signatures using Stripe's libraries
- Use raw request body for signature validation (disable body parsing)
- Handle these key events:
payment_intent.succeeded— one-time payment confirmedcustomer.subscription.created— new subscriptioncustomer.subscription.updated— subscription changescustomer.subscription.deleted— cancellationinvoice.payment_succeeded— renewal payment
Webhook endpoint (app/api/webhooks/stripe/route.ts):
- Accept POST requests from Stripe
- Verify signature:
stripe.webhooks.constructEvent(body, signature, secret) - Process event and update database
- Return 200 status to acknowledge
5. Authentication Middleware Configuration
When using WorkOS or similar auth frameworks, explicitly allow payment routes:
// middleware.ts
export default authkitMiddleware({
eagerAuth: true,
middlewareAuth: {
enabled: true,
unauthenticatedPaths: [
'/',
'/sign-in',
'/sign-up',
'/api/checkout', // Allow unauthenticated checkout
'/api/webhooks/stripe', // Allow webhook delivery
'/payment-success',
'/payment-cancel',
],
},
});
Why: Without this, auth mi
Установить nextjs-stripe-integration в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл nextjs-stripe-integration?
Add Stripe payment processing to Next.js projects. Implement checkout sessions, payment handling, subscriptions, webhooks, and customer management. Use when adding Stripe to a Next.js project, building payment flows, implementing subscriptions, or integrating payment processing.
Как установить скилл nextjs-stripe-integration?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл nextjs-stripe-integration запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic