Kurs Next.js · Moduł 9: Integracje i zaawansowane funkcje
Next.js i Stripe - Kompletny system płatności
W tej lekcji9
W futurystycznej Metropolii Quantum, gdzie transakcje odbywają się błyskawicznie i bezpiecznie, poznasz integrację Next.js ze Stripe - najpopularniejszą platformą płatności online. Ta kombinacja pozwala budować profesjonalne systemy e-commerce z pełną obsługą płatności.
Czym jest Stripe?
Stripe to kompleksowa platforma płatności online, która oferuje:
- Globalne płatności - obsługa 135+ walut i metod płatności
- Developer-friendly API - czytelna dokumentacja i SDK
- Security - zgodność z PCI DSS Level 1
- Subscription management - zarządzanie subskrypcjami
- Fraud prevention - zaawansowana ochrona przed oszustwami
- Webhooks - real-time powiadomienia o zdarzeniach
Instalacja i konfiguracja
Krok 1: Utworzenie konta Stripe
- Zarejestruj się na stripe.com
- Przejdź do Dashboard → Developers → API keys
- Skopiuj klucze:
- Publishable key - używany po stronie klienta
- Secret key - używany tylko po stronie serwera
Krok 2: Instalacja pakietów
# Zainstaluj Stripe SDK
npm install stripe @stripe/stripe-js @stripe/react-stripe-js
# Dla TypeScript dodaj typy
npm install -D @types/stripeKrok 3: Konfiguracja zmiennych środowiskowych
Utwórz plik .env.local:
# Stripe keys
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# App URL
NEXT_PUBLIC_APP_URL=http://localhost:3000Podstawowa integracja
Krok 1: Inicjalizacja Stripe
Utwórz instancję Stripe po stronie serwera:
// lib/stripe.ts
import Stripe from 'stripe';
if (!process.env.STRIPE_SECRET_KEY) {
throw new Error('STRIPE_SECRET_KEY is not defined');
}
export const stripe = new Stripe(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2023-10-16',
typescript: true,
});Po stronie klienta:
// lib/stripe-client.ts
import { loadStripe } from '@stripe/stripe-js';
if (!process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY) {
throw new Error('NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY is not defined');
}
// Singleton pattern dla lepszej wydajności
let stripePromise: Promise<any>;
export const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
}
return stripePromise;
};Krok 2: Stripe Provider
Opakuj aplikację w Stripe Provider:
// app/providers.tsx
'use client';
import { Elements } from '@stripe/react-stripe-js';
import { getStripe } from '@/lib/stripe-client';
interface ProvidersProps {
children: React.ReactNode;
}
export function Providers({ children }: ProvidersProps) {
return (
<Elements stripe={getStripe()}>
{children}
</Elements>
);
}
// app/layout.tsx
import { Providers } from './providers';
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="pl">
<body>
<Providers>
{children}
</Providers>
</body>
</html>
);
}Implementacja płatności
Checkout Session (Recommended)
Stripe Checkout to gotowy, hostowany formularz płatności:
// app/api/checkout/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
export async function POST(request: NextRequest) {
try {
const { items } = await request.json();
// Walidacja items
if (!items || !Array.isArray(items) || items.length === 0) {
return NextResponse.json(
{ error: 'No items provided' },
{ status: 400 }
);
}
// Tworzenie line items dla Stripe
const lineItems = items.map(item => ({
price_data: {
currency: 'pln',
product_data: {
name: item.name,
description: item.description,
images: item.images ? [item.images] : [],
},
unit_amount: Math.round(item.price * 100), // Stripe używa groszy
},
quantity: item.quantity,
}));
// Tworzenie sesji checkout
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card', 'blik', 'p24'],
line_items: lineItems,
mode: 'payment',
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/cart`,
metadata: {
orderId: 'unique-order-id',
customerId: 'customer-id',
},
locale: 'pl',
});
return NextResponse.json({ sessionId: session.id });
} catch (error) {
console.error('Checkout error:', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}Komponent do obsługi checkout:
// components/CheckoutButton.tsx
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { getStripe } from '@/lib/stripe-client';
interface CheckoutButtonProps {
items: Array<{
name: string;
description?: string;
price: number;
quantity: number;
images?: string;
}>;
}
export function CheckoutButton({ items }: CheckoutButtonProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const handleCheckout = async () => {
setLoading(true);
try {
// Tworzenie sesji checkout
const response = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ items }),
});
const { sessionId, error } = await response.json();
if (error) {
throw new Error(error);
}
// Przekierowanie do Stripe Checkout
const stripe = await getStripe();
const { error: stripeError } = await stripe!.redirectToCheckout({
sessionId,
});
if (stripeError) {
throw stripeError;
}
} catch (error) {
console.error('Checkout error:', error);
alert('Wystąpił błąd podczas przekierowania do płatności');
} finally {
setLoading(false);
}
};
return (
<button
onClick={handleCheckout}
disabled={loading}
className="bg-blue-600 text-white px-6 py-3 rounded-lg disabled:opacity-50"
>
{loading ? 'Przekierowywanie...' : 'Przejdź do płatności'}
</button>
);
}Payment Element (Custom Form)
Dla większej kontroli nad UX, użyj Payment Element:
// components/PaymentForm.tsx
'use client';
import { useState, FormEvent } from 'react';
import {
PaymentElement,
useStripe,
useElements,
} from '@stripe/react-stripe-js';
interface PaymentFormProps {
clientSecret: string;
}
export function PaymentForm({ clientSecret }: PaymentFormProps) {
const stripe = useStripe();
const elements = useElements();
const [error, setError] = useState<string | null>(null);
const [processing, setProcessing] = useState(false);
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
if (!stripe || !elements) {
return;
}
setProcessing(true);
setError(null);
const { error: submitError } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: `${window.location.origin}/payment-success`,
},
});
if (submitError) {
setError(submitError.message || 'Wystąpił błąd');
setProcessing(false);
}
};
return (
<form onSubmit={handleSubmit} className="space-y-6">
<PaymentElement
options={{
layout: 'tabs',
paymentMethodOrder: ['card', 'blik', 'p24'],
}}
/>
{error && (
<div className="text-red-600 text-sm">{error}</div>
)}
<button
type="submit"
disabled={!stripe || processing}
className="w-full bg-blue-600 text-white py-3 rounded-lg disabled:opacity-50"
>
{processing ? 'Przetwarzanie...' : 'Zapłać'}
</button>
</form>
);
}API dla Payment Intent
// app/api/payment-intent/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
export async function POST(request: NextRequest) {
try {
const { amount, currency = 'pln' } = await request.json();
// Walidacja kwoty
if (!amount || amount <= 0) {
return NextResponse.json(
{ error: 'Invalid amount' },
{ status: 400 }
);
}
// Tworzenie Payment Intent
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(amount * 100), // Konwersja na grosze
currency,
automatic_payment_methods: {
enabled: true,
},
metadata: {
orderId: 'unique-order-id',
},
});
return NextResponse.json({
clientSecret: paymentIntent.client_secret,
});
} catch (error) {
console.error('Payment intent error:', error);
return NextResponse.json(
{ error: 'Failed to create payment intent' },
{ status: 500 }
);
}
}Webhooks
Webhooks pozwalają na otrzymywanie powiadomień o zdarzeniach w Stripe:
// app/api/webhooks/stripe/route.ts
import { headers } from 'next/headers';
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import Stripe from 'stripe';
export async function POST(request: NextRequest) {
const body = await request.text();
const signature = (await headers()).get('stripe-signature');
if (!signature) {
return NextResponse.json(
{ error: 'Missing stripe-signature header' },
{ status: 400 }
);
}
let event: Stripe.Event;
try {
event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET!
);
} catch (error) {
console.error('Webhook signature verification failed:', error);
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 400 }
);
}
// Obsługa różnych typów eventów
try {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
// Obsłuż ukończoną płatność
await handleSuccessfulPayment(session);
break;
}
case 'payment_intent.succeeded': {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
// Aktualizuj status zamówienia
console.log('Payment succeeded:', paymentIntent.id);
break;
}
case 'payment_intent.payment_failed': {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
// Obsłuż nieudaną płatność
console.log('Payment failed:', paymentIntent.id);
break;
}
case 'customer.subscription.created':
case 'customer.subscription.updated':
case 'customer.subscription.deleted': {
const subscription = event.data.object as Stripe.Subscription;
// Obsłuż zmiany w subskrypcji
await handleSubscriptionChange(subscription);
break;
}
default:
console.log(`Unhandled event type: ${event.type}`);
}
return NextResponse.json({ received: true });
} catch (error) {
console.error('Webhook handler error:', error);
return NextResponse.json(
{ error: 'Webhook handler failed' },
{ status: 500 }
);
}
}
async function handleSuccessfulPayment(session: Stripe.Checkout.Session) {
// Implementacja logiki po udanej płatności
console.log('Payment successful for session:', session.id);
// Przykład: Aktualizacja statusu zamówienia w bazie danych
// await updateOrderStatus(session.metadata.orderId, 'paid');
// Wysłanie emaila z potwierdzeniem
// await sendConfirmationEmail(session.customer_email);
}
async function handleSubscriptionChange(subscription: Stripe.Subscription) {
// Implementacja logiki dla subskrypcji
console.log('Subscription changed:', subscription.id);
}Subskrypcje
Implementacja systemu subskrypcji:
// app/api/subscription/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { auth } from '@/lib/auth'; // Twoja funkcja autentykacji
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.email) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { priceId } = await request.json();
// Znajdź lub utwórz klienta w Stripe
let customerId: string;
const customers = await stripe.customers.list({
email: session.user.email,
limit: 1,
});
if (customers.data.length > 0) {
customerId = customers.data[0].id;
} else {
const customer = await stripe.customers.create({
email: session.user.email,
metadata: {
userId: session.user.id,
},
});
customerId = customer.id;
}
// Utwórz sesję checkout dla subskrypcji
const checkoutSession = await stripe.checkout.sessions.create({
customer: customerId,
payment_method_types: ['card'],
line_items: [
{
price: priceId,
quantity: 1,
},
],
mode: 'subscription',
allow_promotion_codes: true,
success_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.NEXT_PUBLIC_APP_URL}/pricing`,
metadata: {
userId: session.user.id,
},
});
return NextResponse.json({ sessionId: checkoutSession.id });
} catch (error) {
console.error('Subscription error:', error);
return NextResponse.json(
{ error: 'Failed to create subscription' },
{ status: 500 }
);
}
}Customer Portal
Pozwól użytkownikom zarządzać subskrypcjami:
// app/api/customer-portal/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { auth } from '@/lib/auth';
export async function POST(request: NextRequest) {
try {
const session = await auth();
if (!session?.user?.email) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Znajdź klienta
const customers = await stripe.customers.list({
email: session.user.email,
limit: 1,
});
if (customers.data.length === 0) {
return NextResponse.json(
{ error: 'Customer not found' },
{ status: 404 }
);
}
// Utwórz sesję Customer Portal
const portalSession = await stripe.billingPortal.sessions.create({
customer: customers.data[0].id,
return_url: `${process.env.NEXT_PUBLIC_APP_URL}/dashboard`,
});
return NextResponse.json({ url: portalSession.url });
} catch (error) {
console.error('Customer portal error:', error);
return NextResponse.json(
{ error: 'Failed to create portal session' },
{ status: 500 }
);
}
}Bezpieczeństwo
1. Walidacja po stronie serwera
Zawsze waliduj dane po stronie serwera:
// lib/validation.ts
import { z } from 'zod';
export const checkoutSchema = z.object({
items: z.array(z.object({
name: z.string().min(1).max(100),
description: z.string().optional(),
price: z.number().positive(),
quantity: z.number().int().positive(),
images: z.string().url().optional(),
})).min(1),
});
// Użycie w API route
const validatedData = checkoutSchema.parse(await request.json());2. Rate limiting
Zabezpiecz API przed nadużyciami:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(10, '10 s'),
});
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api/')) {
const ip = request.ip ?? '127.0.0.1';
const { success } = await ratelimit.limit(ip);
if (!success) {
return NextResponse.json(
{ error: 'Too many requests' },
{ status: 429 }
);
}
}
return NextResponse.next();
}3. Webhook security
Zawsze weryfikuj podpisy webhooków:
// Użyj stripe.webhooks.constructEvent() jak pokazano wcześniej
// Dodatkowo możesz dodać IP whitelisting
const allowedIPs = [
'3.18.12.63',
'3.130.192.231',
// Pełna lista: https://stripe.com/docs/ips
];Testing
Test mode
Stripe oferuje tryb testowy z kartami testowymi:
// Popularne karty testowe
const testCards = {
success: '4242424242424242',
decline: '4000000000000002',
authRequired: '4000002500003155',
insufficientFunds: '4000000000009995',
};Testowanie webhooków lokalnie
Użyj Stripe CLI:
# Instalacja
brew install stripe/stripe-cli/stripe
# Logowanie
stripe login
# Forward webhooks do lokalnego serwera
stripe listen --forward-to localhost:3000/api/webhooks/stripe
# Test webhook
stripe trigger payment_intent.succeededPodsumowanie
Integracja Next.js ze Stripe daje potężne możliwości budowania systemów płatności. Kluczowe elementy to:
- Checkout Session - dla szybkiej implementacji
- Payment Element - dla custom UX
- Webhooks - dla niezawodności
- Security - walidacja i rate limiting
- Testing - tryb testowy i Stripe CLI
Ta kombinacja pozwala budować profesjonalne aplikacje e-commerce, SaaS z subskrypcjami, marketplace i wiele innych.
Kod do tej lekcji: App.tsx
import React, { useState } from 'react';
interface Product {
id: string;
name: string;
description: string;
price: number;
image: string;
}
interface CartItem extends Product {
quantity: number;
}
const products: Product[] = [
{ id: 'prod_1', name: 'Quantum Shield Pro', description: 'Zaawansowana ochrona danych', price: 4999, image: '' },
{ id: 'prod_2', name: 'Neural Interface v3', description: 'Interfejs programistyczny AI', price: 9999, image: '' },
{ id: 'prod_3', name: 'Cyber Toolkit', description: 'Zestaw narzędzi deweloperskich', price: 2499, image: '' },
{ id: 'prod_4', name: 'Data Stream Engine', description: 'Silnik przetwarzania danych', price: 7499, image: '' },
];
const StripeDemo = () => {
const [cart, setCart] = useState<CartItem[]>([]);
const [step, setStep] = useState<'shop' | 'checkout' | 'success'>('shop');
const [processing, setProcessing] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const addToCart = (product: Product) => {
setCart(prev => {
const existing = prev.find(i => i.id === product.id);
if (existing) return prev.map(i => i.id === product.id ? { ...i, quantity: i.quantity + 1 } : i);
return [...prev, { ...product, quantity: 1 }];
});
};
const total = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
const handleCheckout = async () => {
setProcessing(true);
setLogs([]);
const addLog = (msg: string) => setLogs(prev => [...prev, msg]);
addLog('POST /api/checkout - Creating Stripe session...');
await new Promise(r => setTimeout(r, 500));
addLog('stripe.checkout.sessions.create({ mode: "payment" })');
await new Promise(r => setTimeout(r, 400));
addLog('Session created: cs_live_a1B2c3D4...');
await new Promise(r => setTimeout(r, 300));
addLog('Redirecting to Stripe Checkout...');
await new Promise(r => setTimeout(r, 600));
addLog('Payment successful! session.payment_status: "paid"');
await new Promise(r => setTimeout(r, 300));
addLog('Webhook received: checkout.session.completed');
addLog('Order fulfilled. Redirecting to success page...');
await new Promise(r => setTimeout(r, 400));
setStep('success');
setProcessing(false);
};
const formatPrice = (cents: number) => (cents / 100).toFixed(2) + ' PLN';
return (
<div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
<h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + Stripe Payments</h1>
{step === 'shop' && (
<div style={{ maxWidth: '800px', margin: '20px auto' }}>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '16px', marginBottom: '20px' }}>
{products.map(p => (
<div key={p.id} style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '10px', border: '1px solid #333' }}>
<div style={{ fontSize: '48px', textAlign: 'center' }}>{p.image}</div>
<h3 style={{ color: '#64ffda', margin: '8px 0' }}>{p.name}</h3>
<p style={{ color: '#888', fontSize: '13px' }}>{p.description}</p>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '12px' }}>
<span style={{ color: '#7c4dff', fontWeight: 'bold' }}>{formatPrice(p.price)}</span>
<button onClick={() => addToCart(p)} style={{ padding: '8px 16px', background: '#7c4dff', border: 'none', borderRadius: '6px', color: '#fff', cursor: 'pointer' }}>
Do koszyka
</button>
</div>
</div>
))}
</div>
{cart.length > 0 && (
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '20px', borderRadius: '10px', border: '1px solid #7c4dff' }}>
<h3 style={{ color: '#64ffda' }}>Koszyk ({cart.reduce((s, i) => s + i.quantity, 0)})</h3>
{cart.map(item => (
<div key={item.id} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 0', borderBottom: '1px solid #222' }}>
<span>{item.image} {item.name} x{item.quantity}</span>
<span style={{ color: '#7c4dff' }}>{formatPrice(item.price * item.quantity)}</span>
</div>
))}
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '12px', paddingTop: '12px', borderTop: '2px solid #7c4dff' }}>
<strong>Suma:</strong>
<strong style={{ color: '#64ffda' }}>{formatPrice(total)}</strong>
</div>
<button onClick={() => setStep('checkout')} style={{ width: '100%', marginTop: '12px', padding: '12px', background: 'linear-gradient(45deg, #7c4dff, #64ffda)', border: 'none', borderRadius: '8px', color: '#0f0f23', fontWeight: 'bold', cursor: 'pointer', fontSize: '16px' }}>
Przejdz do platnosci
</button>
</div>
)}
</div>
)}
{step === 'checkout' && (
<div style={{ maxWidth: '600px', margin: '20px auto' }}>
<div style={{ background: 'rgba(255,255,255,0.05)', padding: '24px', borderRadius: '10px', border: '1px solid #333' }}>
<h2 style={{ color: '#64ffda', marginBottom: '16px' }}>Stripe Checkout</h2>
<p style={{ color: '#888', marginBottom: '16px' }}>Suma: <strong style={{ color: '#7c4dff' }}>{formatPrice(total)}</strong></p>
<button onClick={handleCheckout} disabled={processing}
style={{ width: '100%', padding: '14px', background: processing ? '#555' : '#635bff', border: 'none', borderRadius: '8px', color: '#fff', fontWeight: 'bold', cursor: processing ? 'default' : 'pointer', fontSize: '16px' }}>
{processing ? 'Przetwarzanie...' : 'Zaplac przez Stripe'}
</button>
</div>
{logs.length > 0 && (
<div style={{ background: '#000', padding: '16px', borderRadius: '10px', marginTop: '16px', fontFamily: 'monospace', fontSize: '12px' }}>
{logs.map((log, i) => (<div key={i} style={{ color: '#0f0', padding: '2px 0' }}>{log}</div>))}
</div>
)}
</div>
)}
{step === 'success' && (
<div style={{ maxWidth: '500px', margin: '40px auto', textAlign: 'center' }}>
<div style={{ fontSize: '64px' }}>OK</div>
<h2 style={{ color: '#64ffda', margin: '16px 0' }}>Platnosc zakonczona!</h2>
<p style={{ color: '#888' }}>Zamowienie zostalo przetworzone pomyslnie.</p>
<button onClick={() => { setStep('shop'); setCart([]); setLogs([]); }}
style={{ marginTop: '20px', padding: '12px 24px', background: '#7c4dff', border: 'none', borderRadius: '8px', color: '#fff', cursor: 'pointer' }}>
Powrot do sklepu
</button>
</div>
)}
</div>
);
};
export default StripeDemo;Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Stripe Checkout Session wymaga podania:
2. Jaki jest związek między Product a Price w Stripe?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Edytor kodu
Zaimplementuj proces płatności z Stripe Checkout w aplikacji Next.js
- Klikanie w kolejności
Uporządkuj kroki obsługi Stripe webhooks.
- Edytor kodu
Stwórz API route dla Checkout Session.