How to Integrate Stripe Payment with React js & Laravel 10 Part 2

1 year ago admin Reactjs

In the second part of this tutorial, we are going to handle the front end, we will create the CheckoutForm, OrderSummary, and Stripe components and will see how to integrate the Stripe payment inside the OrderSummary component.


Create the CheckoutForm component

So let's create the CheckoutForm component 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';
import { BASE_URL } from '../../Helpers/Url';

export default function Stripe({total}) {
    const stripePromise = loadStripe('Your Publishable Key');
    const [clientSecret, setClientSecret] = useState("");
    const items = [{ amount: total }];

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

    const fetchClientSecret = async () => {
        try {
            const response = await axios.post(`${BASE_URL}order/pay`, {
                items,
            });
            setClientSecret(response.data.clientSecret);
        } catch (error) {
            console.log(error);
        }
    }
    
    return (
        <>
            {
                stripePromise && clientSecret && <Elements stripe={stripePromise} options={{clientSecret}}>
                    <CheckoutForm />
                </Elements>
            }
        </>
    );
}


Create the OrderSummary Component

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

                                                        
                                                                                                                        
import React from 'react';
import { useSelector } from 'react-redux';
import Stripe from './Stripe';

export default function OrderSummary() {
    const { cartItems } = useSelector(state => state.cart);
    let amount = cartItems.reduce((acc,item) => acc += item.price * item.quantity, 0);

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

Related Tuorials

How to Add Bootstrap 5 Icons in React

In this lesson, we will see how to add Bootstrap 5 Icons in React, we'll walk through the steps to a...


How to Add Bootstrap 5 in React

In this lesson, we will see how to add Bootstrap 5 in React, we'll walk through the steps to add Boo...


How to Access Images from the Assets folder in React

In this lesson, we will see how to access images from the assets folder in React. When working...


How to Listen to a Specific Word in React

In this lesson, we will see how to listen to a specific word in React. Sometimes, when working...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 5

In the last part of this tutorial, we will display the cart items, add the ability to increment/decr...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 4

In the fourth part of this tutorial, we will fetch and display all the products on the home page, an...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 3

In the third part of this tutorial, we will start coding the front end, first, we will install the p...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 2

In the second part of this tutorial, we will create the product and payment controllers, and later w...


Build a Shopping Cart Using React js Laravel 11 & Stripe Payment Gateway Part 1

In this tutorial, we will create a shopping cart using React js Laravel 11 and Stripe payment gatewa...


How to Use Rich Text Editor in React js

In this lesson, we will see how to use rich text editor in React JS, let's assume that we have a com...