Integrating Stripe Payments with Next.js: A Step-by-Step Guide
Written on
Chapter 1: Introduction to Stripe Integration
Integrating Stripe is not a routine task; it’s something that, once set up correctly, often gets left alone until a change is necessary. I often find myself revisiting the Stripe checkout integration process and referring to the documentation. While this is helpful, navigating through extensive documentation can sometimes be overwhelming.
This guide is primarily for my own reference, filled with copy-paste code snippets to help set up Stripe in a Next.js environment. I've organized my notes into a clear tutorial that I hope others will find beneficial as well. 😁
Section 1.1: Prerequisites
This tutorial focuses specifically on integrating the checkout feature and does not cover subscriptions. It assumes a foundational knowledge of Next.js. If you require a beginner's guide or have questions, please leave a comment, and I’ll be happy to create additional resources. 😋
Section 1.2: Installing the Stripe NPM Package
To get started, you’ll need to install the Stripe npm package within your Next.js project. Run the following command in your terminal:
npm install stripe
This will add the latest version of the Stripe package to your project’s dependencies.
Section 1.3: Setting Up Your Stripe Account and Retrieving API Keys
Before using Stripe in your Next.js project, you must create a Stripe account and obtain your API keys. Follow these steps:
- Complete the signup process to create your account.
- Once your account is active, click on the "Developers" tab, then select "API Keys" from the left-hand menu.
- Your API keys will be displayed. Keep them secure, as they are essential for authenticating your Stripe API requests.
Section 1.4: Adding API Keys to Your Next.js Project
With your API keys ready, you need to include them in your Next.js project for API calls. One common way to do this is by using environment variables.
Create a .env file in your project’s root directory and add your API keys as follows:
STRIPE_PUBLISHABLE_KEY=pk_test_your_publishable_key
STRIPE_SECRET_KEY=sk_test_your_secret_key
Remember to replace "your_publishable_key" and "your_secret_key" with your actual API key values.
Section 1.5: Using the Stripe NPM Package in Your Project
Now that you have the Stripe npm package installed and your API keys configured, you can start making API calls. Below is an example of how to create a new customer:
import stripe from 'stripe';
const stripeClient = new stripe(process.env.STRIPE_SECRET_KEY);
async function createCustomer() {
const customer = await stripeClient.customers.create({
email: '[email protected]',});
console.log(customer);
}
createCustomer();
This code snippet creates a new customer with the provided email using the Stripe API. For more details on Stripe’s API methods, refer to the official documentation.
Section 1.6: Setting Up Stripe Checkout
To use the Stripe Checkout library, open the Next.js component where you want the checkout process to occur. Import the Stripe library at the top of your file:
import Stripe from 'stripe';
This gives you access to the Stripe object, enabling you to create a Stripe instance and interact with the API. To initiate a payment, you’ll need to create a Stripe Checkout session with the following details:
- The charge amount (in the smallest currency unit, e.g., cents for USD)
- A description of the product/service
- The currency for the payment
- A success URL for redirection after payment
- An optional cancel URL for users who choose to cancel
Here’s an example of creating a Stripe Checkout session:
const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY);
const session = await stripeClient.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
name: 'My Product',
description: 'A description of my product',
amount: 1000, // 10.00 USD in cents
currency: 'usd',
quantity: 1,
},
],
success_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
});
Once the session is created, you can use the session ID to trigger the payment process via the Stripe Checkout library. Implement a Stripe Checkout button in your component, setting the sessionId prop to the session ID you generated.
Section 1.7: Including the Checkout Script in Your Next.js Page
To add the Stripe Checkout script to your page, use the next/head component to ensure it’s included properly. Begin by importing the Head component:
import Head from 'next/head';
Then, use the Head component to insert the Stripe Checkout script into the HTML head:
<Head>
</Head>
This addition allows the Stripe Checkout library to be used on your page. Don't forget to include your Stripe publishable key in the StripeCheckout component when rendering it.
Section 1.8: Triggering the Checkout Process
To create a button that initiates the Stripe Checkout process, use the StripeCheckout component from the react-stripe-checkout library. Start by importing the component:
import StripeCheckout from 'react-stripe-checkout';
Next, define a function to handle the button click, which will begin the Stripe Checkout process:
function handleCheckout() {
// Start the Stripe Checkout process here
}
To trigger the process, set the sessionId prop on the StripeCheckout component to the ID of the created session. Here’s an example:
const stripeClient = new Stripe(process.env.STRIPE_SECRET_KEY);
async function handleCheckout() {
const session = await stripeClient.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [
{
name: 'My Product',
description: 'A description of my product',
amount: 1000, // 10.00 USD in cents
currency: 'usd',
quantity: 1,
},
],
success_url: 'http://localhost:3000/success',
cancel_url: 'http://localhost:3000/cancel',
});
// Set the sessionId prop on the StripeCheckout component
setSessionId(session.id);
}
Finally, render the StripeCheckout component to display a button that triggers the handleCheckout function. Be sure to set the stripeKey prop to your Stripe publishable key:
function MyComponent() {
const [sessionId, setSessionId] = useState(null);
return (
<>
Pay with Stripe
{sessionId && (
<StripeCheckout
stripeKey={process.env.STRIPE_PUBLISHABLE_KEY}
sessionId={sessionId}
/>
)}
</>
);
}
That’s all there is to it! Your button is now configured to start the Stripe Checkout process. Customers clicking the button will be directed to the Stripe Checkout page to enter their payment details and finalize their purchase.
Chapter 2: Video Tutorials
To further assist you in the integration process, here are some useful video tutorials.
This video titled "Set Up Payments With NextJS and Stripe" provides a comprehensive guide to setting up payment systems in your application.
In this video, "How to add Stripe payments to ANY Next.js 14 App! (Easy Tutorial for Beginners)", you'll find an easy-to-follow tutorial perfect for beginners looking to implement Stripe payments in their Next.js apps.