Cours Next.js · Module 9: Intégrations et fonctions avancées
Next.js et Stripe - Un système de paiement complet
Dans cette leçon9
Dans la Métropole Quantum futuriste, où les transactions se déroulent instantanément et en toute sécurité, tu vas apprendre à intégrer Next.js avec Stripe - la plateforme de paiement en ligne la plus populaire. Cette combinaison te permet de construire des systèmes e-commerce professionnels avec une prise en charge complète des paiements.
Qu'est-ce que Stripe ?
Stripe est une plateforme de paiement en ligne complète qui propose :
- Paiements mondiaux - prise en charge de plus de 135 devises et moyens de paiement
- API pensée pour les développeurs - documentation et SDK clairs
- Sécurité - conformité PCI DSS Level 1
- Gestion des abonnements - prise en charge des abonnements
- Prévention de la fraude - protection avancée contre la fraude
- Webhooks - notifications d'événements en temps réel
Installation et configuration
Étape 1 : Créer un compte Stripe
- Inscris-toi sur stripe.com
- Va dans Dashboard → Developers → API keys
- Copie les clés :
- Publishable key - utilisée côté client
- Secret key - utilisée uniquement côté serveur
Étape 2 : Installation des packages
# Installe le SDK Stripe
npm install stripe @stripe/stripe-js @stripe/react-stripe-js
# Pour TypeScript, ajoute les types
npm install -D @types/stripeÉtape 3 : Configuration des variables d'environnement
Crée le fichier .env.local :
# Clés Stripe
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_SECRET_KEY=sk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
# App URL
NEXT_PUBLIC_APP_URL=http://localhost:3000Intégration de base
Étape 1 : Initialisation de Stripe
Crée une instance Stripe côté serveur :
// 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,
});Côté client :
// 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');
}
// Pattern singleton pour de meilleures performances
let stripePromise: Promise<any>;
export const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
}
return stripePromise;
};Étape 2 : Stripe Provider
Enveloppe l'application dans le 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>
);
}Implémentation du paiement
Checkout Session (recommandé)
Stripe Checkout est un formulaire de paiement prêt à l'emploi et hébergé :
// 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();
// Validation des items
if (!items || !Array.isArray(items) || items.length === 0) {
return NextResponse.json(
{ error: 'No items provided' },
{ status: 400 }
);
}
// Création des line items pour 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 utilise les centimes
},
quantity: item.quantity,
}));
// Création de la session 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 }
);
}
}Composant pour gérer le 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 {
// Création de la session 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);
}
// Redirection vers 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('Une erreur est survenue lors de la redirection vers le paiement');
} 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 ? 'Redirection...' : 'Aller au paiement'}
</button>
);
}Payment Element (formulaire personnalisé)
Pour un meilleur contrôle de l'UX, utilise le 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 || 'An error occurred');
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 ? 'Traitement...' : 'Payer'}
</button>
</form>
);
}API pour le 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();
// Validation du montant
if (!amount || amount <= 0) {
return NextResponse.json(
{ error: 'Invalid amount' },
{ status: 400 }
);
}
// Création du Payment Intent
const paymentIntent = await stripe.paymentIntents.create({
amount: Math.round(amount * 100), // Conversion en centimes
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
Les webhooks te permettent de recevoir des notifications sur les événements dans 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 }
);
}
// Gère les différents types d'événements
try {
switch (event.type) {
case 'checkout.session.completed': {
const session = event.data.object as Stripe.Checkout.Session;
// Gère le paiement terminé
await handleSuccessfulPayment(session);
break;
}
case 'payment_intent.succeeded': {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
// Met à jour le statut de la commande
console.log('Payment succeeded:', paymentIntent.id);
break;
}
case 'payment_intent.payment_failed': {
const paymentIntent = event.data.object as Stripe.PaymentIntent;
// Gère le paiement échoué
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;
// Gère les changements d'abonnement
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) {
// Implémente la logique après un paiement réussi
console.log('Payment successful for session:', session.id);
// Exemple : mets à jour le statut de la commande en base de données
// await updateOrderStatus(session.metadata.orderId, 'paid');
// Envoie un email de confirmation
// await sendConfirmationEmail(session.customer_email);
}
async function handleSubscriptionChange(subscription: Stripe.Subscription) {
// Implémentation de la logique pour l'abonnement
console.log('Subscription changed:', subscription.id);
}Abonnements
Implémentation d'un système d'abonnement :
// app/api/subscription/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { stripe } from '@/lib/stripe';
import { auth } from '@/lib/auth'; // Ta fonction d'authentification
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();
// Trouve ou crée le client dans 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;
}
// Crée une session checkout pour l'abonnement
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
Permets aux utilisateurs de gérer leurs abonnements :
// 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 }
);
}
// Trouve le client
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 }
);
}
// Crée une session 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 }
);
}
}Sécurité
1. Validation côté serveur
Valide toujours les données côté serveur :
// 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),
});
// Utilisation dans une route API
const validatedData = checkoutSchema.parse(await request.json());2. Rate limiting
Protège l'API contre les abus :
// 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. Sécurité des webhooks
Vérifie toujours les signatures des webhooks :
// Utilise stripe.webhooks.constructEvent() comme montré plus haut
// En complément, tu peux ajouter une whitelist d'IP
const allowedIPs = [
'3.18.12.63',
'3.130.192.231',
// Liste complète : https://stripe.com/docs/ips
];Tests
Mode test
Stripe propose un mode test avec des cartes de test :
// Cartes de test populaires
const testCards = {
success: '4242424242424242',
decline: '4000000000000002',
authRequired: '4000002500003155',
insufficientFunds: '4000000000009995',
};Tester les webhooks en local
Utilise le Stripe CLI :
# Installation
brew install stripe/stripe-cli/stripe
# Connexion
stripe login
# Redirige les webhooks vers le serveur local
stripe listen --forward-to localhost:3000/api/webhooks/stripe
# Teste le webhook
stripe trigger payment_intent.succeededRésumé
Intégrer Next.js avec Stripe offre de puissantes capacités pour construire des systèmes de paiement. Les éléments clés sont :
- Checkout Session - pour une implémentation rapide
- Payment Element - pour une UX personnalisée
- Webhooks - pour la fiabilité
- Sécurité - validation et rate limiting
- Tests - mode test et Stripe CLI
Cette combinaison te permet de construire des applications e-commerce professionnelles, des SaaS avec abonnements, des marketplaces, et bien plus encore.
Code de cette leçon : 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: 'Protection avancée des données', price: 4999, image: '' },
{ id: 'prod_2', name: 'Neural Interface v3', description: 'Interface de programmation IA', price: 9999, image: '' },
{ id: 'prod_3', name: 'Cyber Toolkit', description: 'Boîte à outils développeur', price: 2499, image: '' },
{ id: 'prod_4', name: 'Data Stream Engine', description: 'Moteur de traitement de données', 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 - Création de la session Stripe...');
await new Promise(r => setTimeout(r, 500));
addLog('stripe.checkout.sessions.create({ mode: "payment" })');
await new Promise(r => setTimeout(r, 400));
addLog('Session créée : cs_live_a1B2c3D4...');
await new Promise(r => setTimeout(r, 300));
addLog('Redirection vers Stripe Checkout...');
await new Promise(r => setTimeout(r, 600));
addLog('Paiement réussi ! session.payment_status : "paid"');
await new Promise(r => setTimeout(r, 300));
addLog('Webhook reçu : checkout.session.completed');
addLog('Commande traitée. Redirection vers la page de succès...');
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' }}>
Ajouter au panier
</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' }}>Panier ({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>Total :</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' }}>
Passer au paiement
</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' }}>Total : <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 ? 'Traitement...' : 'Payer avec 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' }}>Paiement terminé !</h2>
<p style={{ color: '#888' }}>La commande a été traitée avec succès.</p>
<button onClick={() => { setStep('shop'); setCart([]); setLogs([]); }}
style={{ marginTop: '20px', padding: '12px 24px', background: '#7c4dff', border: 'none', borderRadius: '8px', color: '#fff', cursor: 'pointer' }}>
Retour à la boutique
</button>
</div>
)}
</div>
);
};
export default StripeDemo;Entrées de la documentation utilisées dans cette leçon
Tu as repéré une erreur dans cette leçon ?
Teste tes connaissances
Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.
1. Une Stripe Checkout Session nécessite :
2. Quelle est la relation entre Product et Price dans Stripe ?
Voici 2 des 3 questions de cette leçon. Réponds aux autres dans le jeu.
Tâches pratiques dans le jeu
- Éditeur de code
Implémente le processus de paiement avec Stripe Checkout dans une application Next.js
- Clique dans l'ordre
Remets dans l'ordre les étapes du traitement des webhooks Stripe.
- Éditeur de code
Crée une route API pour la Checkout Session.