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
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
mkdir backend && cd backend
npm init -y
npm install express body-parser cors dotenv razorpay
Create a server.js file in the backend folder:
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)
RAZORPAY_KEY_ID=<your_test_key_id>
RAZORPAY_KEY_SECRET=<your_test_key_secret>
Frontend Setup (React)
1.Initialize Frontend
npx create-react-app frontend
cd frontend
npm install axios dotenv
2. Environment Variables (.env)
REACT_APP_RAZORPAY_KEY=<your_test_key_id>
REACT_APP_BACKEND_URL=<your_localhost>
Create a Payment.js file in the src folder:
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:
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:
cd backend
node server.js
2. Start the React app:
cd frontend
npm start
- Open
↗ Original-Artikel auf dev.to lesenVollständiger Original-ArtikelDen kompletten Beitrag mit allen Details direkt auf dev.to lesen.
SOCIAL SHARE CARD GENERATOR