If you’re a developer looking to provide seamless payment experiences for your users within your React application, integrating a payment gateway like Cashfree can be a game-changer. In this guide, we’ll walk you through the process of integrating Cashfree Payment Gateway into your React application, step by step.

Introduction to Online Payments

Online payments are a convenient way to pay for items or services you want to buy on the internet. Instead of using cash or a credit card in person, you can make payments right from your computer or phone. Payment gateways like Cashfree help make these online transactions secure and easy.

Imagine you’re playing your favorite video game and you want to buy a new outfit for your character. Instead of going to a store with cash, you can use online payments to buy the outfit right from the game. It’s like having a digital wallet full of money that you can spend without ever leaving your game!

Payment gateways like Cashfree act as the bridge between the money in your digital wallet and the store you want to buy from online. They make sure your payments are processed quickly and securely so you can enjoy your purchases without any worries.

Now that you know what online payments are and why payment gateways are important, let’s dive into how Cashfree makes it all possible.

How to Integrate Cashfree Payment Gateway in React Js

so let’s start the full process of How to Integrate Cashfree Payment Gateway in React Js

Step 1

Download Your Key from Cashfree Dashboard

Step 2

Setup Client using below Command-List

npm create vite@latest
JavaScript

after installing Vite install a Cashfree Package in the Client

npm i @cashfreepayments/cashfree-js
JavaScript

after this I will show you fully my client code below

import { useState } from 'react'
import axios from "axios"
import {load} from '@cashfreepayments/cashfree-js'


function App() {

  let cashfree;

  let insitialzeSDK = async function () {

    cashfree = await load({
      mode: "sandbox",
    })
  }

  insitialzeSDK()

  const [orderId, setOrderId] = useState("")



  const getSessionId = async () => {
    try {
      let res = await axios.get("http://localhost:8000/payment")
      
      if(res.data && res.data.payment_session_id){

        console.log(res.data)
        setOrderId(res.data.order_id)
        return res.data.payment_session_id
      }


    } catch (error) {
      console.log(error)
    }
  }

  const verifyPayment = async () => {
    try {
      
      let res = await axios.post("http://localhost:8000/verify", {
        orderId: orderId
      })

      if(res && res.data){
        alert("payment verified")
      }

    } catch (error) {
      console.log(error)
    }
  }

  const handleClick = async (e) => {
    e.preventDefault()
    try {

      let sessionId = await getSessionId()
      let checkoutOptions = {
        paymentSessionId : sessionId,
        redirectTarget:"_modal",
      }

      cashfree.checkout(checkoutOptions).then((res) => {
        console.log("payment initialized")

        verifyPayment(orderId)
      })


    } catch (error) {
      console.log(error)
    }

  }
  return (
    <>

      <h1>Cashfree payment getway</h1>
      <div className="card">
        <button onClick={handleClick}>
          Pay now
        </button>

      </div>

    </>
  )
}

export default App
JavaScript

Step 3

Setup Server using express in Node js with Cashfree SDK

npm init -y
npm i express axios crypto dotenv
JavaScript

And Most Important cashfree-pg

npm i cashfree-pg
JavaScript

After this make .env and place all key inside the .env file

CLIENT_ID=XXXXXXXXXXXXXXXXXXXXXXXXXXXX
CLIENT_SECRET=XXXXXXXXXXXXXXXXXXXXXXXX
JavaScript

after this all main server looks like this

const express = require('express');
const cors = require('cors');
const crypto = require('crypto');
const {
    Cashfree
} = require('cashfree-pg');


require('dotenv').config();

const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));



Cashfree.XClientId = process.env.CLIENT_ID;
Cashfree.XClientSecret = process.env.CLIENT_SECRET;
Cashfree.XEnvironment = Cashfree.Environment.SANDBOX;


function generateOrderId() {
    const uniqueId = crypto.randomBytes(16).toString('hex');

    const hash = crypto.createHash('sha256');
    hash.update(uniqueId);

    const orderId = hash.digest('hex');

    return orderId.substr(0, 12);
}


app.get('/', (req, res) => {
    res.send('Hello World!');
})


app.get('/payment', async (req, res) => {

    try {

        let request = {
            "order_amount": 1.00,
            "order_currency": "INR",
            "order_id": await generateOrderId(),
            "customer_details": {
                "customer_id": "webcodder01",
                "customer_phone": "9999999999",
                "customer_name": "Web Codder",
                "customer_email": "[email protected]"
            },
        }

        Cashfree.PGCreateOrder("2023-08-01", request).then(response => {
            console.log(response.data);
            res.json(response.data);

        }).catch(error => {
            console.error(error.response.data.message);
        })


    } catch (error) {
        console.log(error);
    }


})

app.post('/verify', async (req, res) => {

    try {

        let {
            orderId
        } = req.body;

        Cashfree.PGOrderFetchPayments("2023-08-01", orderId).then((response) => {

            res.json(response.data);
        }).catch(error => {
            console.error(error.response.data.message);
        })


    } catch (error) {
        console.log(error);
    }
})

app.listen(8000, () => {
    console.log('Server is running on port 8000');
})
JavaScript

Source Code Download

Download Full Source Code of Cashfree Payment Getway in React Js using Node Js

What is Cashfree?

In online shopping and gaming, businesses need a way to get paid quickly and securely. This is where Cashfree comes in. Cashfree is like a special helper that makes sure when you buy something online or make a payment in a game; the money goes from your account to the right place without any problems.

Cashfree’s Role

Cashfree is like a magical wizard that works behind the scenes to make sure your payments are processed smoothly. Just like how a magic spell makes things happen, Cashfree processes your payment so that you can enjoy your new game or toy without any worries.

Fun Facts about Cashfree

Did you know that many popular websites and apps use Cashfree to make payments safe and easy? It’s like having a secret superpower that helps businesses and customers all around the world!

Understanding React

React is like playing with building blocks on a computer. Just as you can stack blocks to create something cool, developers use React to build amazing websites and apps. It makes the process easier and more fun!

Image result for Cashfree + React: Seamless Integration Guide infographics

Why Use React

React helps developers work faster and smarter. It lets them reuse pieces of code, like Lego bricks, saving time and effort. With React, creating awesome websites and apps becomes a breeze!

The Magic of Integrating Cashfree with React

Imagine you have a fantastic new toy set that you love to play with, but you feel like it’s missing something. That’s where integrating Cashfree with React comes in! It’s like adding a cool new feature to your favorite toy set, making it even more exciting and fun to use.

Step-by-Step Guide

Integrating Cashfree with React may sound like a big and complicated task, but don’t worry, it’s actually quite simple! Just follow these easy steps to connect Cashfree to your React application:

  1. First, make sure you have a Cashfree account and the necessary API keys ready.
  2. Next, install the Cashfree SDK library in your React app using npm or yarn.
  3. Once the library is installed, initialize Cashfree with your API keys to start using the payment gateway.
  4. Create a payment form in your React app using Cashfree’s components and styling options.
  5. Finally, handle the payment response from Cashfree in your app to complete the transaction process.

By following these steps, you can seamlessly integrate Cashfree with your React application and offer a smooth payment experience to your users. It’s like adding a super cool feature to your favorite toy set!

Getting Started with Cashfree Integration

Are you ready to take your online payments to the next level? Integrating Cashfree with your website or app is a great way to make transactions smooth and easy. It’s just like starting a new level in a video game – exciting and full of new possibilities!

Image result for Cashfree + React: Seamless Integration Guide infographics

Image courtesy of medium.com via Google Images

How to Integrate Cashfree API

Starting the integration process is as simple as putting together a new puzzle. First, you’ll need to create an account with Cashfree and get your API key. Think of the API key as a special code that allows your website to communicate with Cashfree seamlessly.

Once you have your API key, it’s time to add Cashfree to your website or app. Just like adding a new player to your favorite game, integrating Cashfree will open up a world of possibilities for your online payments.

Step-by-Step Guide

Here’s a simple guide to help you get started with Cashfree integration:

  1. Create a Cashfree account and get your API key.
  2. Install the Cashfree SDK in your React application.
  3. Set up the necessary payment methods and configurations.
  4. Test your integration to ensure everything is working smoothly.
  5. Start accepting payments with ease!

By following these steps, you’ll be well on your way to improving your online payment experience. Just like mastering a new skill in your favorite game, integrating Cashfree will make your website or app more efficient and user-friendly.

Exploring the Cashfree API

Have you ever been to a restaurant and looked at a menu to decide what to order? Well, think of an API like a menu for computers and apps. The Cashfree API is like a special menu that lets websites and apps talk to each other and handle online payments smoothly. It’s like the secret language they use to make sure your money goes where it needs to go when you buy something online.

What Can You Do with the Cashfree API?

The Cashfree API is like a magical tool that developers can use to make sure your online shopping experience is quick and secure. With this API, websites can accept payments from different sources like credit cards, debit cards, and even digital wallets. It also helps keep track of your purchases and makes sure everything is safe and sound. So, the next time you click that “buy now” button, thank the Cashfree API for making it all happen seamlessly!

Safety First: Keeping Payments Secure

When you buy something online or use a payment gateway like Cashfree, it’s important to keep your money safe. Security is like having a super strong lock on your piggy bank to make sure no one can take your coins without your permission.

Image result for Cashfree + React: Seamless Integration Guide infographics

