From 327a340f1e624bdb35c970aef0b84fe9ab434eb6 Mon Sep 17 00:00:00 2001 From: indar suthar Date: Fri, 14 Nov 2025 05:13:22 +0530 Subject: [PATCH] feat: payment gateway integration(razorpay) --- backend/.env.example | 4 +- backend/package-lock.json | 120 +++++ backend/package.json | 1 + backend/src/app.ts | 2 + backend/src/config/razorpay.config.ts | 42 ++ backend/src/controllers/payment.controller.ts | 483 ++++++++++++++++++ backend/src/models/order.model.ts | 90 ++++ backend/src/routes/paymentRoutes.ts | 21 + frontend/package-lock.json | 289 +++++++++++ frontend/package.json | 1 + frontend/src/components/CartContext.tsx | 68 ++- frontend/src/lib/api.ts | 79 +++ frontend/src/lib/utils.tsx | 17 + frontend/src/pages/Payment.tsx | 351 +++++++++---- 14 files changed, 1461 insertions(+), 107 deletions(-) create mode 100644 backend/src/config/razorpay.config.ts create mode 100644 backend/src/controllers/payment.controller.ts create mode 100644 backend/src/models/order.model.ts create mode 100644 backend/src/routes/paymentRoutes.ts diff --git a/backend/.env.example b/backend/.env.example index 009be97..724342f 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -9,4 +9,6 @@ JWT_REFRESH_SECRET=anothersecretkey456 NODE_ENV=development FIREBASE_STORAGE_BUCKET=get-from-firebaseconsole GOOGLE_CLIENT_ID=yours -GOOGLE_CLIENT_SECRET=yours \ No newline at end of file +GOOGLE_CLIENT_SECRET=yours +RAZORPAY_KEY_ID=your_razorpay_key_id +RAZORPAY_KEY_SECRET=your_razorpay-secret \ No newline at end of file diff --git a/backend/package-lock.json b/backend/package-lock.json index e330619..0f9c379 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -23,6 +23,7 @@ "morgan": "^1.10.0", "nodemailer": "^7.0.9", "nodemon": "^3.1.10", + "razorpay": "^2.9.6", "socket.io": "^4.8.1", "socket.io-client": "^4.8.1", "uuid": "^13.0.0", @@ -1876,6 +1877,23 @@ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==", "license": "MIT" }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz", + "integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -2142,6 +2160,18 @@ "node": ">=18" } }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -2258,6 +2288,15 @@ "ms": "2.0.0" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -2492,6 +2531,21 @@ "node": ">= 0.4" } }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escape-html": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", @@ -2643,6 +2697,26 @@ "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==", "license": "MIT" }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreground-child": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", @@ -2659,6 +2733,22 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/formdata-polyfill": { "version": "4.0.10", "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", @@ -3121,6 +3211,21 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/hasown": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", @@ -4027,6 +4132,12 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/pstree.remy": { "version": "1.1.8", "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", @@ -4081,6 +4192,15 @@ "node": ">= 0.8" } }, + "node_modules/razorpay": { + "version": "2.9.6", + "resolved": "https://registry.npmjs.org/razorpay/-/razorpay-2.9.6.tgz", + "integrity": "sha512-zsHAQzd6e1Cc6BNoCNZQaf65ElL6O6yw0wulxmoG5VQDr363fZC90Mp1V5EktVzG45yPyNomNXWlf4cQ3622gQ==", + "license": "MIT", + "dependencies": { + "axios": "^1.6.8" + } + }, "node_modules/react": { "version": "19.2.0", "resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz", diff --git a/backend/package.json b/backend/package.json index 26b17b5..886b337 100644 --- a/backend/package.json +++ b/backend/package.json @@ -25,6 +25,7 @@ "morgan": "^1.10.0", "nodemailer": "^7.0.9", "nodemon": "^3.1.10", + "razorpay": "^2.9.6", "socket.io": "^4.8.1", "socket.io-client": "^4.8.1", "uuid": "^13.0.0", diff --git a/backend/src/app.ts b/backend/src/app.ts index 612fa0e..43beca4 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -7,6 +7,7 @@ import userRoutes from "./routes/user.routes"; import productRoutes from "./routes/product.routes"; import cartRoutes from "./routes/cartRoutes"; import auctionRoutes from "./routes/auctionRoutes"; +import paymentRoutes from "./routes/paymentRoutes"; import mongoose from "mongoose"; import { requestLogger } from "./middleware/loggerMiddleware"; import { errorHandler } from "./middleware/errorMiddleware"; @@ -39,6 +40,7 @@ app.use("/api/products", productRoutes); app.use("/api/users", userRoutes); app.use("/api/cart", cartRoutes); app.use("/api/auctions", auctionRoutes); +app.use("/api/payments", paymentRoutes); // MongoDB connect (optional) const mongoUri = process.env.MONGO_URI; diff --git a/backend/src/config/razorpay.config.ts b/backend/src/config/razorpay.config.ts new file mode 100644 index 0000000..1220021 --- /dev/null +++ b/backend/src/config/razorpay.config.ts @@ -0,0 +1,42 @@ +import Razorpay from "razorpay"; +import dotenv from "dotenv"; + +dotenv.config(); +const RAZORPAY_KEY_ID = process.env.RAZORPAY_KEY_ID?.trim(); +const RAZORPAY_KEY_SECRET = process.env.RAZORPAY_KEY_SECRET?.trim(); +if (!RAZORPAY_KEY_ID || !RAZORPAY_KEY_SECRET) { + console.warn( + " Warning: Razorpay credentials not found. Please set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET in .env file" + ); + console.warn( + "Payment functionality will not work until credentials are configured." + ); +} +let razorpayInstance: Razorpay; + +if (RAZORPAY_KEY_ID && RAZORPAY_KEY_SECRET) { + try { + razorpayInstance = new Razorpay({ + key_id: RAZORPAY_KEY_ID, + key_secret: RAZORPAY_KEY_SECRET, + }); + console.log("✅ Razorpay initialized successfully"); + } catch (error) { + console.error("❌ Failed to initialize Razorpay:", error); + razorpayInstance = new Razorpay({ + key_id: "", + key_secret: "", + }); + } +} else { + razorpayInstance = new Razorpay({ + key_id: "", + key_secret: "", + }); +} +export const razorpay = razorpayInstance; +export const RAZORPAY_CONFIG = { + keyId: RAZORPAY_KEY_ID || "", + currency: "INR", +}; + diff --git a/backend/src/controllers/payment.controller.ts b/backend/src/controllers/payment.controller.ts new file mode 100644 index 0000000..349bd1a --- /dev/null +++ b/backend/src/controllers/payment.controller.ts @@ -0,0 +1,483 @@ +import { Request, Response } from "express"; +import mongoose from "mongoose"; +import { razorpay, RAZORPAY_CONFIG } from "../config/razorpay.config"; +import Order, { OrderStatus, PaymentStatus } from "../models/order.model"; +import Cart from "../models/cart.model"; +import crypto from "crypto"; + +interface AuthenticatedRequest extends Request { + user?: { + id: string; + email?: string; + }; +} +export const createOrder = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ + success: false, + message: "Unauthorized - User ID not found" + }); + return; + } + + console.log("Creating order for user:", userId); + let cart; + try { + cart = await Cart.findOne({ userId: new mongoose.Types.ObjectId(userId) }); + } catch (cartError: any) { + console.error("Cart lookup error:", cartError); + res.status(500).json({ + success: false, + message: "Failed to retrieve cart", + error: cartError.message, + }); + return; + } + + if (!cart) { + res.status(400).json({ + success: false, + message: "Cart not found. Please add items to your cart first." + }); + return; + } + + if (cart.items.length === 0) { + res.status(400).json({ + success: false, + message: "Cart is empty. Please add items to your cart first." + }); + return; + } + + console.log("Cart found with", cart.items.length, "items"); + + // Calc amounts + const totalAmount = cart.totalPrice || 0; + if (totalAmount <= 0) { + res.status(400).json({ + success: false, + message: "Invalid cart total. Please check your cart items.", + }); + return; + } + + const shippingCharges = totalAmount > 0 ? 99 : 0; + const tax = Math.round(totalAmount * 0.18); + const finalAmount = totalAmount + shippingCharges + tax; + if (finalAmount < 1) { + res.status(400).json({ + success: false, + message: "Order amount is too small. Minimum order value is ₹1.", + }); + return; + } + const amountInPaise = Math.round(finalAmount * 100); + console.log("Order amount:", finalAmount, "INR (", amountInPaise, "paise)"); + if (!RAZORPAY_CONFIG.keyId || !process.env.RAZORPAY_KEY_SECRET) { + console.error("Razorpay configuration missing"); + res.status(500).json({ + success: false, + message: "Payment gateway configuration error. Please contact support.", + error: "Razorpay credentials not configured", + }); + return; + } + + // Create Razorpay order + let razorpayOrder; + try { + console.log("Creating Razorpay order..."); + razorpayOrder = await razorpay.orders.create({ + amount: amountInPaise, + currency: RAZORPAY_CONFIG.currency, + receipt: `order_${Date.now()}_${userId.substring(0, 8)}`, + notes: { + userId, + cartId: cart._id.toString(), + }, + }); + console.log("Razorpay order created:", razorpayOrder.id); + } catch (razorpayError: any) { + console.error("Razorpay order creation error:", razorpayError); + + let errorMessage = "Payment gateway error"; + if (razorpayError.error?.description) { + errorMessage = razorpayError.error.description; + } else if (razorpayError.message) { + errorMessage = razorpayError.message; + } + + res.status(500).json({ + success: false, + message: "Failed to create payment order", + error: errorMessage, + details: process.env.NODE_ENV === "development" ? razorpayError : undefined, + }); + return; + } + + // Create order in database + let order; + try { + order = new Order({ + userId: new mongoose.Types.ObjectId(userId), + items: cart.items.map((item) => ({ + productId: item.productId, + name: item.name, + price: item.price, + quantity: item.quantity, + })), + totalAmount, + shippingCharges, + tax, + finalAmount, + orderStatus: OrderStatus.PENDING, + paymentStatus: PaymentStatus.PENDING, + razorpayOrderId: razorpayOrder.id, + }); + + await order.save(); + console.log("Order saved to database:", order._id.toString()); + } catch (orderError: any) { + console.error("Database order creation error:", orderError); + res.status(500).json({ + success: false, + message: "Failed to create order in database", + error: orderError.message, + }); + return; + } + + res.status(200).json({ + success: true, + order: { + id: razorpayOrder.id, + amount: razorpayOrder.amount, + currency: razorpayOrder.currency, + receipt: razorpayOrder.receipt, + }, + orderId: order._id.toString(), + key: RAZORPAY_CONFIG.keyId, + }); + } catch (error: any) { + console.error("Create order error:", error); + res.status(500).json({ + success: false, + message: "Failed to create order", + error: error.message || "Unknown error occurred", + stack: process.env.NODE_ENV === "development" ? error.stack : undefined, + }); + } +}; + +export const verifyPayment = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ + success: false, + message: "Unauthorized" + }); + return; + } + + const { + razorpay_order_id, + razorpay_payment_id, + razorpay_signature, + orderId, + } = req.body; + + if (!razorpay_order_id || !razorpay_payment_id || !razorpay_signature) { + res.status(400).json({ + success: false, + message: "Missing payment details", + }); + return; + } + + console.log("Verifying payment for order:", razorpay_order_id); + + let order; + try { + const query: any = { + razorpayOrderId: razorpay_order_id, + userId: new mongoose.Types.ObjectId(userId), + }; + + if (orderId) { + try { + query._id = new mongoose.Types.ObjectId(orderId); + } catch (e) { + } + } + + order = await Order.findOne(query); + } catch (findError: any) { + console.error("Order lookup error:", findError); + res.status(500).json({ + success: false, + message: "Failed to find order", + error: findError.message, + }); + return; + } + + if (!order) { + res.status(404).json({ + success: false, + message: "Order not found", + }); + return; + } + + // Verify signature + const secret = process.env.RAZORPAY_KEY_SECRET || ""; + if (!secret) { + console.error("Razorpay secret not configured"); + res.status(500).json({ + success: false, + message: "Payment verification configuration error", + }); + return; + } + + const generatedSignature = crypto + .createHmac("sha256", secret) + .update(`${razorpay_order_id}|${razorpay_payment_id}`) + .digest("hex"); + + const isSignatureValid = generatedSignature === razorpay_signature; + + if (!isSignatureValid) { + console.error("Invalid payment signature"); + order.paymentStatus = PaymentStatus.FAILED; + await order.save(); + + res.status(400).json({ + success: false, + message: "Payment verification failed: Invalid signature", + }); + return; + } + + order.razorpayPaymentId = razorpay_payment_id; + order.razorpaySignature = razorpay_signature; + order.paymentStatus = PaymentStatus.SUCCESS; + order.orderStatus = OrderStatus.CONFIRMED; + await order.save(); + + console.log("Payment verified successfully for order:", order._id.toString()); + + try { + const cart = await Cart.findOne({ userId: new mongoose.Types.ObjectId(userId) }); + if (cart) { + cart.items = []; + cart.totalPrice = 0; + await cart.save(); + console.log("Cart cleared for user:", userId); + } + } catch (cartError) { + console.warn("Failed to clear cart:", cartError); + } + + res.status(200).json({ + success: true, + message: "Payment verified successfully", + order: { + id: order._id.toString(), + orderStatus: order.orderStatus, + paymentStatus: order.paymentStatus, + finalAmount: order.finalAmount, + }, + }); + } catch (error: any) { + console.error("Verify payment error:", error); + res.status(500).json({ + success: false, + message: "Payment verification failed", + error: error.message || "Unknown error occurred", + stack: process.env.NODE_ENV === "development" ? error.stack : undefined, + }); + } +}; + +export const getOrderStatus = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + + const { orderId } = req.params; + + if (!orderId) { + res.status(400).json({ message: "Order ID is required" }); + return; + } + + let order; + try { + order = await Order.findOne({ + _id: orderId, + userId: new mongoose.Types.ObjectId(userId), + }).populate("items.productId"); + } catch (findError: any) { + res.status(400).json({ + message: "Invalid order ID", + error: findError.message, + }); + return; + } + + if (!order) { + res.status(404).json({ message: "Order not found" }); + return; + } + + res.status(200).json({ + success: true, + order: { + id: order._id.toString(), + items: order.items, + totalAmount: order.totalAmount, + shippingCharges: order.shippingCharges, + tax: order.tax, + finalAmount: order.finalAmount, + orderStatus: order.orderStatus, + paymentStatus: order.paymentStatus, + createdAt: order.createdAt, + updatedAt: order.updatedAt, + }, + }); + } catch (error: any) { + console.error("Get order status error:", error); + res.status(500).json({ + success: false, + message: "Failed to fetch order status", + error: error.message || "Unknown error occurred", + }); + } +}; + +export const getUserOrders = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + + const orders = await Order.find({ + userId: new mongoose.Types.ObjectId(userId), + }) + .populate("items.productId") + .sort({ createdAt: -1 }); + + res.status(200).json({ + success: true, + orders: orders.map((order) => ({ + id: order._id.toString(), + items: order.items, + totalAmount: order.totalAmount, + shippingCharges: order.shippingCharges, + tax: order.tax, + finalAmount: order.finalAmount, + orderStatus: order.orderStatus, + paymentStatus: order.paymentStatus, + createdAt: order.createdAt, + updatedAt: order.updatedAt, + })), + }); + } catch (error: any) { + console.error("Get user orders error:", error); + res.status(500).json({ + success: false, + message: "Failed to fetch orders", + error: error.message || "Unknown error occurred", + }); + } +}; + +export const updateOrderStatus = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const userId = req.user?.id; + if (!userId) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + + const { orderId } = req.params; + const { orderStatus, paymentStatus } = req.body; + + if (!orderId) { + res.status(400).json({ message: "Order ID is required" }); + return; + } + + let order; + try { + order = await Order.findOne({ + _id: orderId, + userId: new mongoose.Types.ObjectId(userId), + }); + } catch (findError: any) { + res.status(400).json({ + message: "Invalid order ID", + error: findError.message, + }); + return; + } + + if (!order) { + res.status(404).json({ message: "Order not found" }); + return; + } + + if (orderStatus && Object.values(OrderStatus).includes(orderStatus)) { + order.orderStatus = orderStatus; + } + + if (paymentStatus && Object.values(PaymentStatus).includes(paymentStatus)) { + order.paymentStatus = paymentStatus; + } + + await order.save(); + + res.status(200).json({ + success: true, + message: "Order status updated successfully", + order: { + id: order._id.toString(), + orderStatus: order.orderStatus, + paymentStatus: order.paymentStatus, + }, + }); + } catch (error: any) { + console.error("Update order status error:", error); + res.status(500).json({ + success: false, + message: "Failed to update order status", + error: error.message || "Unknown error occurred", + }); + } +}; diff --git a/backend/src/models/order.model.ts b/backend/src/models/order.model.ts new file mode 100644 index 0000000..9fbfbac --- /dev/null +++ b/backend/src/models/order.model.ts @@ -0,0 +1,90 @@ +import mongoose, { Schema, Types, Document } from "mongoose"; + +export interface IOrderItem { + productId: Types.ObjectId; + name: string; + price: number; + quantity: number; +} + +export enum OrderStatus { + PENDING = "pending", + PROCESSING = "processing", + CONFIRMED = "confirmed", + SHIPPED = "shipped", + DELIVERED = "delivered", + CANCELLED = "cancelled", +} + +export enum PaymentStatus { + PENDING = "pending", + PROCESSING = "processing", + SUCCESS = "success", + FAILED = "failed", + REFUNDED = "refunded", +} + +export interface IOrder extends Document { + userId: Types.ObjectId; + items: IOrderItem[]; + totalAmount: number; + shippingCharges: number; + tax: number; + finalAmount: number; + orderStatus: OrderStatus; + paymentStatus: PaymentStatus; + razorpayOrderId?: string; + razorpayPaymentId?: string; + razorpaySignature?: string; + shippingAddress?: { + street: string; + city: string; + state: string; + zipCode: string; + country: string; + }; + createdAt: Date; + updatedAt: Date; +} + +const orderItemSchema = new Schema({ + productId: { type: Schema.Types.ObjectId, ref: "Product", required: true }, + name: { type: String, required: true }, + price: { type: Number, required: true }, + quantity: { type: Number, required: true, min: 1 }, +}); + +const orderSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: "User", required: true }, + items: [orderItemSchema], + totalAmount: { type: Number, required: true, min: 0 }, + shippingCharges: { type: Number, default: 0, min: 0 }, + tax: { type: Number, default: 0, min: 0 }, + finalAmount: { type: Number, required: true, min: 0 }, + orderStatus: { + type: String, + enum: Object.values(OrderStatus), + default: OrderStatus.PENDING, + }, + paymentStatus: { + type: String, + enum: Object.values(PaymentStatus), + default: PaymentStatus.PENDING, + }, + razorpayOrderId: { type: String }, + razorpayPaymentId: { type: String }, + razorpaySignature: { type: String }, + shippingAddress: { + street: { type: String }, + city: { type: String }, + state: { type: String }, + zipCode: { type: String }, + country: { type: String, default: "India" }, + }, + }, + { timestamps: true } +); + +export default mongoose.model("Order", orderSchema); + diff --git a/backend/src/routes/paymentRoutes.ts b/backend/src/routes/paymentRoutes.ts new file mode 100644 index 0000000..0a5ae0c --- /dev/null +++ b/backend/src/routes/paymentRoutes.ts @@ -0,0 +1,21 @@ +import express, { Router } from "express"; +import { + createOrder, + verifyPayment, + getOrderStatus, + getUserOrders, + updateOrderStatus, +} from "../controllers/payment.controller"; +import { authenticate } from "../middleware/authMiddleware"; + +const router: Router = express.Router(); + +//payment routes +router.post("/create-order", authenticate, createOrder); +router.post("/verify", authenticate, verifyPayment); +router.get("/orders", authenticate, getUserOrders); +router.get("/orders/:orderId", authenticate, getOrderStatus); +router.patch("/orders/:orderId/status", authenticate, updateOrderStatus); + +export default router; + diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 16b594f..8fb78ea 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -49,6 +49,7 @@ "input-otp": "^1.4.2", "lucide-react": "^0.462.0", "next-themes": "^0.3.0", + "razorpay": "^2.9.6", "react": "^18.3.1", "react-day-picker": "^9.11.1", "react-dom": "^18.3.1", @@ -5502,6 +5503,23 @@ "node": ">=12" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "license": "MIT" + }, + "node_modules/axios": { + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.2.tgz", + "integrity": "sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.4", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -5608,6 +5626,19 @@ "node": ">=8" } }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -5765,6 +5796,18 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "license": "MIT" }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -6024,6 +6067,15 @@ "dev": true, "license": "MIT" }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -6087,6 +6139,20 @@ "csstype": "^3.0.2" } }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/electron-to-chromium": { "version": "1.5.237", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.237.tgz", @@ -6228,6 +6294,24 @@ "url": "https://github.com/fb55/entities?sponsor=1" } }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -6235,6 +6319,33 @@ "dev": true, "license": "MIT" }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/escalade": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", @@ -6683,6 +6794,42 @@ "dev": true, "license": "ISC" }, + "node_modules/follow-redirects": { + "version": "1.15.11", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", + "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", + "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/framer-motion": { "version": "12.23.24", "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.23.24.tgz", @@ -6738,6 +6885,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/gensync": { "version": "1.0.0-beta.2", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", @@ -6757,6 +6913,30 @@ "node": "6.* || 8.* || >= 10.*" } }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/get-nonce": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz", @@ -6766,6 +6946,19 @@ "node": ">=6" } }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -6812,6 +7005,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/graceful-fs": { "version": "4.2.11", "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", @@ -6835,6 +7040,45 @@ "node": ">=8" } }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, "node_modules/html-encoding-sniffer": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz", @@ -7546,6 +7790,15 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/mdn-data": { "version": "2.12.2", "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.12.2.tgz", @@ -7575,6 +7828,27 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/min-indent": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/min-indent/-/min-indent-1.0.1.tgz", @@ -8012,6 +8286,12 @@ "node": ">=12.0.0" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", @@ -8058,6 +8338,15 @@ ], "license": "MIT" }, + "node_modules/razorpay": { + "version": "2.9.6", + "resolved": "https://registry.npmjs.org/razorpay/-/razorpay-2.9.6.tgz", + "integrity": "sha512-zsHAQzd6e1Cc6BNoCNZQaf65ElL6O6yw0wulxmoG5VQDr363fZC90Mp1V5EktVzG45yPyNomNXWlf4cQ3622gQ==", + "license": "MIT", + "dependencies": { + "axios": "^1.6.8" + } + }, "node_modules/react": { "version": "18.3.1", "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 794e782..b2b214a 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -52,6 +52,7 @@ "input-otp": "^1.4.2", "lucide-react": "^0.462.0", "next-themes": "^0.3.0", + "razorpay": "^2.9.6", "react": "^18.3.1", "react-day-picker": "^9.11.1", "react-dom": "^18.3.1", diff --git a/frontend/src/components/CartContext.tsx b/frontend/src/components/CartContext.tsx index 34fd46d..ed261b3 100644 --- a/frontend/src/components/CartContext.tsx +++ b/frontend/src/components/CartContext.tsx @@ -1,4 +1,4 @@ -import React, { createContext, useContext, useEffect, useReducer } from "react"; +import React, { createContext, useContext, useEffect, useReducer, useCallback, useRef } from "react"; import { useNotification } from "./NotificationContext"; const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || "http://localhost:5000"; @@ -73,6 +73,7 @@ interface CartContextValue { updateQuantity: (params: { itemId?: string; productId?: string; quantity: number }) => Promise; clearCart: () => Promise; refreshFromServer: () => Promise; + syncToBackend: () => Promise; } const CartContext = createContext(undefined); @@ -86,6 +87,8 @@ export const useCart = (): CartContextValue => { export const CartProvider: React.FC> = ({ children }) => { const [state, dispatch] = React.useReducer(reducer, initialState); const { notifyAddToCart } = useNotification(); + const isRefreshingRef = useRef(false); + const isSyncingRef = useRef(false); useEffect(() => { try { @@ -115,9 +118,11 @@ export const CartProvider: React.FC> = ({ children } } }; - const refreshFromServer = async () => { + const refreshFromServer = useCallback(async () => { const token = localStorage.getItem("accessToken"); - if (!token) return; // nothing to do + if (!token || isRefreshingRef.current) return; + + isRefreshingRef.current = true; try { const res = await callBackend(`${API_BASE_URL}/api/cart`, { method: "GET", headers: getAuthHeaders() }); const cart = await res.json(); @@ -132,8 +137,62 @@ export const CartProvider: React.FC> = ({ children } dispatch({ type: "SET_CART", payload: items }); } catch (err) { // ignore + } finally { + isRefreshingRef.current = false; } - }; + }, []); + const syncToBackend = useCallback(async () => { + const token = localStorage.getItem("accessToken"); + if (!token || state.items.length === 0 || isSyncingRef.current) return; + + isSyncingRef.current = true; + try { + const res = await callBackend(`${API_BASE_URL}/api/cart`, { method: "GET", headers: getAuthHeaders() }); + const serverCart = await res.json(); + const serverItems = serverCart?.items || []; + + const currentItems = state.items; + for (const localItem of currentItems) { + const serverItem = serverItems.find((si: any) => + si.productId?.toString() === localItem.productId + ); + if (!serverItem) { + try { + await callBackend(`${API_BASE_URL}/api/cart`, { + method: "POST", + headers: getAuthHeaders(), + body: JSON.stringify({ + productId: localItem.productId, + name: localItem.name, + price: localItem.price, + quantity: localItem.quantity, + }), + }); + } catch (err) { + console.warn("Failed to sync item:", localItem.name, err); + } + } else if (serverItem.quantity !== localItem.quantity && serverItem._id) { + try { + await callBackend(`${API_BASE_URL}/api/cart/${serverItem._id}`, { + method: "PATCH", + headers: getAuthHeaders(), + body: JSON.stringify({ quantity: localItem.quantity }), + }); + } catch (err) { + console.warn("Failed to update item quantity:", localItem.name, err); + } + } + } + + if (!isRefreshingRef.current) { + await refreshFromServer(); + } + } catch (err) { + console.warn("Failed to sync cart to backend:", err); + } finally { + isSyncingRef.current = false; + } + }, [state.items, refreshFromServer]); const addItem = async (item: CartItem) => { const token = localStorage.getItem("accessToken"); @@ -255,6 +314,7 @@ export const CartProvider: React.FC> = ({ children } updateQuantity, clearCart, refreshFromServer, + syncToBackend, }; return {children}; diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts index 70f409c..018d893 100644 --- a/frontend/src/lib/api.ts +++ b/frontend/src/lib/api.ts @@ -161,4 +161,83 @@ export const googleLogin = async (idToken: string): Promise => { } catch (error: any) { throw error; } +}; +//Payment API functions +export interface CreateOrderResponse { + success: boolean; + order: { + id: string; + amount: number; + currency: string; + receipt: string; + }; + orderId: string; + key: string; +} + +export interface VerifyPaymentData { + razorpay_order_id: string; + razorpay_payment_id: string; + razorpay_signature: string; + orderId: string; +} + +export const createPaymentOrder = async (): Promise => { + const token = localStorage.getItem("accessToken"); + if (!token) { + throw new Error("Not authenticated. Please login to continue."); + } + + try { + const response = await fetch(`${API_BASE_URL}/api/payments/create-order`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + }); + + const responseData = await response.json().catch(() => ({})); + if (!response.ok) { + const errorData = await response.json().catch(() => ({ message: "Failed to create order" })); + throw new Error(errorData.message || "Failed to create order"); + } + + return responseData; + } catch (error: any) { + if (error.message && error.status) { + throw error; + } + if (error.name === "TypeError" || error.message.includes("fetch")) { + throw new Error("Network error. Please check your internet connection and try again."); + } + throw error; + } +}; + +export const verifyPayment = async (data: VerifyPaymentData): Promise => { + const token = localStorage.getItem("accessToken"); + if (!token) { + throw new Error("Not authenticated"); + } + + try { + const response = await fetch(`${API_BASE_URL}/api/payments/verify`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify(data), + }); + + if (!response.ok) { + const errorData = await response.json().catch(() => ({ message: "Payment verification failed" })); + throw new Error(errorData.message || "Payment verification failed"); + } + + return await response.json(); + } catch (error: any) { + throw error; + } }; \ No newline at end of file diff --git a/frontend/src/lib/utils.tsx b/frontend/src/lib/utils.tsx index a5ef193..ccf5eb8 100644 --- a/frontend/src/lib/utils.tsx +++ b/frontend/src/lib/utils.tsx @@ -4,3 +4,20 @@ import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } + +export function loadScript(src: string): Promise { + return new Promise((resolve, reject) => { + const existingScript = document.querySelector(`script[src="${src}"]`); + if (existingScript) { + resolve(); + return; + } + + const script = document.createElement("script"); + script.src = src; + script.async = true; + script.onload = () => resolve(); + script.onerror = () => reject(new Error(`Failed to load script: ${src}`)); + document.head.appendChild(script); + }); +} \ No newline at end of file diff --git a/frontend/src/pages/Payment.tsx b/frontend/src/pages/Payment.tsx index 3228f1d..1b4dd5e 100644 --- a/frontend/src/pages/Payment.tsx +++ b/frontend/src/pages/Payment.tsx @@ -1,11 +1,19 @@ -import React, { useState } from "react"; +import React, { useState, useEffect } from "react"; import { useNavigate, Link } from "react-router-dom"; import { motion, AnimatePresence } from "framer-motion"; import { useCart } from "../components/CartContext"; import { useNotification } from "../components/NotificationContext"; +import { createPaymentOrder, verifyPayment } from "../lib/api"; +import { loadScript } from "../lib/utils"; + +declare global { + interface Window { + Razorpay: any; + } +} const Payment: React.FC = () => { - const { state, clearCart } = useCart(); + const { state, clearCart, refreshFromServer, syncToBackend } = useCart(); const navigate = useNavigate(); const { notifyBuyItem } = useNotification(); const [paymentMethod, setPaymentMethod] = useState<"card" | "upi" | "wallet" | "netbanking">("card"); @@ -19,12 +27,49 @@ const Payment: React.FC = () => { bank: "", }); const [isProcessing, setIsProcessing] = useState(false); + const [error, setError] = useState(""); + const [razorpayLoaded, setRazorpayLoaded] = useState(false); + const [orderId, setOrderId] = useState(""); + const [isLoading, setIsLoading] = useState(true); const total = state.items.reduce((sum, item) => sum + item.price * item.quantity, 0); const tax = Math.round(total * 0.18); const shipping = total > 0 ? 99 : 0; const finalTotal = total + tax + shipping; + // Load Razorpay script + useEffect(() => { + let isMounted = true; + + const initialize = async () => { + setIsLoading(true); + try { + if (isMounted) { + await refreshFromServer(); + } + if (window.Razorpay) { + if (isMounted) setRazorpayLoaded(true); + } else { + await loadScript("https://checkout.razorpay.com/v1/checkout.js"); + if (isMounted) setRazorpayLoaded(true); + } + } catch (error) { + console.error("Failed to initialize:", error); + if (isMounted) { + setError("Failed to load payment gateway. Please refresh the page."); + } + } finally { + if (isMounted) setIsLoading(false); + } + }; + + initialize(); + + return () => { + isMounted = false; + }; + }, []); + const handleInputChange = (e: React.ChangeEvent) => { const { name, value } = e.target; if (name === "cardNumber") { @@ -42,19 +87,149 @@ const Payment: React.FC = () => { const handlePayment = async (e: React.FormEvent) => { e.preventDefault(); + setError(""); setIsProcessing(true); - // Simulate payment processing - setTimeout(async () => { - setIsProcessing(false); - // Notify for each purchased item - state.items.forEach(item => { - notifyBuyItem(item.name, item.price * item.quantity); + + try { + if (!razorpayLoaded || !window.Razorpay) { + throw new Error("Payment gateway not loaded. Please refresh the page."); + } + + if (state.items.length === 0) { + throw new Error("Your cart is empty. Please add items to cart before proceeding to payment."); + } + try { + await syncToBackend(); + await refreshFromServer(); + } catch (syncError) { + console.warn("Cart sync warning:", syncError); + } + + let orderResponse; + try { + orderResponse = await createPaymentOrder(); + setOrderId(orderResponse.orderId); + } catch (orderError: any) { + if (orderError.status === 401 || orderError.message?.includes("authenticated")) { + setError("Your session has expired. Please login again."); + setTimeout(() => { + navigate("/signin"); + }, 2000); + setIsProcessing(false); + return; + } + throw orderError; + } + + //Initialize Razorpay payment + const options = { + key: orderResponse.key, + amount: orderResponse.order.amount, + currency: orderResponse.order.currency, + name: "UniLoot", + description: `Order for ${state.items.length} item(s)`, + order_id: orderResponse.order.id, + prefill: { + name: formData.cardName || "Customer", + email: "", + contact: "", + }, + theme: { + color: "#4F46E5", + }, + handler: async (response: any) => { + // Payment successful-verify on backend + try { + const verifyResponse = await verifyPayment({ + razorpay_order_id: response.razorpay_order_id, + razorpay_payment_id: response.razorpay_payment_id, + razorpay_signature: response.razorpay_signature, + orderId: orderResponse.orderId, + }); + + if (verifyResponse.success) { + state.items.forEach(item => { + notifyBuyItem(item.name, item.price * item.quantity); + }); + + await clearCart(); + navigate("/cart", { + replace: true, + }); + } else { + setError("Payment verification failed. Please contact support."); + setIsProcessing(false); + setTimeout(() => { + navigate("/cart", { replace: true }); + }, 2000); + } + } catch (verifyError: any) { + console.error("Payment verification error:", verifyError); + setError(verifyError.message || "Payment verification failed. Please contact support."); + setIsProcessing(false); + setTimeout(() => { + navigate("/cart", { replace: true }); + }, 2000); + } + }, + modal: { + ondismiss: () => { + setIsProcessing(false); + }, + }, + }; + + const razorpay = new window.Razorpay(options); + razorpay.on("payment.failed", (response: any) => { + console.error("Payment failed:", response.error); + setError(`Payment failed: ${response.error.description || "Unknown error"}`); + setIsProcessing(false); + setTimeout(() => { + navigate("/cart", { replace: true }); + }, 2000); }); - await clearCart(); - navigate("/success", { replace: true }); - }, 2200); + + razorpay.open(); + } catch (error: any) { + console.error("Payment error:", error); + setError(error.message || "Failed to process payment. Please try again."); + setIsProcessing(false); + setTimeout(() => { + navigate("/cart", { replace: true }); + }, 2000); + } }; + if (isLoading || !razorpayLoaded) { + return ( +
+
+
+

Loading payment gateway...

+
+
+ ); + } + + //if cart is empty + if (state.items.length === 0) { + return ( +
+
+
🛒
+

