DEV Community

Sh Raj
Sh Raj

Posted on • Originally published at article.shade.cool

7 1 1 1 1

How to add Stripe payment functionality to Next.js App

How to add Stripe payment functionality using the Next.js App Router:

1. Set Up Your Stripe Account

  • Sign up at stripe.com.
  • Complete the setup process including adding business details and bank account.

2. Install Stripe Packages

  • Install the required Stripe packages in your Next.js project:

     npm install stripe @stripe/stripe-js @stripe/react-stripe-js
    

3. Create a Server-Side Route for Payment Intent

  • Use the Next.js App Router to create an API route for generating a payment intent.

     // app/api/create-payment-intent/route.js
     import Stripe from 'stripe';
    
     const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
    
     export async function POST(request) {
       const { amount } = await request.json();
    
       try {
         const paymentIntent = await stripe.paymentIntents.create({
           amount,
           currency: 'usd',
         });
    
         return new Response(JSON.stringify({ clientSecret: paymentIntent.client_secret }), {
           status: 200,
           headers: {
             'Content-Type': 'application/json',
           },
         });
       } catch (error) {
         return new Response(JSON.stringify({ error: error.message }), {
           status: 500,
           headers: {
             'Content-Type': 'application/json',
           },
         });
       }
     }
    

4. Create a Client-Side Payment Form

  • Set up a client-side form to collect payment information using Stripe Elements.

     // app/page.js
     import { useState, useEffect } from 'react';
     import { loadStripe } from '@stripe/stripe-js';
     import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
    
     const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY);
    
     function CheckoutForm({ clientSecret }) {
       const stripe = useStripe();
       const elements = useElements();
       const [error, setError] = useState(null);
       const [success, setSuccess] = useState(null);
    
       const handleSubmit = async (event) => {
         event.preventDefault();
    
         const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
           payment_method: {
             card: elements.getElement(CardElement),
           },
         });
    
         if (error) {
           setError(error.message);
         } else if (paymentIntent.status === 'succeeded') {
           setSuccess('Payment succeeded!');
         }
       };
    
       return (
         <form onSubmit={handleSubmit}>
           <CardElement />
           <button type="submit" disabled={!stripe}>Pay</button>
           {error && <div>{error}</div>}
           {success && <div>{success}</div>}
         </form>
       );
     }
    
     export default function Home() {
       const [clientSecret, setClientSecret] = useState('');
    
       useEffect(() => {
         fetch('/api/create-payment-intent', {
           method: 'POST',
           headers: { 'Content-Type': 'application/json' },
           body: JSON.stringify({ amount: 5000 }), // amount in cents
         })
           .then((res) => res.json())
           .then((data) => setClientSecret(data.clientSecret));
       }, []);
    
       return (
         clientSecret && (
           <Elements stripe={stripePromise} options={{ clientSecret }}>
             <CheckoutForm clientSecret={clientSecret} />
           </Elements>
         )
       );
     }
    

5. Testing and Deployment

  • Use Stripe's test card numbers to test the integration. For example, 4242 4242 4242 4242 is a valid test card number.
  • Once testing is complete, deploy your Next.js application and switch Stripe from test mode to live mode in the dashboard.

By following these steps, you can easily integrate Stripe payments into your Next.js application using the App Router. If you need further customization or encounter any issues, refer to Stripe's detailed documentation and API references.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
sh20raj profile image
Sh Raj

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay