mirror of
https://github.com/kevin-DL/complete-node-bootcamp.git
synced 2026-01-15 20:54:53 +00:00
Initial commit 🚀
This commit is contained in:
54
4-natours/after-section-13/controllers/bookingController.js
Normal file
54
4-natours/after-section-13/controllers/bookingController.js
Normal file
@@ -0,0 +1,54 @@
|
||||
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
|
||||
const Tour = require('../models/tourModel');
|
||||
const Booking = require('../models/bookingModel');
|
||||
const catchAsync = require('../utils/catchAsync');
|
||||
const factory = require('./handlerFactory');
|
||||
|
||||
exports.getCheckoutSession = catchAsync(async (req, res, next) => {
|
||||
// 1) Get the currently booked tour
|
||||
const tour = await Tour.findById(req.params.tourId);
|
||||
console.log(tour);
|
||||
|
||||
// 2) Create checkout session
|
||||
const session = await stripe.checkout.sessions.create({
|
||||
payment_method_types: ['card'],
|
||||
success_url: `${req.protocol}://${req.get('host')}/my-tours/?tour=${
|
||||
req.params.tourId
|
||||
}&user=${req.user.id}&price=${tour.price}`,
|
||||
cancel_url: `${req.protocol}://${req.get('host')}/tour/${tour.slug}`,
|
||||
customer_email: req.user.email,
|
||||
client_reference_id: req.params.tourId,
|
||||
line_items: [
|
||||
{
|
||||
name: `${tour.name} Tour`,
|
||||
description: tour.summary,
|
||||
images: [`https://www.natours.dev/img/tours/${tour.imageCover}`],
|
||||
amount: tour.price * 100,
|
||||
currency: 'usd',
|
||||
quantity: 1
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
// 3) Create session as response
|
||||
res.status(200).json({
|
||||
status: 'success',
|
||||
session
|
||||
});
|
||||
});
|
||||
|
||||
exports.createBookingCheckout = catchAsync(async (req, res, next) => {
|
||||
// This is only TEMPORARY, because it's UNSECURE: everyone can make bookings without paying
|
||||
const { tour, user, price } = req.query;
|
||||
|
||||
if (!tour && !user && !price) return next();
|
||||
await Booking.create({ tour, user, price });
|
||||
|
||||
res.redirect(req.originalUrl.split('?')[0]);
|
||||
});
|
||||
|
||||
exports.createBooking = factory.createOne(Booking);
|
||||
exports.getBooking = factory.getOne(Booking);
|
||||
exports.getAllBookings = factory.getAll(Booking);
|
||||
exports.updateBooking = factory.updateOne(Booking);
|
||||
exports.deleteBooking = factory.deleteOne(Booking);
|
||||
Reference in New Issue
Block a user