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

11 months 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 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...


How to Download a File from the Server Using Laravel and React js

In this tutorial, we will see how to download a file from the server using Laravel and React js, let...


How to Add a Class on Hover in React js

In this lesson, we will see how to add a class on hover in React js, let's assume that we have a boo...


Drag and Drop Image and File Upload Using React and Laravel

In this tutorial, we will see how to upload files using drag and drop in React js and Laravel, first...


API Authentication Using Laravel Sanctum and React js Part 3

In the third part of this tutorial, we will register and log in the user, get the access token, and...


API Authentication Using Laravel Sanctum and React js Part 2

In the second part of this tutorial, we will start handling the frontend first, we will create the r...


API Authentication Using Laravel Sanctum and React js Part 1

In today's tutorial, we are going to see how to create a token-based authentication system using Lar...


How to Update Nested Array with Hooks in React

In this lesson, we will see how to update nested array with hooks in React, let's assume that we hav...


How to Set the Loading State Only on a Specific Clicked Button in React

In this lesson, we will see how to set the loading state only on a specific clicked button in React,...


Create a Rest API in PHP and Consume it in React Part 5

In the fifth part of this tutorial, we will add routes to our application and finally, we will add s...