Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

227. Finishing Payments with Stripe Webhooks #233

Open
erezamsalem opened this issue Sep 17, 2024 · 1 comment
Open

227. Finishing Payments with Stripe Webhooks #233

erezamsalem opened this issue Sep 17, 2024 · 1 comment

Comments

@erezamsalem
Copy link

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
Copy link

qadzek commented Oct 22, 2024

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants