The most common way to integrate Stripe into your Next.js application is by using Stripe Checkout. Stripe Checkout is a pre-built, mobile-responsive checkout page that handles everything from collecting payment details to processing the transaction. It's the quickest and easiest way to get started with payments.
To create a basic checkout flow, we'll need to perform a few key steps:
- Install the Stripe Node.js library on your server and the Stripe.js SDK in your frontend.
npm install stripe @stripe/stripe-js
npx yarn add stripe @stripe/stripe-js- Set up an API route in your Next.js application to create a Stripe Checkout Session on the server.
// pages/api/create-checkout-session.js
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
export default async (req, res) => {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
unit_amount: 2000, // $20.00
product_data: {
name: 'Awesome T-Shirt',
description: 'A comfy and stylish t-shirt'
},
},
quantity: 1,
},
],
mode: 'payment',
success_url: `${req.headers.origin}/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/cancel`,
});
res.status(200).json({ id: session.id });
};- On your frontend, create a button that, when clicked, will fetch the Checkout Session ID from your API route and redirect the user to Stripe Checkout.
// pages/index.js
import { loadStripe } from '@stripe/stripe-js';
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLIC_KEY);
export default function Home() {
const createCheckoutSession = async () => {
const stripe = await stripePromise;
const res = await fetch('/api/create-checkout-session', {
method: 'POST',
});
const session = await res.json();
const result = await stripe.redirectToCheckout({
sessionId: session.id,
});
if (result.error) {
alert(result.error.message);
}
};
return (
<div>
<h1>My Awesome Store</h1>
<button onClick={createCheckoutSession}>Buy T-Shirt</button>
</div>
);
}