How to Integrate Stripe Payment with Node js & React js Part 2

11 months ago admin Nodejs

In the second part of this tutorial, we will move to the front end, we will create the Checkout component where we will display the stripe checkout form and handle the payment.


Install the package

First, let's install the packages that we need.

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

Create the CheckoutForm component

Inside components let's create a new folder 'payments' inside add a new component 'CheckoutForm' and add the code below inside.

                                                        
                                                                                                                        
import { PaymentElement } from "@stripe/react-stripe-js";
import { useState } from "react";
import { useStripe, useElements } from "@stripe/react-stripe-js";


export default function CheckoutForm() {
  const stripe = useStripe();
  const elements = useElements();
  const [message, setMessage] = useState(null);
  const [isProcessing, setIsProcessing] = useState(false);

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

    if (!stripe || !elements) {
      // Stripe.js has not yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    setIsProcessing(true);

    const response = await stripe.confirmPayment({
      elements,
      confirmParams: {
        // Make sure to change this to your payment completion page
      },
      redirect: "if_required",
    });

    if (
      (response.error && response.error.type === "card_error") ||
      (response.error && response.error.type === "validation_error")
    ) {
      setMessage(response.error.message);
    } else if (response.paymentIntent.id) {
      //display success message or redirect user
    }

    setIsProcessing(false);
  };

  return (
    <form id="payment-form" onSubmit={handleSubmit}>
      <PaymentElement id="payment-element" />
      <button disabled={isProcessing || !stripe || !elements} id="submit">
        <span id="button-text">
          {isProcessing ? "Processing ... " : "Pay now"}
        </span>
      </button>
      {/* Show any error or success messages */}
      {message && <div id="payment-message">{message}</div>}
    </form>
  );
}


Create the Stripe component

Next, let's create the Stripe component and add the code below inside.

                                                        
                                                                                                                        
import React, { useEffect, useState } from "react";
import { loadStripe } from "@stripe/stripe-js";
import { Elements } from "@stripe/react-stripe-js";
import CheckoutForm from "./CheckoutForm";
import axios from "axios";


export default function Stripe() {
  const stripePromise = loadStripe("Your Publishable Key");
  const [clientSecret, setClientSecret] = useState("");
  const total = 100 * 100;

  useEffect(() => {
    fetchClientSecret();
  }, []);

  const fetchClientSecret = async () => {
    try {
      const response = await axios.post('http://localhost:3001/order/pay', {
        amount: total,
      });
      setClientSecret(response.data.clientSecret);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <>
      {stripePromise && clientSecret && (
        <Elements stripe={stripePromise} options={{ clientSecret }}>
          <CheckoutForm />
        </Elements>
      )}
    </>
  );
}


Create the Checkout Component

Finally, let's create the Checkout component and add the code below inside.

                                                        
                                                                                                                        
import React from "react";
import Stripe from "./Stripe";

export default function Checkout() {

  return (
    <div className="container">
      <div className="row my-3">
        <div className="col-md-6 mx-auto">
          <Stripe />
        </div>
      </div>
    </div>
  );
}