🔧 Programmierung 🕛 vor 1 Jahr 8 Min Lesezeit
0

"Integrating Razor pay API in a React 18 App with Node.js Backend: A Complete Guide"

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht




Step 1: Set Up Your Razorpay Account




  • To use Razorpay, you’ll need to create an account and set up your business information.






1.1. Create an Account




  • Go to Razorpay Signup Page.











Prerequisites




  • Make sure you have the following tools installed:


  • Node.js (v22.11.0 or above)


  • npm or yarn


  • Razorpay API Key


  • React 18


  • A basic understanding of React and Node.js







Project Structure






CODE
razorpay-api/  
├── backend/
│ ├── server.js
│ ├── package.json
│ ├── .env
└── frontend/
├── src/
│ ├── App.js
│ ├── Payment.js
│ └── server.js
├── package.json
└── .env










Backend Implementation






1. Initialize the Backend






CODE
mkdir backend && cd backend  
npm init -y
npm install express body-parser cors dotenv razorpay









Create a server.js file in the backend folder:






CODE
const express = require("express");
const Razorpay = require("razorpay");
const bodyParser = require("body-parser");
const cors = require("cors");
require("dotenv").config();

const app = express();
app.use(bodyParser.json());
app.use(cors());

// Razorpay instance
const razorpay = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});

app.post("/create-order", async (req, res) => {
const { amount } = req.body;

try {
const order = await razorpay.orders.create({
amount: amount * 100, // amount in paise
currency: "INR",
receipt: `receipt_${Date.now()}`,
});
res.json({ orderId: order.id });
} catch (error) {
res.status(500).send(error);
}
});

app.listen(5000, () => {
console.log("Server running on Your_Localhost");[
});










Environment Variables (.env)






CODE
RAZORPAY_KEY_ID=<your_test_key_id>
RAZORPAY_KEY_SECRET=<your_test_key_secret>









Frontend Setup (React)






1.Initialize Frontend






CODE
npx create-react-app frontend
cd frontend
npm install axios dotenv










2. Environment Variables (.env)






CODE
REACT_APP_RAZORPAY_KEY=<your_test_key_id>
REACT_APP_BACKEND_URL=<your_localhost>










Create a Payment.js file in the src folder:






CODE
import React, { useState } from "react";
import axios from "axios";

const Payment = () => {
const [amount, setAmount] = useState(""); // State to track user-entered amount
const [paymentDetails, setPaymentDetails] = useState(null); // State to track payment response

const handlePayment = async () => {
if (!amount || isNaN(amount) || amount <= 0) {
alert("Please enter a valid amount.");
return;
}

const backendURL = process.env.REACT_APP_BACKEND_URL;

try {
// Step 1: Create an order on the backend
const { data } = await axios.post(`${backendURL}/create-order`, { amount });

// Step 2: Define Razorpay checkout options
const options = {
key: process.env.REACT_APP_RAZORPAY_KEY, // Razorpay API Key
amount: amount * 100, // Amount in paise
currency: "INR",
name: "Test Company",
description: "Test Transaction",
order_id: data.orderId, // Order ID from backend
handler: (response) => {
// Step 3: Handle successful payment
alert("Payment Successful");
console.log("Payment Response:", response);
setPaymentDetails(response); // Update state with payment details
},
prefill: {
name: "Test User",
email: "[email protected]",
contact: "9999999999",
},
theme: {
color: "#3399cc",
},
};

// Step 4: Open Razorpay checkout
const razor = new window.Razorpay(options);
razor.open();
} catch (error) {
console.error("Payment Failed:", error);
alert("Payment Failed. Please try again.");
}
};

return (
<div>

<div>
<label>Enter Amount (): </label>
<input
type="number"
value={amount}
onChange={(e) => setAmount(e.target.value)}
placeholder="Enter amount to pay"
/>
<button onClick={handlePayment}>Pay {amount || 0}</button>
</div>

{/* Display Payment Details */}
{paymentDetails && (
<div style={{ marginTop: "20px", border: "1px solid #ccc", padding: "10px" }}>
<h3>Payment Details</h3>
<p><strong>Payment ID:</strong> {paymentDetails.razorpay_payment_id}</p>
<p><strong>Order ID:</strong> {paymentDetails.razorpay_order_id}</p>
<p><strong>Signature:</strong> {paymentDetails.razorpay_signature}</p>
</div>
)}
</div>
);
};

export default Payment;










Update App.js




  • Replace the contents of App.js with:




CODE
import React from "react";
import Payment from "./Payment";

const App = () => {
return (
<div>
<h1>Razor pay Integration</h1>
<Payment />
</div>
);
};

export default App;










Test the Integration






1. Start the backend server:






CODE
cd backend  
node server.js










2. Start the React app:






CODE
cd frontend  
npm start







Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
6 Quellen
CVE-2022-44255 | TOTOLINK LR350 9.3.5u.6369_B20220309 buffer overflow (EUVD-2022-47204)
2 Quellen
CVE-2026-68426 | Linux Kernel up to 6.18.41/7.1.5/7.2-rc3 xfrm validate_xmit_skb_list use after free (Nessus ID 346426)
1 Quelle
Windows 11 Probleme mit gültiger Domänenanmeldung nach September-Update [Workaround]
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten "Integrating Razor pay API in a React 18 App with Node.js Backend: A Complete Guide"

Thematisch verwandte Begriffe: Integrating, Razor, React, with · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...