ReactJS = vite Razorpay Integration
Sat Oct 19 2024 05:52:57 GMT+0000 (Coordinated Universal Time)
Saved by @Rishi1808
import './index.css'; import React from 'react'; import Apis from './APIs'; import axios from 'axios'; function App() { const [responseId, setResponseId] = React.useState(""); const [responseState, setResponseState] = React.useState([]); 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); }); }; const createRazorpayOrder = async (amount) => { const data = { amount: amount * 100, currency: "INR" }; try { const response = await axios.post(Apis.PAYMENT_API.CREATE_ORDER, data); handleRazorpayScreen(response.data.amount, response.data.order_id); } catch (error) { console.error("Error creating order:", error); } }; const handleRazorpayScreen = async (amount, orderId) => { const res = await loadScript("https://checkout.razorpay.com/v1/checkout.js"); if (!res) { alert("Some error at Razorpay screen loading"); return; } const options = { key: 'rzp_test_GcZZFDPP0jHtC4', amount: amount, currency: 'INR', name: "Papaya Coders", description: "Payment to Papaya Coders", image: "https://papayacoders.com/demo.png", order_id: orderId, // Use the order ID for payment handler: function (response) { setResponseId(response.razorpay_payment_id); }, prefill: { name: "Papaya Coders", email: "papayacoders@gmail.com" }, theme: { color: "#F4C430" } }; const paymentObject = new window.Razorpay(options); paymentObject.open(); }; const paymentFetch = async (e) => { e.preventDefault(); const paymentId = e.target.paymentId.value; try { const response = await axios.get(Apis.PAYMENT_API.FETCH_PAYMENT(paymentId)); setResponseState(response.data); } catch (error) { console.error("Error fetching payment:", error); } }; return ( <div className="App flex flex-col items-center justify-center min-h-screen bg-gray-100"> <button className="bg-yellow-400 hover:bg-yellow-500 text-white font-bold py-2 px-4 rounded mb-4" onClick={() => createRazorpayOrder(100)} > Payment of 100 Rs. </button> {responseId && <p className="text-green-600">{responseId}</p>} <h1 className="text-2xl font-bold mb-4">This is payment verification form</h1> <form onSubmit={paymentFetch} className="flex flex-col items-center"> <input type="text" name="paymentId" className="border rounded py-2 px-4 mb-4" placeholder="Enter Payment ID" /> <button type="submit" className="bg-blue-500 hover:bg-blue-600 text-white font-bold py-2 px-4 rounded" > Fetch Payment </button> {responseState.length !== 0 && ( <ul className="mt-4 bg-white p-4 rounded shadow"> <li>Amount: {responseState.amount / 100} Rs.</li> <li>Currency: {responseState.currency}</li> <li>Status: {responseState.status}</li> <li>Method: {responseState.method}</li> </ul> )} </form> </div> ); } export default App;
Comments