Image courtesy of www.cashfree.com via Google Images

Why Security Matters

Just like you wouldn’t want someone sneaking into your room and taking your favorite toys, you don’t want people stealing your money when you make an online payment. That’s why payment gateways like Cashfree have special ways to protect your information and keep your transactions secure.

How Cashfree Keeps You Safe

Cashfree uses special codes and encryption to make sure that only you and the person you’re paying can see the information. It’s like having a secret language that only you and your friend understand, so no one else can eavesdrop and know what you’re talking about.

StepDescription
Step 1Install Cashfree SDK in your React project using npm or yarn.
Step 2Import Cashfree SDK in your React component where you want to integrate payments.
Step 3Set up the necessary configuration and initialize the Cashfree SDK with your Merchant ID and Secret Key.
Step 4Create a payment form in your React component with the required fields such as amount, order ID, etc.
Step 5Handle the payment initiation on user interaction (e.g., button click) by calling the Cashfree SDK’s payment method.
Step 6Implement the necessary event listeners to handle payment success and failure callbacks from Cashfree SDK.
Step 7Update the UI based on payment status and provide feedback to the user.

When you see a little lock symbol or “https” in the website address, it means your connection is secure, just like having a secret handshake to know you can trust the person you’re shaking hands with.

So, next time you use Cashfree to make a payment, remember that they’re like the superhero guardian of your money, making sure it stays safe and sound. It’s like having a superpower that keeps your coins safe from sneaky villains!

Troubleshooting Common Issues

As much as we try to make things as smooth as possible, sometimes little bumps in the road can occur. If you’re facing any issues while using Cashfree Payment Gateway, don’t worry! Here are some simple solutions to common problems that might arise

What to Do When Something Goes Wrong

If you’re trying to make a payment and it’s not going through, the first thing to do is to check your internet connection. Make sure you have a stable connection to ensure the payment process goes smoothly. If the problem persists, you can try refreshing the page or closing and reopening the app.

Another common issue is entering incorrect payment details. Double-check all the information you’ve entered, such as card numbers, expiry dates, and CVV codes. Even a small mistake can cause a payment to fail.

If you’re still having trouble, don’t hesitate to reach out to customer support. They’re there to help you with any issues you may encounter and can guide you through the troubleshooting process. Remember, it’s okay to ask for help when you need it!

Real-World Examples

Let’s take a look at some online stores and apps that use Cashfree as their payment gateway. These examples will show you how Cashfree is integrated into websites and applications that you might already be familiar with!

Image result for Cashfree + React: Seamless Integration Guide infographics

Image courtesy of www.youtube.com via Google Images

Example 1: Gaming Website

Imagine playing your favorite online game and wanting to buy some cool new features or accessories for your character. When you go to make a purchase, the website uses Cashfree to securely process your payment. This way, you can get what you want quickly and get back to playing without any hassle.

Example 2: Toy Store App

Picture browsing through a toy store app on your tablet or phone. When you find the perfect toy that you just have to have, you can easily buy it using Cashfree. This payment gateway ensures that your payment information is kept safe so you can enjoy your new toy worry-free!

These real-world examples show how Cashfree is a trusted payment gateway used by popular online stores and apps to make shopping and gaming experiences smooth and secure for kids like you!

Conclusion

In conclusion, we have learned about the world of online payments and how payment gateways like Cashfree play a crucial role in enabling smooth transactions while ensuring the security of our money. Cashfree acts as the virtual cashier, helping websites and apps get paid for the goods and services they offer.

Cashfree’s Role

Think of Cashfree as the friendly assistant at a store that helps you pay for your favorite toys or games online, making sure your money reaches the right place quickly and securely.

Fun Facts about Cashfree

Did you know that Cashfree is like a superhero for online businesses, swooping in to save the day by making payments hassle-free and reliable?

Now, when we talk about integrating Cashfree with React, it’s like adding a new feature to your favorite toy – enhancing its functionality and making it even more exciting to use. Just like how adding a cool new accessory to your bike can make riding even more fun!

Step-by-Step Guide

If you’re curious about how to connect Cashfree to a React app, follow the simple steps we’ve outlined, just like following the instructions to build a new LEGO set for added playtime adventures!

Remember, keeping payments secure is as important as wearing a helmet while riding your bike. Cashfree acts as a protector, ensuring that your money stays safe and sound during online transactions.

And if you ever face any issues with Cashfree, don’t worry! Just like fixing a flat tire on your bike, we’ve provided some easy troubleshooting tips to help you navigate through any bumps in the payment process.

Lastly, real-world examples of Cashfree in action show us how online stores and apps use this payment gateway to offer a seamless shopping experience, just like how your favorite online games or toy stores make it easy for you to get your hands on the latest toys or gadgets.