One of the simplest ways to integrate Stripe payments into your Next.js application is by leveraging Stripe Checkout. This is a pre-built, hosted checkout page that handles all the complexity of collecting payment information securely. Your primary task on the frontend is to initiate this process by redirecting your user to the Stripe Checkout URL.
The process typically involves these steps: the user clicks a 'Checkout' button, your frontend makes an API call to your backend to create a Stripe Checkout Session, and your backend returns the Checkout Session URL. Your frontend then redirects the user to this URL.
graph TD
A[User Clicks Checkout] --> B{Frontend Calls Backend API};
B --> C[Backend Creates Stripe Checkout Session];
C --> D[Backend Returns Checkout Session URL];
D --> E{Frontend Redirects User to URL};
E --> F[Stripe Checkout Page];
Let's break down how you'd implement the frontend part. First, you'll need a button in your React component that triggers the checkout process. This button will call a function that handles the API request to your backend.
import React from 'react';
function ProductPage() {
const handleCheckout = async () => {
// API call to your backend will go here
console.log('Initiating checkout...');
};
return (
<div>
<h1>Awesome Product</h1>
<p>$19.99</p>
<button onClick={handleCheckout}>Buy Now</button>
</div>
);
}
export default ProductPage;Next, you'll modify the handleCheckout function to make a POST request to an API endpoint on your Next.js server. This endpoint will be responsible for creating the Stripe Checkout Session. We'll assume you have an API route set up at /api/create-checkout-session.
import React from 'react';
function ProductPage() {
const handleCheckout = async () => {
try {
const response = await fetch('/api/create-checkout-session', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// You might send product details here if your backend needs them
// body: JSON.stringify({ productId: 'prod_123' }),
});
if (!response.ok) {
throw new Error('Failed to create checkout session');
}
const session = await response.json();
// The backend should return a URL for the checkout session
window.location.href = session.url;
} catch (error) {
console.error('Error during checkout:', error);
// Display an error message to the user
}
};
return (
<div>
<h1>Awesome Product</h1>
<p>$19.99</p>
<button onClick={handleCheckout}>Buy Now</button>
</div>
);
}
export default ProductPage;Finally, the response.json() will contain the session object, which crucially includes a url property. This url is the link to the hosted Stripe Checkout page. By setting window.location.href to this URL, you seamlessly redirect your user to Stripe's secure payment form.
Remember, the fetch request above assumes your backend will respond with a JSON object like {"url": "https://checkout.stripe.com/pay/cs_test_..."}. The exact structure will depend on your backend implementation, which we'll cover in the next section.