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…


This content originally appeared on DEV Community and was authored by Sh Raj

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.


This content originally appeared on DEV Community and was authored by Sh Raj


Print Share Comment Cite Upload Translate Updates
APA

Sh Raj | Sciencx (2024-07-08T04:12:59+00:00) How to add Stripe payment functionality to Next.js App. Retrieved from https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/

MLA
" » How to add Stripe payment functionality to Next.js App." Sh Raj | Sciencx - Monday July 8, 2024, https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/
HARVARD
Sh Raj | Sciencx Monday July 8, 2024 » How to add Stripe payment functionality to Next.js App., viewed ,<https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/>
VANCOUVER
Sh Raj | Sciencx - » How to add Stripe payment functionality to Next.js App. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/
CHICAGO
" » How to add Stripe payment functionality to Next.js App." Sh Raj | Sciencx - Accessed . https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/
IEEE
" » How to add Stripe payment functionality to Next.js App." Sh Raj | Sciencx [Online]. Available: https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/. [Accessed: ]
rf:citation
» How to add Stripe payment functionality to Next.js App | Sh Raj | Sciencx | https://www.scien.cx/2024/07/08/how-to-add-stripe-payment-functionality-to-next-js-app/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.