Adding stripe payment in react application

Author
April 06, 2022

In this article i will explain you how you can add stripe payment to your react application

Step 1: Install required package for stripe

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

Step 2: Go to your stripe account and get the public stripe key

  • Login to your stripe account

  • Go to developers option in header

  • Click on API Keys on left panel

  • You will be able to see your publishable key

stripe-payment

Step 3: Copy paste the following code in your react functional component

  • Replace your publishable key with the publishable key which you got in the above steps
import React from "react";
import ReactDOM from "react-dom";
import { loadStripe } from "@stripe/stripe-js";
import {
  CardElement,
  Elements,
  useStripe,
  useElements,
} from "@stripe/react-stripe-js";

const CheckoutForm = () => {
  const stripe = useStripe();
  const elements = useElements();

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (elements == null) {
      return;
    }

    const { error, paymentMethod } = await stripe.createPaymentMethod({
      type: "card",
      card: elements.getElement(CardElement),
    });
  };

  return (
    <form onSubmit={handleSubmit}>
      <CardElement />
      <button type="submit" disabled={!stripe || !elements}>
        Pay
      </button>
    </form>
  );
};

const stripePromise = loadStripe("stripe_publishable_key");

const StripeCheckOut = () => {
  return (
    <Elements stripe={stripePromise}>
      <CheckoutForm />
    </Elements>
  );
};

export default StripeCheckOut;