ok ora colleghiamo a stripe e creiamo dei prodotti prova nella homepage devono essere…
- User
ok ora colleghiamo a stripe e creiamo dei prodotti prova nella homepage devono essere accessibili solo chi è registrato trammite firebase
- Assistant
ok ora colleghiamo a stripe e creiamo dei prodotti prova nella homepage devono essere accessibili solo chi è registrato trammite firebase
Per collegare Stripe al tuo progetto Next.js con TypeScript, integrare Firebase Authentication per limitare l'accesso ai prodotti e mostrare i prodotti di prova nella homepage, segui questa guida passo passo.
Crea un Account Stripe:
Installa Stripe: In terminale, esegui:
npm install @stripe/stripe-js stripe
o con Yarn:
yarn add @stripe/stripe-js stripe
Aggiungi la Chiave Segreta di Stripe alle Variabili d'Ambiente:
Modifica il file .env.local per includere la chiave segreta di Stripe:
STRIPE_SECRET_KEY=sk_test_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_test_...
Assicurati che Firebase Authentication sia configurato (come descritto nel messaggio precedente). Abilita il metodo di autenticazione "Email/Password" nella Firebase Console.
Next.js permette di creare API Routes. Creiamo un endpoint per recuperare i prodotti da Stripe.
pages/api/products.ts:
import type { NextApiRequest, NextApiResponse } from 'next';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2022-11-15',
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'GET') {
try {
const products = await stripe.products.list({
limit: 10, // Limite di prodotti da recuperare
active: true,
});
const prices = await stripe.prices.list({
limit: 10,
active: true,
});
// Combina prodotti e prezzi
const productsWithPrices = products.data.map(product => {
const price = prices.data.find(p => p.product === product.id);
return {
id: product.id,
name: product.name,
description: product.description,
image: product.images[0],
price: price ? price.unit_amount : null,
currency: price ? price.currency : null,
};
});
res.status(200).json(productsWithPrices);
} catch (error) {
res.status(500).json({ error: error.message });
}
} else {
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Modifichiamo la homepage (pages/index.tsx) per mostrare i prodotti solo agli utenti autenticati.
Crea un contesto per gestire l'autenticazione:
Crea un file src/context/AuthContext.tsx:
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { auth } from '../utils/firebase';
import { onAuthStateChanged, User } from 'firebase/auth';
interface AuthContextType {
user: User | null;
loading: boolean;
}
const AuthContext = createContext<AuthContextType>({ user: null, loading: true });
export const AuthProvider = ({ children }: { children: ReactNode }) => {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setUser(user);
setLoading(false);
});
return unsubscribe;
}, []);
return (
<AuthContext.Provider value={{ user, loading }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
Avvolgi l'applicazione con il contesto in pages/_app.tsx:
import { AppProps } from 'next/app';
import { AuthProvider } from '../context/AuthContext';
import '../styles/globals.css';
function MyApp({ Component, pageProps }: AppProps) {
return (
<AuthProvider>
<Component {...pageProps} />
</AuthProvider>
);
}
export default MyApp;
Modifica pages/index.tsx per mostrare i prodotti solo agli utenti autenticati:
import { useState, useEffect } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useAuth } from '../context/AuthContext';
interface Product {
id: string;
name: string;
description: string | null;
image: string | null;
price: number | null;
currency: string | null;
}
export default function Home() {
const { user, loading } = useAuth();
const [products, setProducts] = useState<Product[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (user) {
// Recupera i prodotti solo se l'utente è autenticato
fetch('/api/products')
.then((res) => res.json())
.then((data) => setProducts(data))
.catch((err) => setError(err.message));
}
}, [user]);
if (loading) {
return <div>Caricamento...</div>;
}
if (!user) {
return (
<div style={{ padding: '2rem', textAlign: 'center' }}>
<h1>Benvenuto!</h1>
<p>Devi essere autenticato per vedere i prodotti.</p>
<Link href="/login">
<a style={{ color: '#0070f3', textDecoration: 'underline' }}>Accedi</a>
</Link>
</div>
);
}
return (
<div style={{ padding: '2rem' }}>
<Head>
<title>Homepage di Prova</title>
<meta name="description" content="Una semplice homepage di prova con Next.js e TypeScript" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 style={{ color: '#333', marginBottom: '1rem' }}>Benvenuto, {user.email}!</h1>
<p style={{ color: '#555', marginBottom: '2rem' }}>
Ecco i prodotti disponibili:
</p>
{error && <p style={{ color: 'red' }}>Errore: {error}</p>}
<div style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}>
{products.map((product) => (
<div key={product.id} style={{ border: '1px solid #ddd', padding: '1rem', borderRadius: '4px' }}>
{product.image && <img src={product.image} alt={product.name} style={{ maxWidth: '100%' }} />}
<h2 style={{ fontSize: '1.2rem', margin: '0.5rem 0' }}>{product.name}</h2>
<p style={{ color: '#555' }}>{product.description}</p>
{product.price && (
<p style={{ fontWeight: 'bold' }}>
{(product.price / 100).toFixed(2)} {product.currency?.toUpperCase()}
</p>
)}
<button
style={{
padding: '8px 16px',
backgroundColor: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
}}
>
Acquista
</button>
</div>
))}
</div>
</main>
</div>
);
}
Aggiungiamo un pulsante di logout nella homepage per consentire agli utenti di disconnettersi.
Modifica pages/index.tsx aggiungendo il logout:
import { useState, useEffect } from 'react';
import Head from 'next/head';
import Link from 'next/link';
import { useAuth } from '../context/AuthContext';
import { signOut } from 'firebase/auth';
import { auth } from '../utils/firebase';
interface Product {
id: string;
name: string;
description: string | null;
image: string | null;
price: number | null;
currency: string | null;
}
export default function Home() {
const { user, loading } = useAuth();
const [products, setProducts] = useState<Product[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (user) {
fetch('/api/products')
.then((res) => res.json())
.then((data) => setProducts(data))
.catch((err) => setError(err.message));
}
}, [user]);
const handleLogout = async () => {
try {
await signOut(auth);
} catch (error) {
console.error('Errore durante il logout:', error);
}
};
if (loading) {
return <div>Caricamento...</div>;
}
if (!user) {
return (
<div style={{ padding: '2rem', textAlign: 'center' }}>
<h1>Benvenuto!</h1>
<p>Devi essere autenticato per vedere i prodotti.</p>
<Link href="/login">
<a style={{ color: '#0070f3', textDecoration: 'underline' }}>Accedi</a>
</Link>
</div>
);
}
return (
<div style={{ padding: '2rem' }}>
<Head>
<title>Homepage di Prova</title>
<meta name="description" content="Una semplice homepage di prova con Next.js e TypeScript" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem' }}>
<h1 style={{ color: '#333' }}>Benvenuto, {user.email}!</h1>
<button
onClick={handleLogout}
style={{
padding: '8px 16px',
backgroundColor: '#dc2626',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
}}
>
Logout
</button>
</div>
<p style={{ color: '#555', marginBottom: '2rem' }}>
Ecco i prodotti disponibili:
</p>
{error && <p style={{ color: 'red' }}>Errore: {error}</p>}
<div style={{ display: 'grid', gap: '1rem', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))' }}>
{products.map((product) => (
<div key={product.id} style={{ border: '1px solid #ddd', padding: '1rem', borderRadius: '4px' }}>
{product.image && <img src={product.image} alt={product.name} style={{ maxWidth: '100%' }} />}
<h2 style={{ fontSize: '1.2rem', margin: '0.5rem 0' }}>{product.name}</h2>
<p style={{ color: '#555' }}>{product.description}</p>
{product.price && (
<p style={{ fontWeight: 'bold' }}>
{(product.price / 100).toFixed(2)} {product.currency?.toUpperCase()}
</p>
)}
<button
style={{
padding: '8px 16px',
backgroundColor: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
}}
>
Acquista
</button>
</div>
))}
</div>
</main>
</div>
);
}
npm run dev
/login (creato nel messaggio precedente).Per implementare il pagamento, dobbiamo creare un checkout con Stripe. Ecco un esempio base:
Crea un'API per creare una sessione di checkout (pages/api/checkout.ts):
import type { NextApiRequest, NextApiResponse } from 'next';
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
apiVersion: '2022-11-15',
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
try {
const { priceId } = req.body;
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price: priceId,
quantity: 1,
},
],
mode: 'payment',
success_url: `${req.headers.origin}/success`,
cancel_url: `${req.headers.origin}/cancel`,
});
res.status(200).json({ id: session.id });
} catch (error) {
res.status(500).json({ error: error.message });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Modifica il pulsante "Acquista" nella homepage per avviare il checkout:
// Aggiungi questa importazione in cima a pages/index.tsx
import { loadStripe } from '@stripe/stripe-js';
// Inizializza Stripe
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY!);
// Modifica il pulsante "Acquista" nel map dei prodotti
const handleCheckout = async (priceId: string) => {
const stripe = await stripePromise;
const response = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ priceId }),
});
const session = await response.json();
await stripe?.redirectToCheckout({ sessionId: session.id });
};
// Nel map dei prodotti, modifica il pulsante:
<button
onClick={() => handleCheckout(product.priceId)} // Assicurati che priceId sia disponibile nei dati del prodotto
style={{
padding: '8px 16px',
backgroundColor: '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
}}
>
Acquista
</button>
Crea pagine di successo e cancellazione (pages/success.tsx e pages/cancel.tsx):
// pages/success.tsx
export default function Success() {
return (
<div style={{ padding: '2rem', textAlign: 'center' }}>
<h1>Pagamento Riuscito!</h1>
<p>Grazie per il tuo acquisto.</p>
</div>
);
}
// pages/cancel.tsx
export default function Cancel() {
return (
<div style={{ padding: '2rem', textAlign: 'center' }}>
<h1>Pagamento Annullato</h1>
<p>Hai annullato il pagamento. Torna alla homepage per riprovare.</p>
</div>
);
}
Ora hai:
Se hai bisogno di ulteriori funzionalità (es. gestione degli ordini, webhook di Stripe), fammelo sapere! 🚀