The heart of any Stripe integration lies in creating a 'checkout session'. This session represents a customer's intention to pay for specific items and guides them through the Stripe Checkout payment flow. For security and to manage sensitive information, creating a checkout session is always done on your server.
To begin, you'll need to install the Stripe Node.js library if you haven't already. This library provides convenient methods for interacting with the Stripe API.
npm install stripe
# or
yarn add stripeNext, initialize the Stripe library with your secret API key. It's crucial to use your 'secret' key here, not your 'publishable' key, as this operation is performed on the server. You should store your secret key securely, typically using environment variables.
const stripe = require('stripe')('sk_test_YOUR_SECRET_KEY');
// It's best practice to load your secret key from an environment variable:
// const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);Now, let's create a function that will handle the creation of a Stripe Checkout session. This function will typically be part of an API route in your Next.js application.
export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'T-shirt',
},
unit_amount: 2000, // amount in cents
},
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 });
} catch (err) {
res.status(500).json({ error: err.message });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end('Method Not Allowed');
}
}Let's break down the key parameters used in stripe.checkout.sessions.create():
payment_method_types: An array specifying the payment methods you want to accept. 'card' is the most common for basic setups.line_items: An array of objects, each representing an item in the customer's cart. Each item requiresprice_data(currency, product name, and amount in cents) andquantity.mode: 'payment' for one-time purchases, or 'subscription' for recurring payments.success_url: The URL Stripe will redirect the customer to after a successful payment. You can use the{CHECKOUT_SESSION_ID}placeholder to dynamically include the session ID in the URL, which can be useful for confirming the order on your backend.cancel_url: The URL Stripe will redirect the customer to if they cancel the payment process.