From 3f8776af1e122ac4d5f55c5a660335aad70ecc8c Mon Sep 17 00:00:00 2001 From: yashrajverma Date: Fri, 4 Jun 2021 11:26:50 +0530 Subject: [PATCH] Payment purchase date --- controllers/payment.js | 358 ++++++++++++++++++++--------------------- models/Order.js | 49 +++--- 2 files changed, 199 insertions(+), 208 deletions(-) diff --git a/controllers/payment.js b/controllers/payment.js index 57ff4fa..685b72d 100644 --- a/controllers/payment.js +++ b/controllers/payment.js @@ -1,197 +1,187 @@ -const razorpay = require('razorpay') ; -const Order = require('../models/Order') ; -const User = require('../models/User') ; -const CourseType = require('../models/CourseType') ; -const Course = require('../models/Course') ; -const Student = require('../models/Student') ; -const Coupon = require('../models/Coupon') ; -const { getAllCoupons } = require('./coupon'); +const razorpay = require("razorpay"); +const Order = require("../models/Order"); +const User = require("../models/User"); +const CourseType = require("../models/CourseType"); +const Course = require("../models/Course"); +const Student = require("../models/Student"); +const Coupon = require("../models/Coupon"); +const { getAllCoupons } = require("./coupon"); //test credentials of razorpay const instance = new razorpay({ - key_id : process.env.KEY_ID , - key_secret : process.env.KEY_SECRET -}) ; + key_id: process.env.KEY_ID, + key_secret: process.env.KEY_SECRET, +}); -module.exports.postVerify =async (req , res , next) => { +module.exports.postVerify = async (req, res, next) => { + try { + //Secret we put in razorpay + const SECRET = "CantileverLabs"; - try - { - //Secret we put in razorpay - const SECRET = 'CantileverLabs' ; + const crypto = require("crypto"); - const crypto = require('crypto') - - const shasum = crypto.createHmac('sha256', SECRET) ; - shasum.update(JSON.stringify(req.body)) - const digest = shasum.digest('hex') - - //if secret is matched - if (digest === req.headers['x-razorpay-signature']) { - console.log('request is legit') - // process it - const orderId = req.body.payload.payment.entity.order_id ; - //fetching the order from the orderId - let order = await Order.findOne({orderId:orderId}) ; - let courseId = order.course ; - //adding the payment detail - order.paymentDetail = req.body.payload.payment ; - //making the paymentSuccess as true - order.paymentSuccess = true ; - - //now getting the details of user which has bought this course - const userId = order.user ; - let user = await User.findById(userId) ; - let student =await Student.findById(user.student) ; + const shasum = crypto.createHmac("sha256", SECRET); + shasum.update(JSON.stringify(req.body)); + const digest = shasum.digest("hex"); - let ind = -1 ; - //checking whether user has already bought this course or not - if(student.courses) - { - ind = student.courses.findIndex(course => String(course.basicInfo) == String(courseId)) ; - } - console.log(ind); - if(ind == -1) - { - //adding a new object in the courses array of student - let newObj = { - basicInfo : courseId , - details : { - completed : [] - } - } - let courses = [...student.courses] ; - courses.push(newObj) ; - student.courses = courses ; - await student.save() ; - await order.save() ; - res.status(200).json({ - status : 'ok' - }) ; - } - else - { - //user has already bought this course - res.status(200).json({ - error:'already paid' - }) - } + //if secret is matched + if (digest === req.headers["x-razorpay-signature"]) { + console.log("request is legit"); + // process it + const orderId = req.body.payload.payment.entity.order_id; + //fetching the order from the orderId + let order = await Order.findOne({ orderId: orderId }); + let courseId = order.course; + //adding the payment detail + order.paymentDetail = req.body.payload.payment; + //making the paymentSuccess as true + order.paymentSuccess = true; - //now updating that course in user also - //console.log(req.body.payload.payment) ; - //require('fs').writeFileSync('payment1.json', JSON.stringify(req.body, null, 4)) - - } - else { - // pass it - console.log("HELLO IN ERROR"); - res.status(200).json({ - error:'error' - }) - } + //now getting the details of user which has bought this course + const userId = order.user; + let user = await User.findById(userId); + let student = await Student.findById(user.student); + + let ind = -1; + //checking whether user has already bought this course or not + if (student.courses) { + ind = student.courses.findIndex( + (course) => String(course.basicInfo) == String(courseId) + ); + } + console.log(ind); + if (ind == -1) { + //adding a new object in the courses array of student + let newObj = { + basicInfo: courseId, + details: { + completed: [], + }, + }; + let courses = [...student.courses]; + courses.push(newObj); + student.courses = courses; + await student.save(); + await order.save(); + res.status(200).json({ + status: "ok", + }); + } else { + //user has already bought this course + res.status(200).json({ + error: "already paid", + }); + } + + //now updating that course in user also + //console.log(req.body.payload.payment) ; + //require('fs').writeFileSync('payment1.json', JSON.stringify(req.body, null, 4)) + } else { + // pass it + console.log("HELLO IN ERROR"); + res.status(200).json({ + error: "error", + }); } - catch(err) - { - console.log(err); + } catch (err) { + console.log(err); + } +}; + +module.exports.postRazorpay = async (req, res, next) => { + try { + //this route will be called after clicking the payment + + //here this is the id of courseType + const courseId = req.body.courseId; + const couponCode = req.body.couponCode; + const userId = req.user._id; + + console.log( + "Course ID =", + courseId, + " Coupon code =", + couponCode, + " user ID =", + userId + ); + + let user = await User.findById(userId); + let student = await Student.findById(user.student); + let course = await CourseType.findById(courseId); + + console.log(student.courses); + //we are creating a new order associated to it + //we are setting the paymentSuccess to be false + + let discount = 0; + + let coupon = await Coupon.findOne({ couponCode: couponCode }); + if (coupon && coupon.numAllowed > 0) { + discount = coupon.percentage; } - -} ; - -module.exports.postRazorpay = async (req , res , next) => { - try - { - - //this route will be called after clicking the payment - - //here this is the id of courseType - const courseId = req.body.courseId ; - const couponCode = req.body.couponCode ; - const userId = req.user._id ; - - console.log("Course ID =" ,courseId ," Coupon code =" , couponCode ," user ID =" , userId) ; - - let user = await User.findById(userId) ; - let student =await Student.findById(user.student) ; - let course =await CourseType.findById(courseId) ; - - console.log(student.courses); - //we are creating a new order associated to it - //we are setting the paymentSuccess to be false - - let discount = 0 ; - - let coupon = await Coupon.findOne({couponCode : couponCode}) ; - if(coupon && coupon.numAllowed > 0) - { - discount = coupon.percentage ; - } - - let ind = -1 ; - //checking whether user has already bought this course or not - if(student.courses) - { - ind = student.courses.findIndex(course => String(course.basicInfo) == String(courseId)) ; - } - console.log(ind); - if(ind == -1) - { - let order = new Order({ - course : courseId , - user : userId , - paymentSuccess : false - }) ; - - order = await order.save() ; - - const payment_capture = 1 ; - - //setting the amount according to the course - let amount = Number(course.amount) ; - - amount = amount - amount*discount/100 ; - - amount = Math.ceil(amount) ; - - const options = {amount : (amount*100).toString() - , currency : "INR" - , receipt : order._id.toString() - , payment_capture - } ; - - //this is a razorpay feature - const response = await instance.orders.create(options) ; - - order.orderId = response.id ; - await order.save() ; - res.status(200).json({ - id:response.id , - currency : response.currency , - amount : response.amount , - name:(user.firstName + " " + user.lastName) , - email:user.email , - receipt : response.receipt - }); - if(coupon && coupon.numAllowed > 0) - { - coupon.numAllowed = coupon.numAllowed - 1 ; - await coupon.save() ; - } - } - else - { - //user has already bought this course - res.status(500).json({ - error:'already paid' - }) - } + let ind = -1; + //checking whether user has already bought this course or not + if (student.courses) { + ind = student.courses.findIndex( + (course) => String(course.basicInfo) == String(courseId) + ); } - catch(err) - { - console.log(err); - res.status(500).json({ - error : "error" - }) - } -} + console.log(ind); + if (ind == -1) { + let order = new Order({ + course: courseId, + user: userId, + paymentSuccess: false, + date_purchased: Date.now().toString(), + }); + order = await order.save(); + + const payment_capture = 1; + + //setting the amount according to the course + let amount = Number(course.amount); + + amount = amount - (amount * discount) / 100; + + amount = Math.ceil(amount); + + const options = { + amount: (amount * 100).toString(), + currency: "INR", + receipt: order._id.toString(), + payment_capture, + }; + + //this is a razorpay feature + const response = await instance.orders.create(options); + + order.orderId = response.id; + await order.save(); + res.status(200).json({ + id: response.id, + currency: response.currency, + amount: response.amount, + name: user.firstName + " " + user.lastName, + email: user.email, + receipt: response.receipt, + }); + if (coupon && coupon.numAllowed > 0) { + coupon.numAllowed = coupon.numAllowed - 1; + await coupon.save(); + } + } else { + //user has already bought this course + res.status(500).json({ + error: "already paid", + }); + } + } catch (err) { + console.log(err); + res.status(500).json({ + error: "error", + }); + } +}; diff --git a/models/Order.js b/models/Order.js index 2be1af8..d2a1930 100644 --- a/models/Order.js +++ b/models/Order.js @@ -1,28 +1,29 @@ -const mongoose = require('mongoose') ; +const mongoose = require("mongoose"); -const Schema = mongoose.Schema ; +const Schema = mongoose.Schema; const orderSchema = new Schema({ - user : { - type:mongoose.Types.ObjectId , - ref:'User' , - required:true - } , - course : { - type: mongoose.Types.ObjectId , - ref : 'CourseType' , - required : true - }, - paymentSuccess : { - type:Boolean , - required : true - } , - paymentDetail : { - type:Object - } , - orderId : { - type : String - } -}) ; + user: { + type: mongoose.Types.ObjectId, + ref: "User", + required: true, + }, + course: { + type: mongoose.Types.ObjectId, + ref: "CourseType", + required: true, + }, + paymentSuccess: { + type: Boolean, + required: true, + }, + paymentDetail: { + type: Object, + }, + orderId: { + type: String, + }, + date_purchased: { type: Date }, +}); -module.exports = mongoose.model('Order' , orderSchema) ; \ No newline at end of file +module.exports = mongoose.model("Order", orderSchema);