Adding Stripe Payment to Your Next.js App: A Step-by-step Tutorial



Introduction:

In this tutorial, we will be integrating Stripe payment functionality into a Next.js application. Stripe is a popular platform that provides a suite of tools for online payment processing. It allows businesses to easily accept and process payments from customers. By integrating Stripe into our Next.js application, we will be able to accept payments and perform other related tasks such as creating subscriptions, handling webhooks and much more.


Setting up a Stripe account:

Before we begin, you'll need to sign up for a Stripe account if you don't have one already. Once you have an account, you can find your API keys in the Stripe dashboard. We will be using these keys to connect to the Stripe API from our Next.js application.


Installing the Stripe package:

Next, we will install the Stripe package in our Next.js application. We can do this by running npm install stripe in our project directory. This package provides a JavaScript library that we can use to interact with the Stripe API in our application.


Setting up the server-side:

Next, we need to set up the server-side of our application to handle the payment process. In the server.js file, or a seperate folder called server, we will import the stripe library, and initialize it with our Stripe secret key.

Then we'll create an endpoint for creating paymentIntents and handling webhook events.


const stripe = require('stripe')('YOUR_SECRET_KEY');

server.post('/api/create-payment-intent', async (req, res) => {

  const { amount } = req.body;


  try {

    const paymentIntent = await stripe.paymentIntents.create({

      amount: amount * 100,

      currency: 'usd'

    });

    res.json({ client_secret: paymentIntent.client_secret });

  } catch (err) {

    res.status(500).json({ statusCode: 500, message: err.message });

  }

});

In this example, we create an endpoint '/api/create-payment-intent' that handles the creation of a PaymentIntent, the amount is passed from the client and is used to create the PaymentIntent and the client_secret returned.

Setting up the client-side:

Now that we have set up our server-side, we can now move on to the client-side and use the Stripe.js library to handle the Payment process.

We need to import the Stripe.js library to the client side by adding a script to the head of the HTML file in pages/_document.js :


<script src="https://js.stripe.com/v3/"></script>


Next, we will import the library in a component and use it to handle the Payment process.

For example, we can create a payment component that handles the submission of the payment form, and the creation of the PaymentIntent on the server side:


import { useState } from 'react';

import axios from 'axios';

import { useEffect } from 'react';

import { loadStripe } from '@stripe/stripe-js';

const stripePromise = loadStripe('YOUR_PUBLISHABLE_KEY');


const Payment = () => {

const [amount, setAmount] = useState(0);

const [error, setError] = useState(null);

const [clientSecret, setClientSecret] = useState(null);


useEffect(() => {

async function createPaymentIntent() {

try {

const { data } = await axios.post('/api/create-payment-intent', { amount });

setClientSecret(data.client_secret);

} catch (err) {

setError(err.message);

}

}

if (amount > 0) {

createPaymentIntent();

}

}, [amount]);


const handleSubmit = async (event) => {

event.preventDefault();

setError(null);


const stripe = await stripePromise;

const { error } = await stripe.confirmCardPayment(clientSecret, {

  payment_method: {

    card: cardElement,

    billing_details: {

      name: event.target.name.value

    }

  }

});


if (error) {

  setError(error.message);

} else {

  // payment succeeded

}

};


return (

<form onSubmit={handleSubmit}>

<label>

Amount:

<input

type="number"

value={amount}

onChange={(e) => setAmount(e.target.value)}

/>

</label>

<label>

Name:

<input type="text" placeholder="Name" name="name" required />

</label>

<label>

Credit Card:

<CardElement id="card-element" options={CARD_ELEMENT_OPTIONS} />

</label>

{error && <p style={{ color: 'red' }}>{error}</p>}

<button type="submit">Pay</button>

</form>

);

};

export default Payment;


In this code snippet, we use the `useEffect` hook to create a PaymentIntent on the server-side when the amount changes, also we handle the form submission, and use the stripePromise to confirm the payment and get the card details.


Conclusion:

   In this tutorial, we have seen how to add Stripe payment functionality to a Next.js application. We've covered how to set up a Stripe account, install the Stripe package, set up the server-side and the client-side. By following the steps outlined in this tutorial, you can easily add payment functionality to your Next.js applications and handle various payments related tasks.

Reactions

Post a Comment

0 Comments