How to integrate RazorPay Gateway into your ReactJS + express.js(frontend+backend)
Published: 2023-11-19 11:02:13

**Step 1**: you need to upload the script programmatically in reactJS.

Add this in App.js

```
import { useEffect } from "react";
import displayRazor from "./utils/paymentGateway";
function App() {

  //programatically adding the script in html

  const loadscript = (src)=>{
    return new Promise((resolve)=>{
      const script = document.createElement("script");
      script.src = src;
      script.onload = ()=>{
        resolve(true);
      }
      script.onerror = ()=>{
        resolve(false);
      }

      document.body.appendChild(script);
    })

  }
  // on page Load , we are adding script.
  useEffect(()=>{
  loadscript("http://checkout.razorpay.com/v1/checkout.js")
  },[])

  return(
   <>
   
   <button onClick={displayRazor}>Buy Now</button>
   
   </>
  )
  }
  
export default App
```

- loadscript is taking src as the parameter which is returning a promise .

- resolve is used by passing argument as true or false , indicating that script has been successfully loaded or not.

- DOM manipulation is used for creation and appending the element.

- "http://checkout.razorpay.com/v1/checkout.js" is the endpoint provided by Razorpay for orders.


**Step 2**:
 Now we will create a function which will trigger a pop-up of razorPay on the screen.

**create utils > paymentGateway.js**
(you can create folder of your choice , this is what i personally prefer)

**paymentGateway.js**
```
export default async function displayRazor(){
const data = await fetch("http://localhost:3000/razorpay", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  } 
}).then((t) => t.json());
const option = {
  key:"<your_key>",
  currency:data.currency,
  amount:data.amount,
  description:"",
  image:"http://localhost:3000/logo.jpg",
  handler:(res)=>{
   alert("order_id" + res.razorpay_order_id);
   alert("payment_id" + res.razorpay_payment_id);
  },
// name that will shown on the popUp
  prefill:{
    name:"",
    email:"",
    contact:""
  }
 }
 const paymentObject = new window.Razorpay(option);
 
 paymentObject.open();
}
```
- displayRazor function will be triggered on click.

- This will make a post request to the backend server.

- instance of razorpay which accepts option as a parameter object.



## Backend:


Note : in your package.json --> add type : "module"


**step 1** : In cmd 

npm i express path cors shortid razorpay url



**step 2**: add this in your index.js : 


- import all the required libraries
```
import express from "express";
import path from "path";
import cors from "cors";
import shortid from "shortid";
import razorpay from "razorpay";
import { fileURLToPath } from "url";
import { dirname } from "path";
const PORT = 3000;
```





**step 3**: add a middleware for preventing cors error

```
app.use(cors())
```


**step 4**: create an instance of express:

```
const app = express();
```

**step 5** : create an instance of razorpay:
```
const razorpayInstance = new razorpay({
  key_id: "<key_id>",
  key_secret: "<key_secret>"
});
```
- how to generate this key_id and key_secret will be explained in the end.


**step 6** : (optional) --> add logo.png in your root directory

create a route handler for fetching the png:
```
app.get("/logo.png", async (req, res) => {
  try {
    // Use import.meta.url to get the current file's URL,
    // then convert it to the file path using fileURLToPath.
    const currentFilePath = fileURLToPath(import.meta.url);
    
    // Get the directory name using the dirname function.
    const currentDir = dirname(currentFilePath);

    // Create the path to the logo.png file.
    const imagePath = path.join(currentDir, "logo.png");

    // Send the file as a response
    res.sendFile(imagePath);
  } catch (error) {
    console.error("Error serving logo.png:", error);
    res.status(500).send("Internal Server Error");
  }
});
```

- fileURLToPath(import.meta.url): This is used to convert the file URL of the current module (where this code is located) to a file path.
- dirname(currentFilePath): This extracts the directory name from the file path.
- path.join(currentDir, "logo.png"): This creates the full file path by joining the directory path with the filename "logo.png".


step 7 :(important) create a route handler for the creating payment order 


```
app.post("/razorpay",async (req,res)=>{
  const payment_capture = 1;  
// 1 means payment should be captured immediately
  const amount = 2;
  const currency = 'INR';
const option = {
  amount: amount *100,
  currency:currency,
  receipt: shortid.generate(),
  payment_capture
};
  try{
   const response = await razorpayInstance.orders.create(option);
   console.log(response);
     res.json({
      id:response.id,
      currency:response.currency,
      amount:response.amount
     })
  }
  catch(error){
   console.log (error);
  }

})
```


Our whole backend and frontend part is completed.


How to generate API keys in razorpay:

step1 : visit [razorpay](https://dashboard.razorpay.com/app/dashboard)

step 2 : search api

step 3 : click on API keys

step 4 : generate your own API keys and replace it in the above code.


Github code : [PaymentGatewayDemo](https://github.com/chirag14252/RazorPaymentGateway
)