Skip to content

227. Finishing Payments with Stripe Webhooks #233

Description

@erezamsalem

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 });
};

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions