Payment purchase date

This commit is contained in:
yashrajverma 2021-06-04 11:26:50 +05:30
parent 375a1fe0b5
commit 3f8776af1e
2 changed files with 199 additions and 208 deletions

View File

@ -1,34 +1,32 @@
const razorpay = require('razorpay') ; const razorpay = require("razorpay");
const Order = require('../models/Order') ; const Order = require("../models/Order");
const User = require('../models/User') ; const User = require("../models/User");
const CourseType = require('../models/CourseType') ; const CourseType = require("../models/CourseType");
const Course = require('../models/Course') ; const Course = require("../models/Course");
const Student = require('../models/Student') ; const Student = require("../models/Student");
const Coupon = require('../models/Coupon') ; const Coupon = require("../models/Coupon");
const { getAllCoupons } = require('./coupon'); const { getAllCoupons } = require("./coupon");
//test credentials of razorpay //test credentials of razorpay
const instance = new razorpay({ const instance = new razorpay({
key_id: process.env.KEY_ID, key_id: process.env.KEY_ID,
key_secret : process.env.KEY_SECRET key_secret: process.env.KEY_SECRET,
}); });
module.exports.postVerify = async (req, res, next) => { module.exports.postVerify = async (req, res, next) => {
try {
try
{
//Secret we put in razorpay //Secret we put in razorpay
const SECRET = 'CantileverLabs' ; const SECRET = "CantileverLabs";
const crypto = require('crypto') const crypto = require("crypto");
const shasum = crypto.createHmac('sha256', SECRET) ; const shasum = crypto.createHmac("sha256", SECRET);
shasum.update(JSON.stringify(req.body)) shasum.update(JSON.stringify(req.body));
const digest = shasum.digest('hex') const digest = shasum.digest("hex");
//if secret is matched //if secret is matched
if (digest === req.headers['x-razorpay-signature']) { if (digest === req.headers["x-razorpay-signature"]) {
console.log('request is legit') console.log("request is legit");
// process it // process it
const orderId = req.body.payload.payment.entity.order_id; const orderId = req.body.payload.payment.entity.order_id;
//fetching the order from the orderId //fetching the order from the orderId
@ -46,62 +44,52 @@ module.exports.postVerify =async (req , res , next) => {
let ind = -1; let ind = -1;
//checking whether user has already bought this course or not //checking whether user has already bought this course or not
if(student.courses) if (student.courses) {
{ ind = student.courses.findIndex(
ind = student.courses.findIndex(course => String(course.basicInfo) == String(courseId)) ; (course) => String(course.basicInfo) == String(courseId)
);
} }
console.log(ind); console.log(ind);
if(ind == -1) if (ind == -1) {
{
//adding a new object in the courses array of student //adding a new object in the courses array of student
let newObj = { let newObj = {
basicInfo: courseId, basicInfo: courseId,
details: { details: {
completed : [] completed: [],
} },
} };
let courses = [...student.courses]; let courses = [...student.courses];
courses.push(newObj); courses.push(newObj);
student.courses = courses; student.courses = courses;
await student.save(); await student.save();
await order.save(); await order.save();
res.status(200).json({ res.status(200).json({
status : 'ok' status: "ok",
}); });
} } else {
else
{
//user has already bought this course //user has already bought this course
res.status(200).json({ res.status(200).json({
error:'already paid' error: "already paid",
}) });
} }
//now updating that course in user also //now updating that course in user also
//console.log(req.body.payload.payment) ; //console.log(req.body.payload.payment) ;
//require('fs').writeFileSync('payment1.json', JSON.stringify(req.body, null, 4)) //require('fs').writeFileSync('payment1.json', JSON.stringify(req.body, null, 4))
} else {
}
else {
// pass it // pass it
console.log("HELLO IN ERROR"); console.log("HELLO IN ERROR");
res.status(200).json({ res.status(200).json({
error:'error' error: "error",
}) });
} }
} } catch (err) {
catch(err)
{
console.log(err); console.log(err);
} }
}; };
module.exports.postRazorpay = async (req, res, next) => { module.exports.postRazorpay = async (req, res, next) => {
try try {
{
//this route will be called after clicking the payment //this route will be called after clicking the payment
//here this is the id of courseType //here this is the id of courseType
@ -109,7 +97,14 @@ module.exports.postRazorpay = async (req , res , next) => {
const couponCode = req.body.couponCode; const couponCode = req.body.couponCode;
const userId = req.user._id; const userId = req.user._id;
console.log("Course ID =" ,courseId ," Coupon code =" , couponCode ," user ID =" , userId) ; console.log(
"Course ID =",
courseId,
" Coupon code =",
couponCode,
" user ID =",
userId
);
let user = await User.findById(userId); let user = await User.findById(userId);
let student = await Student.findById(user.student); let student = await Student.findById(user.student);
@ -122,24 +117,24 @@ module.exports.postRazorpay = async (req , res , next) => {
let discount = 0; let discount = 0;
let coupon = await Coupon.findOne({ couponCode: couponCode }); let coupon = await Coupon.findOne({ couponCode: couponCode });
if(coupon && coupon.numAllowed > 0) if (coupon && coupon.numAllowed > 0) {
{
discount = coupon.percentage; discount = coupon.percentage;
} }
let ind = -1; let ind = -1;
//checking whether user has already bought this course or not //checking whether user has already bought this course or not
if(student.courses) if (student.courses) {
{ ind = student.courses.findIndex(
ind = student.courses.findIndex(course => String(course.basicInfo) == String(courseId)) ; (course) => String(course.basicInfo) == String(courseId)
);
} }
console.log(ind); console.log(ind);
if(ind == -1) if (ind == -1) {
{
let order = new Order({ let order = new Order({
course: courseId, course: courseId,
user: userId, user: userId,
paymentSuccess : false paymentSuccess: false,
date_purchased: Date.now().toString(),
}); });
order = await order.save(); order = await order.save();
@ -149,14 +144,15 @@ module.exports.postRazorpay = async (req , res , next) => {
//setting the amount according to the course //setting the amount according to the course
let amount = Number(course.amount); let amount = Number(course.amount);
amount = amount - amount*discount/100 ; amount = amount - (amount * discount) / 100;
amount = Math.ceil(amount); amount = Math.ceil(amount);
const options = {amount : (amount*100).toString() const options = {
, currency : "INR" amount: (amount * 100).toString(),
, receipt : order._id.toString() currency: "INR",
, payment_capture receipt: order._id.toString(),
payment_capture,
}; };
//this is a razorpay feature //this is a razorpay feature
@ -168,30 +164,24 @@ module.exports.postRazorpay = async (req , res , next) => {
id: response.id, id: response.id,
currency: response.currency, currency: response.currency,
amount: response.amount, amount: response.amount,
name:(user.firstName + " " + user.lastName) , name: user.firstName + " " + user.lastName,
email: user.email, email: user.email,
receipt : response.receipt receipt: response.receipt,
}); });
if(coupon && coupon.numAllowed > 0) if (coupon && coupon.numAllowed > 0) {
{
coupon.numAllowed = coupon.numAllowed - 1; coupon.numAllowed = coupon.numAllowed - 1;
await coupon.save(); await coupon.save();
} }
} } else {
else
{
//user has already bought this course //user has already bought this course
res.status(500).json({ res.status(500).json({
error:'already paid' error: "already paid",
}) });
} }
} } catch (err) {
catch(err)
{
console.log(err); console.log(err);
res.status(500).json({ res.status(500).json({
error : "error" error: "error",
}) });
} }
} };

View File

@ -1,28 +1,29 @@
const mongoose = require('mongoose') ; const mongoose = require("mongoose");
const Schema = mongoose.Schema; const Schema = mongoose.Schema;
const orderSchema = new Schema({ const orderSchema = new Schema({
user: { user: {
type: mongoose.Types.ObjectId, type: mongoose.Types.ObjectId,
ref:'User' , ref: "User",
required:true required: true,
}, },
course: { course: {
type: mongoose.Types.ObjectId, type: mongoose.Types.ObjectId,
ref : 'CourseType' , ref: "CourseType",
required : true required: true,
}, },
paymentSuccess: { paymentSuccess: {
type: Boolean, type: Boolean,
required : true required: true,
}, },
paymentDetail: { paymentDetail: {
type:Object type: Object,
}, },
orderId: { orderId: {
type : String type: String,
} },
date_purchased: { type: Date },
}); });
module.exports = mongoose.model('Order' , orderSchema) ; module.exports = mongoose.model("Order", orderSchema);