Your cart is empty

+

Please add items to your cart before proceeding to payment.

+ + Go to Cart + +
+
+ ); + } + return (
@@ -63,6 +238,19 @@ const Payment: React.FC = () => {

Complete your purchase with secure payment

+ {error && ( + +
+ ⚠️ +

{error}

+
+
+ )} +
@@ -75,7 +263,15 @@ const Payment: React.FC = () => { { id: "wallet", name: "Wallet", icon: "👛", color: "from-purple-500 to-purple-700" }, { id: "netbanking", name: "Net Banking", icon: "🏦", color: "from-orange-500 to-orange-700" }, ].map(method => ( - ))}
+
+

+ Note: All payment methods will be processed securely through Razorpay. You will be redirected to Razorpay's secure payment gateway. +

+
-

{paymentMethod === "card" ? "Card Details" : paymentMethod === "upi" ? "UPI Payment" : paymentMethod === "wallet" ? "Digital Wallet" : "Net Banking"}

+

Payment Details

- - {paymentMethod === "card" && ( -
-
- - -
- -
- - -
- -
-
- - -
-
- - -
-
- -
- 🔒 -
-

Secure Payment

-

Your card details are encrypted and secure

-
-
-
- )} - - {paymentMethod === "upi" && ( -
+
+
+
+ 🔒
- - -
- -
- - -
- -
-
- 💡 -
-

Quick Payment

-

You'll be redirected to your UPI app to complete the payment

-
-
+

Secure Payment Gateway

+

Powered by Razorpay

- )} - - {paymentMethod === "wallet" && ( -
-
- -
- {["paytm", "phonepe", "amazonpay", "other"].map((w) => ( - - ))} -
-
+

+ Click the button below to proceed to Razorpay's secure payment gateway. + You can pay using Credit/Debit Cards, UPI, Wallets, or Net Banking. +

+
- {formData.wallet &&
You'll be redirected to {formData.wallet} to complete your payment
} +
+ +
+

100% Secure Transactions

+

Your payment information is encrypted and secure

- )} - - {paymentMethod === "netbanking" && ( -
-
- - -
+
+
-
-
🏦
-

Secure Net Banking

-

You'll be redirected to your bank's secure portal to complete the payment

-
+ + {isProcessing ? ( +
+
+ Processing Payment...
+ ) : ( + `Pay ₹${finalTotal.toLocaleString()}` )} - - - - {isProcessing ?
Processing Payment...
: `Pay ₹${finalTotal.toLocaleString()}`}
@@ -225,4 +372,4 @@ const Payment: React.FC = () => { ); }; -export default Payment; \ No newline at end of file +export default Payment;