Skip to content

Commit

Permalink
modify the payment method and verification complete and added the pos…
Browse files Browse the repository at this point in the history
…t hook to create order
  • Loading branch information
SalmanAd01 committed Nov 5, 2022
1 parent 3c90a16 commit dc12af7
Show file tree
Hide file tree
Showing 10 changed files with 7,462 additions and 6,378 deletions.
2 changes: 1 addition & 1 deletion controllers/seller.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const getDashbord = async (req, res) => {
}
}
]);
console.log(foodwithandwithoutoffer);
// console.log(foodwithandwithoutoffer);
res.render('index', {
persist: req.persist,
food: foodwithandwithoutoffer,
Expand Down
2 changes: 2 additions & 0 deletions model/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const Rating = require('./rating');
const Seller = require('./seller');
const Offer = require('./offer');
const Cart = require('./cart');
const Payment = require('./payment');
module.exports = {
model: [
User,
Expand All @@ -14,5 +15,6 @@ module.exports = {
Seller,
Offer,
Cart,
Payment
],
};
1 change: 1 addition & 0 deletions model/order.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const OrderSchema = new mongoose.Schema({
},
quantity: {
type: Number,
default: 1,
required: [true, 'Please enter quantity'],
trim: true,
},
Expand Down
88 changes: 59 additions & 29 deletions model/payment.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,64 @@
const mongoose = require('mongoose')

const Order = require('./order')
const paymentDetailsSchema = new mongoose.Schema({
orderId: {
type: String,
required: true
},
amount: {
type: Number
},
receiptId: {
type: String
},
paymentId: {
type: String,
},
signature: {
type: String,
},
email: {
type: String
},
contact: {
type: String
},
createdAt: {
type: Date
},
status: {
type: String
}
orderId: {
type: String,
required: true
},
foodId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Food',
required: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
amount: {
type: Number,
required: true
},
receiptId: {
type: String,
required: true
},
paymentId: {
type: String,
},
signature: {
type: String,
},
email: {
type: String
},
contact: {
type: String
},
createdAt: {
type: Date
},
status: {
type: String
}
});

// when we findOneAndUpdate, if the status is paid, then we need to create the order model
paymentDetailsSchema.post('findOneAndUpdate', async function (doc) {
if (doc.status === 'paid') {
const order = new Order({
userId: doc.userId,
orderDetails: [{
foodId: doc.foodId,
quantity: 1,
price: doc.amount
}],
totalAmount: doc.amount,
paymentType: 'razorpay',
paymentStatus: 'paid'
})
await order.save()
}
})

module.exports = mongoose.model('PaymentDetail', paymentDetailsSchema)
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"mongoose": "^6.5.4",
"mongoose-unique-validator": "^3.1.0",
"multer": "^1.4.5-lts.1",
"nanoid": "3.3.2",
"pino": "^8.7.0",
"pino-pretty": "^9.1.1",
"razorpay": "^2.8.3",
Expand Down
217 changes: 153 additions & 64 deletions routes/razorpay.js
Original file line number Diff line number Diff line change
@@ -1,74 +1,163 @@
const express = require('express');
const app = express.Router();
const router = express.Router();
const Razorpay = require('razorpay');
const PaymentDetail = require('../model/payment');
const crypto = require('crypto');

app.post('/', async (req, res) => {
try{
let {amount} = req.body;
console.log('payment');
var instance = new Razorpay({
key_id: process.env.KEY_ID,
key_secret: process.env.KEY_SECRET,
const Food = require('../model/food');
const auth = require('../middleware/auth');
const { checkIfUser } = require('../middleware/requiredUser');
const checkMongooseId = require('../middleware/mongooseId');
const { default: mongoose } = require('mongoose');
const { nanoid } = require('nanoid');
const instance = new Razorpay({
key_id: process.env.KEY_ID,
key_secret: process.env.KEY_SECRET
});
router.post('/verify', async (req, res) => {
try {
console.log("verify");
console.log(req.body);
const hmac = crypto.createHmac('sha256', process.env.KEY_SECRET);
hmac.update(req.body.razorpay_order_id + '|' + req.body.razorpay_payment_id);
const digest = hmac.digest('hex');
if (digest === req.body.razorpay_signature) {
const paymentData = await instance.payments.fetch(req.body.razorpay_payment_id);
await PaymentDetail.findOneAndUpdate({ orderId: req.body.razorpay_order_id }, {
paymentId: req.body.razorpay_payment_id,
signature: req.body.razorpay_signature,
status: 'paid',
email: paymentData.email,
contact: paymentData.contact
}, { new: true });
return res.status(200).json({
message: 'Payment Successful'
});
} else {
return res.status(500).json({
message: 'Something Went Wrong'
});
}
}
catch (e) {
console.log(e);
res.status(500).json({
message: 'Something Went Wrong'
});
}
})
router.post('/:id', checkMongooseId, auth, checkIfUser, async (req, res) => {
console.log(req.params.id);
try {
// check if food is available and has any offer
const actualPrice = await Food.aggregate([
{
$match: {
_id: mongoose.Types.ObjectId(req.params.id),
isAvailable: true,
},
},
{
$lookup: {
from: 'offers',
localField: '_id',
foreignField: 'food',
as: 'offer',
},
},
{
$project: {
_id: 1,
name: 1,
price: 1,
offer: {
$filter: {
input: '$offer',
as: 'offer',
cond: {
$gte: ['$$offer.validTill', new Date()]
}
},
}
},
},
{
$project: {
_id: 1,
name: 1,
price: 1,
offer: {
$cond: {
if: {
$eq: [
{
$size: '$offer'
},
0
]
},
then: 0,
else: {
$arrayElemAt: ['$offer', 0]
}
}
},
},
},
{
$project: {
_id: 1,
name: 1,
price: 1,
offer: 1,
actual: {
$cond: {
if: { $eq: ['$offer', 0] },
then: '$price',
else: '$offer.newprice',

await instance.orders.create({
amount: amount * 100,
currency: "INR",
receipt: "receipt#1",
}).then(async (response) => {
// Save orderId and other payment details
const paymentDetail = new PaymentDetail({
orderId: response.id,
receiptId: response.receipt,
amount: response.amount,
currency: response.currency,
createdAt: response.created_at,
status: response.status
})

try {
// Render Order Confirmation page if saved succesfully
await paymentDetail.save()
res.status(201).json({
success: true,
order:response,
amount,
});

} catch (err) {
// Throw err if failed to save
if (err) throw err;
}
}
}
},
},
{
$project: {
_id: 1,
name: 1,
price: '$actual',
},
}
])
const options = {
amount: actualPrice[0].price * 100,
currency: 'INR',
receipt: nanoid(),
payment_capture: 1
};
instance.orders.create(options, async (err, order) => {
if (err) {
console.log(err);
return res.status(500).json({
message: 'Something Went Wrong'
});
}
const paymentDetail = new PaymentDetail({
userId: req.user._id,
foodId: req.params.id,
orderId: order.id,
amount: order.amount,
currency: order.currency,
receiptId: order.receipt,
status: order.status
});
await paymentDetail.save();
return res.status(200).json({ order, paymentDetail });
});
} catch (e) {
console.log(e);
res.status(500).json({
message: 'Something Went Wrong'
});
}
catch (err) {
console.log(err);
res.status(500).json({ error: 'Error creating user' });
}
});

app.post('/verify', (req, res) => {
try {
const { razorpay_order_id, razorpay_payment_id, razorpay_signature } =
req.body;
const sign = razorpay_order_id + "|" + razorpay_payment_id;
const expectedSign = crypto
.createHmac("sha256", process.env.KEY_SECRET)
.update(sign.toString())
.digest("hex");

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

}
})

module.exports = app;
module.exports = router;
Loading

0 comments on commit dc12af7

Please sign in to comment.