jonasschmedtmann / complete-node-bootcamp

Starter files, final projects and FAQ for my Complete Node.js Bootcamp
https://www.udemy.com/nodejs-express-mongodb-bootcamp/?couponCode=GITHUB515
3.13k stars 3.63k forks source link

227. Finishing Payments with Stripe Webhooks #233

Open erezamsalem opened 1 month ago

erezamsalem commented 1 month ago

Hello in order to use Sripe successfully without - Axios 500 Error the code in- bookingController.js- should change to:

Lines 8- 35 should be:

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'], mode: 'payment', // Added this line success_url: ${req.protocol}://${req.get('host')}/my-tours?alert=booking, cancel_url: ${req.protocol}://${req.get('host')}/tour/${tour.slug}, customer_email: req.user.email, client_reference_id: req.params.tourId, line_items: [ { price_data: { currency: 'usd', product_data: { name: ${tour.name} Tour, description: tour.summary, images: [${req.protocol}://${req.get('host')}/img/tours/${tour.imageCover}], }, unit_amount: tour.price * 100, }, quantity: 1, }, ], })

Lines 51-69 should be:

const createBookingCheckout = async session => { const tour = session.client_reference_id; const user = (await User.findOne({ email: session.customer_email })).id; const price = session.amount_total / 100; // Updated to use amount_total await Booking.create({ tour, user, price }); };

exports.webhookCheckout = (req, res, next) => { const signature = req.headers['stripe-signature'];

let event; try { event = stripe.webhooks.constructEvent( req.body, signature, process.env.STRIPE_WEBHOOK_SECRET ); } catch (err) { return res.status(400).send(Webhook error: ${err.message}); }

if (event.type === 'checkout.session.completed') createBookingCheckout(event.data.object);

res.status(200).json({ received: true }); };

qadzek commented 1 week ago

Thank you. I can confirm that this approach makes the webhooks work. The most important line for me to change was: const price = session.amount_total / 100;