Skip to content

Commit

Permalink
created order and payment routes
Browse files Browse the repository at this point in the history
  • Loading branch information
VenketeshRushi committed Aug 22, 2023
1 parent 7c722fb commit 04f783f
Show file tree
Hide file tree
Showing 11 changed files with 511 additions and 332 deletions.
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ const prisma = require("./db.server");
const AuthApiRoutes = require("./module_auth/routes/auth.routes");
const ProductApiRoutes = require("./module_product/routes/product.routes");
const FavouriteApiRoutes = require("./module_favourite/routes/favourite.routes");
const OrderApiRoutes = require("./module_order/routes/order.routes");
const paymentController = require("./payment.controller");

const app = express();

Expand All @@ -15,6 +17,10 @@ app.use(cors());
app.use("/auth", AuthApiRoutes);
app.use("/product", ProductApiRoutes);
app.use("/favourite", FavouriteApiRoutes);
app.use("/order", OrderApiRoutes);

//Razorpay payment
app.use("/api/payment", paymentController);

app.listen(8000, async () => {
try {
Expand Down
83 changes: 83 additions & 0 deletions module_order/controllers/OrderController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
const prisma = require("../../db.server");

exports.createOrder = async (req, res, next) => {
try {
const { orderSummary, cartProducts, shippingDetails, paymentDetails } =
req.body;

const createdOrder = await prisma.order.create({
data: {
subTotal: orderSummary.subTotal,
quantity: orderSummary.quantity,
shipping: orderSummary.shipping,
discount: orderSummary.discount,
total: orderSummary.total,
user: {
connect: { id: req.user.id },
},
PaymentDetails: {
create: {
razorpayOrderId: paymentDetails.razorpayOrderId,
razorpayPaymentId: paymentDetails.razorpayPaymentId,
},
},
ShippingDetails: {
create: {
firstName: shippingDetails.firstName,
lastName: shippingDetails.lastName,
addressLine1: shippingDetails.addressLine1,
addressLine2: shippingDetails.addressLine2,
locality: shippingDetails.locality,
pinCode: shippingDetails.pinCode,
state: shippingDetails.state,
country: shippingDetails.country,
email: shippingDetails.email,
mobile: shippingDetails.mobile,
},
},
cartProducts: {
create: cartProducts.map((product) => ({
title: product.title,
gender: product.gender,
description: product.description,
category: product.category,
price: product.price,
size: product.size,
color: product.color,
rating: product.rating,
img: product.img,
quantity: product.quantity,
user: {
connect: { id: req.user.id },
},
})),
},
},
});

res.status(201).json(createdOrder);
} catch (error) {
console.error(error);
next(error);
}
};

exports.getOrders = async (req, res, next) => {
try {
const orders = await prisma.order.findMany({
where: {
userId: req.user.id,
},
include: {
PaymentDetails: true,
ShippingDetails: true,
cartProducts: true,
},
});

res.status(200).json(orders);
} catch (error) {
console.error(error);
next(error);
}
};
20 changes: 20 additions & 0 deletions module_order/middleware/handleErrors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/* eslint-disable no-unused-vars */
const { GeneralError } = require("../utils/errors");

const handleErrors = (err, req, res, next) => {
if (err instanceof GeneralError) {
return res.json({
status: "error",
message: err.message,
data: err.stack,
});
}

return res.status(200).json({
status: "error",
message: err.message,
data: err.stack,
});
};

module.exports = handleErrors;
16 changes: 16 additions & 0 deletions module_order/routes/order.routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const express = require("express");
const router = express.Router();

const authorization = require("../../module_auth/middleware/authorization");
const OrderController = require("../controllers/OrderController");

// HANDLING ERRORS
router.use(authorization);

// TO CREATE ORDER
router.post("/createorder", authorization, OrderController.createOrder);

// TO GET ORDERS
router.get("/getorders", authorization, OrderController.getOrders);

module.exports = router;
25 changes: 25 additions & 0 deletions module_order/utils/errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/* eslint-disable no-use-before-define */
// eslint-disable-next-line max-classes-per-file
class GeneralError extends Error {
constructor(message) {
super();
this.message = message;
}

getCode() {
if (this instanceof BadRequest) {
return 200;
}
if (this instanceof NotFound) {
return 404;
}
return 500;
}
}

class BadRequest extends GeneralError { }
class NotFound extends GeneralError { }

module.exports = {
GeneralError, BadRequest, NotFound,
};
61 changes: 61 additions & 0 deletions payment.controller.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const router = require("express").Router();
const Razorpay = require("razorpay");
const crypto = require("crypto");

//Saving the order id to use it for verification purpose
let order_id;

//To create order id
router.post("/order", async (req, res) => {
try {
const instance = new Razorpay({
key_id: process.env.RAZORPAY_KEY_ID,
key_secret: process.env.RAZORPAY_KEY_SECRET,
});

const options = {
amount: req.body.amount * 100,
currency: "INR",
receipt: crypto.randomBytes(10).toString("hex"),
};

instance.orders.create(options, (error, order) => {
if (error) {
console.log(error);
return res
.status(500)
.json({ message: "Something went wrong", status: "Failed" });
}
order_id = order.id;
res.status(201).json(order);
});
} catch (error) {
console.log(error);
return res.status(500).json({ message: "Internal server error" });
}
});

//To verify payment
router.post("/verify", async (req, res) => {
try {
const { razorpay_payment_id, razorpay_signature } = req.body;

const sign = order_id + "|" + razorpay_payment_id;

const expectedSign = crypto
.createHmac("sha256", process.env.RAZORPAY_KEY_SECRET)
.update(sign.toString())
.digest("hex");

if (razorpay_signature === expectedSign) {
return res.status(201).json({ message: "Payment verified successfully" });
} else {
return res.status(400).json({ message: "Invalid signature sent!" });
}
} catch (error) {
console.log(error);
return res.status(500).json({ message: "Internal server error" });
}
});

module.exports = router;
1 change: 1 addition & 0 deletions prisma/generated/client/index-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ exports.Prisma.CartProductScalarFieldEnum = {
rating: 'rating',
img: 'img',
quantity: 'quantity',
orderId: 'orderId',
userId: 'userId'
};

Expand Down
Loading

0 comments on commit 04f783f

Please sign in to comment.