Explaining the Payment Process Component in a React Application

in blurt •  last year 

The PaymentProcess component, which is a part of a React application, will be examined and explained in this blog post's introduction. We'll dissect the code, go over its operation, and give a rundown of the primary ideas and technologies employed.

src
Overview: The application's payment procedure is handled by the PaymentProcess component. To support payment transactions, it engages with external APIs like Razorpay. To make accepting payments easy for users, the component combines a variety of React and Material-UI components. Let's examine the code in detail and comprehend each of its portions.

Code Explanation:

Import Statements:

// Import required modules and components
import React, { useContext, useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import {
  Backdrop,
  Box,
  Button,
  CircularProgress,
  Grid,
  Snackbar,
  Typography,
} from "@mui/material";
import MuiAlert from "@mui/material/Alert";
import { ShoppingBagOutlined } from "@mui/icons-material";
import CourseInfo from "./CourseInfo";
import Cookies from "js-cookie";
import TagManager from "react-gtm-module";
import {
  fetchGetPaymentClientID,
  removeCookies,
} from "../../Redux/Slices/authSlice";
import {
  endingRegexOfCookiesMatch,
  startingRegexOfCookiesMatch,
} from "../../constants/getCookieRegex";

The import statements at the beginning of the code snippet bring in all the necessary modules, components, and utilities required for the PaymentProcess component. These include React, React Router, Material-UI components such as Box, Button, Grid, Snackbar, and Typography, as well as custom components like CourseInfo. Additionally, it imports functions and constants from various files to handle authentication, cookies, and regular expressions.

Functional Component Definition:

const PaymentProcess = (props) => {
  // Component logic goes here
};

The PaymentProcess component is defined as a functional component using an arrow function syntax. It receives props as a parameter, allowing it to receive data or functions from its parent component.

State and Context Initialization:

const navigate = useNavigate();
const dispatch = useDispatch();
const [openBackDrop, setOpenBackDrop] = useState(false);
const authToken = Cookies.get("jwtTokenCredentialsAccessTokenStudent");
const courseName = Cookies.get("courseName");
const {
  getStudentPrimaryDetails,
  firstName,
  middleName,
  lastName,
  email,
  mobileNumber,
  addressLine1ForStepChange,
  studentId,
} = useContext(StudentFormContext);

In this section, several state variables are initialized using the useState hook. These variables include openBackDrop, which controls the visibility of a backdrop during payment processing. The navigate and dispatch variables are initialized using the useNavigate and useDispatch hooks, respectively.

The component also accesses the StudentFormContext using the useContext hook to retrieve student details required for payment processing. These details are deconstructed from the context object and assigned to respective variables.


src

useEffect Hooks:

useEffect(() => {
  TagManager.initialize({ gtmId: "GTM-T847FNF" });
}, []);

useEffect(() => {
  getStudentPrimaryDetails(courseName);
  // eslint-disable-next-line react-hooks/exhaustive-deps
}, [courseName]);

useEffect(() => {
  dispatch(fetchGetPaymentClientID(authToken));
}, [authToken, dispatch]);

The useEffect hook is used to perform side effects such as initializing the TagManager, fetching student primary details, and fetching the payment client ID. The first useEffect hook initializes the TagManager with a specific GTM ID.

The second useEffect hook fetches the student's primary details by calling the getStudentPrimaryDetails function, which takes the courseName as a parameter. This hook ensures that the primary details are fetched whenever the courseName changes.

The third useEffect hook dispatches the fetchGetPaymentClientID action, passing the authToken as a dependency. This ensures that the payment client ID is fetched whenever the authToken changes.

Redux Integration:

const { razorPayKeyId } = useSelector((state) => state.auth);

The component uses the useSelector hook to access the Redux store. It retrieves the razorPayKeyId from the auth state, which is later used in the payment process. By accessing the store state using useSelector, the component can retrieve the required data.

Event Handlers:

const handleUpdatePayment = async () => {
  setOpenBackDrop(true);
  const token = Cookies.get("jwtTokenCredentialsAccessTokenStudent");

  const response = await fetch(`/api/v1/student/${studentId}/payment/order`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      paymentMode: "razorpay",
    }),
  });

  const data = await response.json();
  const orderId = data.orderId;

  const options = {
    key: razorPayKeyId,
    amount: data.amount,
    currency: "INR",
    order_id: orderId,
    name: `${firstName} ${lastName}`,
    email: email,
    contact: mobileNumber,
    description: `Enrollment for ${courseName}`,
    callback_url: `/payment/${studentId}/success`,
    prefill: {
      name: `${firstName} ${lastName}`,
      email: email,
      contact: mobileNumber,
    },
    theme: {
      color: "#ff8a00",
    },
  };

  const razorpay = new window.Razorpay(options);
  razorpay.open();

  razorpay.on("payment.success", async function () {
    setOpenBackDrop(false);
    await fetch(`/api/v1/student/${studentId}/payment/success`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        paymentMode: "razorpay",
        orderId: orderId,
      }),
    });

    removeCookies(startingRegexOfCookiesMatch, endingRegexOfCookiesMatch);
    navigate(`/payment/${studentId}/success`);
  });

  razorpay.on("payment.error", function () {
    setOpenBackDrop(false);
    navigate(`/payment/${studentId}/failed`);
  });
};

The handleUpdatePayment function is responsible for creating an order and initiating the payment process using Razorpay. When called, it sets openBackDrop to true, which displays a loading backdrop to indicate payment processing.

It then sends a POST request to the server to create an order by using the /api/v1/student/${studentId}/payment/order endpoint. The request includes the payment mode (razorpay) in the request body.

Upon receiving the response, it extracts the order ID and constructs the options object required by Razorpay. This object includes details such as the payment amount, currency, order ID, customer information, and callback URL.


src

Conclusion:
The PaymentProcess component plays a crucial role in facilitating the payment process within a React application. It integrates external APIs, manages state and context, and leverages Redux for global state management. By understanding the code and its different sections, developers can gain insight into how payment functionality can be implemented in a React application.

Remember to consult the complete codebase for a comprehensive understanding and proper implementation

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE BLURT!