Last active
February 10, 2025 14:19
-
-
Save amritmaurya1504/5999b0e6cd9612bcbb195263b8bbe2eb to your computer and use it in GitHub Desktop.
Razorpay Integration Code Snippet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // BACKEND | |
| // CREATE ORDER /api/payment/create-order | |
| // Initialize Razorpay | |
| const razorpay = new Razorpay({ | |
| key_id: config.razorpayKeyId, | |
| key_secret: config.razorpaySecretKey, | |
| }); | |
| try { | |
| const { amount } = req.body; | |
| const options = { | |
| amount: amount * 100, // Amount in paisa (1 INR = 100 paisa) | |
| currency: "INR", | |
| receipt: `receipt_${Date.now()}`, | |
| }; | |
| const order = await razorpay.orders.create(options); | |
| res.json({ success: true, order }); | |
| } catch (error) { | |
| next(error); | |
| } | |
| // VERIFY PAYMENT /api/payment/verify-payment | |
| const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = | |
| req.body; | |
| const expectedSignature = crypto | |
| .createHmac("sha256", config.razorpaySecretKey) | |
| .update(razorpay_order_id + "|" + razorpay_payment_id) | |
| .digest("hex"); | |
| if (expectedSignature === razorpay_signature) { | |
| res.json({ success: true, message: "Payment verified successfully!" }); | |
| } else { | |
| const error = createHttpError(400, "Payment verification failed!"); | |
| return next(error); | |
| } | |
| } catch (error) { | |
| next(error); | |
| } | |
| // WEBHOOK /api/payment/wwebhoo-verification | |
| try { | |
| const secret = config.razorpyWebhookSecret; | |
| const signature = req.headers["x-razorpay-signature"]; | |
| const body = JSON.stringify(req.body); // Convert payload to string | |
| // π Verify the signature | |
| const expectedSignature = crypto | |
| .createHmac("sha256", secret) | |
| .update(body) | |
| .digest("hex"); | |
| if (expectedSignature === signature) { | |
| console.log("β Webhook verified:", req.body); | |
| // β Process payment (e.g., update DB, send confirmation email) | |
| if (req.body.event === "payment.captured") { | |
| const payment = req.body.payload.payment.entity; | |
| console.log(`π° Payment Captured: ${payment.amount / 100} INR`); | |
| // Update database, send email, etc. | |
| } | |
| res.json({ success: true }); | |
| } else { | |
| const error = createHttpError(400, "β Invalid Signature!"); | |
| return next(error); | |
| } | |
| } catch (error) { | |
| console.log(error); | |
| next(error); | |
| } | |
| // DEMO DATA RECIEVED IN BODY | |
| { | |
| "entity": "event", | |
| "account_id": "acc_ABC123456XYZ", | |
| "event": "payment.captured", | |
| "contains": ["payment"], | |
| "payload": { | |
| "payment": { | |
| "entity": { | |
| "id": "pay_ABC123XYZ", | |
| "entity": "payment", | |
| "amount": 50000, | |
| "currency": "INR", | |
| "status": "captured", | |
| "order_id": "order_123XYZ", | |
| "invoice_id": null, | |
| "international": false, | |
| "method": "upi", | |
| "amount_refunded": 0, | |
| "refund_status": null, | |
| "captured": true, | |
| "description": "Test Payment", | |
| "card_id": null, | |
| "bank": null, | |
| "wallet": null, | |
| "vpa": "user@upi", | |
| "email": "customer@example.com", | |
| "contact": "+919876543210", | |
| "notes": { | |
| "customer_id": "12345", | |
| "order_note": "Payment for Order #123" | |
| }, | |
| "created_at": 1707398262 | |
| } | |
| } | |
| } | |
| } | |
| // FRONTEND CODE | |
| function 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 handlePlaceOrder = async () => { | |
| if (!paymentMethod) { | |
| enqueueSnackbar("Please select your payment method!", { | |
| variant: "warning", | |
| }); | |
| return; | |
| } | |
| try { | |
| const res = await loadScript( | |
| "https://checkout.razorpay.com/v1/checkout.js" | |
| ); | |
| if (!res) { | |
| enqueueSnackbar("Razorpay SDK failed to load. Are you online?", { | |
| variant: "warning", | |
| }); | |
| return; | |
| } | |
| const reqData = { | |
| amount: totalPriceWithTax, // Amount in INR | |
| currency: "INR", | |
| }; | |
| const { data } = await createOrderRazorpay(reqData); | |
| const options = { | |
| key: `${import.meta.env.VITE_RAZORPAY_KEY_ID}`, | |
| amount: data.order.amount, | |
| currency: data.order.currency, | |
| name: "RESTRO", | |
| description: "Secure Payment for Your Meal", | |
| order_id: data.order.id, | |
| handler: async function (response) { | |
| const verification = await verifyPaymentRazorpay(response); | |
| console.log(verification); | |
| enqueueSnackbar(verification.data.message, { variant: "success" }); | |
| }, | |
| prefill: { | |
| name: customerData.name, | |
| email: "", | |
| contact: customerData.phone, | |
| }, | |
| theme: { color: "#025cca" }, | |
| }; | |
| const rzp = new window.Razorpay(options); | |
| rzp.open(); | |
| } catch (error) { | |
| console.log(error); | |
| enqueueSnackbar("Payment Failed!", { variant: "error" }); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Razorpay not available in my country any other way??