Section

Creating a Basic Checkout Flow

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

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:

  1. 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
  1. 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 });
};
  1. 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>
  );
}
  1. Create success and cancel pages to inform the user about the outcome of their payment.
// pages/success.js
import { useRouter } from 'next/router';

export default function Success() {
  const router = useRouter();
  const { session_id } = router.query;

  return (
    <div>
      <h1>Payment Successful!</h1>
      <p>Thank you for your order. Your session ID is: {session_id}</p>
    </div>
  );
}
// pages/cancel.js
export default function Cancel() {
  return (
    <div>
      <h1>Payment Cancelled</h1>
      <p>Your payment was cancelled. You can try again later.</p>
    </div>
  );
}

This flow involves client-side actions to initiate the checkout and server-side logic to securely create the Stripe Checkout session. The redirect to Stripe's hosted page ensures a secure and PCI-compliant payment experience without you having to handle sensitive card details.

graph TD
    A[User Clicks 'Buy'] --> B{Frontend: Fetch Checkout Session ID};
    B --> C[API Route: Create Stripe Checkout Session];
    C --> D{Stripe API};
    D --> E[Checkout Session ID Returned to Frontend];
    E --> F[Frontend: Redirect to Stripe Checkout];
    F --> G[Stripe Checkout Page];
    G -- Successful Payment --> H[User Redirected to Success Page];
    G -- Cancelled Payment --> I[User Redirected to Cancel Page];