Web Developers - 19-Process Payments with Stripe Checkout using Next.js API Routes
Process Payments with Stripe Checkout Using Next.js API Routes
In today’s digital landscape, integrating payment processing into web applications is crucial for developers. Stripe is a powerful payment processing platform that simplifies this process, and when paired with Next.js, it creates a seamless way to handle payments. In this blog post, we will explore how to process payments using Stripe Checkout with Next.js API Routes.
What You Will Learn
By the end of this tutorial, you will:
- Understand how to set up a Stripe account
- Create a Next.js application
- Use API routes to handle payment processing
- Implement Stripe Checkout in your application
Prerequisites
Before we begin, ensure you have the following:
- Basic knowledge of JavaScript and React
- Node.js installed on your machine
- A Stripe account (you can sign up for free)
Step 1: Setting Up Your Stripe Account
- Sign Up for Stripe: Go to Stripe's website and create an account.
- Get Your API Keys: After logging in, navigate to the Developer section in the dashboard and copy your test API keys (Publishable Key and Secret Key).
Step 2: Creating a Next.js Application
To get started, we need to create a Next.js application.
Open your terminal and run the following command:
npx create-next-app@latest stripe-checkout-demoChange into the project directory:
cd stripe-checkout-demoInstall the Stripe library:
npm install stripe
Step 3: Setting Up API Routes
Next.js allows you to create API routes to handle server-side logic. We will create an API route to manage payments.
- Create a new directory called
pages/apiif it doesn't already exist. - Inside the
apidirectory, create a file namedcheckout.js.
The Checkout API Route
Open checkout.js and add the following code:
// pages/api/checkout.js
import Stripe from 'stripe';
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
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: req.body.items,
mode: 'payment',
success_url: `${req.headers.origin}/success`,
cancel_url: `${req.headers.origin}/cancel`,
});
res.status(200).json({ id: session.id });
} catch (error) {
res.status(500).json({ error: error.message });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Explanation
- Import Stripe: We import the Stripe library and initialize it with the secret key.
- Handle POST Requests: We define a handler that listens for POST requests.
- Create a Checkout Session: We create a checkout session with items passed in the request body.
- Respond with Session ID: The session ID is returned to the client for further processing.
Step 4: Creating the Checkout Page
Next, we will create a simple checkout page to allow users to make payments.
- Create a new file named
checkout.jsin thepagesdirectory.
The Checkout Page Code
Open checkout.js and add the following code:
// pages/checkout.js
import { useState } from 'react';
const Checkout = () => {
const [loading, setLoading] = useState(false);
const handleCheckout = async () => {
setLoading(true);
const response = await fetch('/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
items: [
{
price_data: {
currency: 'usd',
product_data: {
name: 'Awesome Product',
},
unit_amount: 2000, // $20.00
},
quantity: 1,
},
],
}),
});
const session = await response.json();
const stripe = await getStripe();
await stripe.redirectToCheckout({ sessionId: session.id });
setLoading(false);
};
return (
<div>
<h1>Checkout</h1>
<button onClick={handleCheckout} disabled={loading}>
{loading ? 'Processing...' : 'Checkout'}
</button>
</div>
);
};
export default Checkout;
Explanation
- State Management: We use React’s
useStateto manage loading state. - Handle Checkout: The
handleCheckoutfunction fetches the checkout session from the API and redirects the user to Stripe Checkout. - Button: A simple button triggers the checkout process.
Step 5: Using Stripe's JavaScript Library
To finalize the setup, you need to install the Stripe.js library to handle the redirection to the Stripe Checkout page.
Install Stripe.js:
npm install @stripe/stripe-jsCreate a utility function to initialize Stripe:
// utils/getStripe.js
import { loadStripe } from '@stripe/stripe-js';
let stripePromise;
const getStripe = () => {
if (!stripePromise) {
stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
}
return stripePromise;
};
export default getStripe;
Step 6: Environment Variables
Make sure to set your environment variables in a .env.local file in your project root:
STRIPE_SECRET_KEY=your_secret_key
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=your_publishable_key
Step 7: Running the Application
Start your Next.js application:
npm run devVisit
http://localhost:3000/checkoutto see your checkout page in action.
Conclusion
In this tutorial, we successfully integrated Stripe Checkout with a Next.js application using API routes. You learned how to set up a Stripe account, create a Next.js application, and handle payments using API routes.
With this foundation, you can expand your application further, add more products, and incorporate advanced features provided by Stripe.
Happy coding!
Connect with SkillBakery Studios
Explore more tutorials, tools, and resources:
Posted by SkillBakery Studios


No comments:
Post a Comment