How To Use Stripe Payment In React js

In this article, we learn how to use Stripe payment in our React app.

First open react project and install stripe dependency.

npm install @stripe/stripe-js

In App.js file import loadStripe from the stripe.

Also, we need to create an account in stripe for the publishable key and price key.

Now for stripe payment define the publishable key in stripePromise.

const stripePromise = loadStripe('YOUR PUBLISHABLE KEY')

For checkout need to create redirectToCheckout and inside that lineItems, mode, cancleUrl, successUrl… define. In lineItems, we need to define price key and quality…

const { error } = await stripe.redirectToCheckout({
  lineItems: [
    {
      price: 'YOUR PRICE KEY',
      quantity: 1,
    }
  ],
  mode: 'payment',
  cancelUrl: window.location.origin,
  successUrl: `${window.location.origin}/thankyou`,
})

If it gives some error then set the flag and show them otherwise payment continues.

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

Now we need a button for the payment method so take a button and give them a click event.

<button role='link' onClick={handleClick} disabled={loading}> Go to Checkout </button>

Now my App.js looks like this,

import './App.css';
import { useState } from 'react'
import { loadStripe } from '@stripe/stripe-js';

const stripePromise = loadStripe('YOUR PUBLISHABLE KEY')

function App() {
  const [stripeError, setStripeError] = useState()
  const [loading, setLoading] = useState()

  const handleClick = async () => {
    setLoading(true)
    const stripe = await stripePromise
    const { error } = await stripe.redirectToCheckout({
      lineItems: [
        {
          price: 'YOUR PRICE KEY',
          quantity: 1
        }
      ],
      mode: 'payment',
      cancelUrl: window.location.origin,
      successUrl: `${window.location.origin}/thankyou`,
    })
    if (error) {
      setLoading(false)
      setStripeError(error)
    }
  }

  return (
    <div className="button">
      {stripeError && <p style={{ color: 'red' }}>{stripeError}</p>}
      <button role='link' onClick={handleClick} disabled={loading}>
        Go to Checkout
      </button>
    </div>
  );
}

export default App;

Output:-

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories