From 686d20eccfce43a66360a056c0e1cd44cf332cb4 Mon Sep 17 00:00:00 2001 From: 2ManyProjects Date: Sat, 26 Apr 2025 21:43:06 -0500 Subject: [PATCH] fixed webhook endpoint --- backend/src/routes/stripePayment.js | 129 ++++++++++++++-------------- 1 file changed, 65 insertions(+), 64 deletions(-) diff --git a/backend/src/routes/stripePayment.js b/backend/src/routes/stripePayment.js index ecc9f60..503d67a 100644 --- a/backend/src/routes/stripePayment.js +++ b/backend/src/routes/stripePayment.js @@ -4,6 +4,71 @@ const stripe = require('stripe'); const config = require('../config'); module.exports = (pool, query, authMiddleware) => { + + // Webhook to handle events from Stripe + router.post('/webhook', express.raw({type: 'application/json'}), async (req, res) => { + // This needs to be called with raw body data + const payload = req.body; + const sig = req.headers['stripe-signature']; + + let event; + + try { + // Verify the webhook signature + const webhookSecret = config.payment?.stripeWebhookSecret; + if (!webhookSecret) { + throw new Error('Stripe webhook secret is not configured'); + } + + event = stripeClient.webhooks.constructEvent(payload, sig, webhookSecret); + + // Handle the event + switch (event.type) { + case 'checkout.session.completed': + const session = event.data.object; + + // Check if payment was successful + if (session.payment_status === 'paid') { + // Get metadata + const { order_id, user_id } = session.metadata; + + if (order_id) { + // Update order status in database + await query( + 'UPDATE orders SET status = $1, payment_completed = true, payment_id = $2 WHERE id = $3', + ['processing', session.id, order_id] + ); + + console.log(`Payment completed for order ${order_id}`); + } + } + break; + + case 'payment_intent.payment_failed': + const paymentIntent = event.data.object; + console.log(`Payment failed: ${paymentIntent.last_payment_error?.message}`); + + // Handle failed payment + if (paymentIntent.metadata?.order_id) { + await query( + 'UPDATE orders SET status = $1, payment_notes = $2 WHERE id = $3', + ['payment_failed', 'Payment attempt failed', paymentIntent.metadata.order_id] + ); + } + break; + + default: + console.log(`Unhandled event type ${event.type}`); + } + + // Return a 200 success response + res.status(200).send(); + } catch (err) { + console.error(`Webhook Error: ${err.message}`); + return res.status(400).send(`Webhook Error: ${err.message}`); + } + }); + // Apply authentication middleware to all routes router.use(authMiddleware); @@ -120,70 +185,6 @@ module.exports = (pool, query, authMiddleware) => { next(error); } }); - - // Webhook to handle events from Stripe - router.post('/webhook', express.raw({type: 'application/json'}), async (req, res) => { - // This needs to be called with raw body data - const payload = req.body; - const sig = req.headers['stripe-signature']; - - let event; - - try { - // Verify the webhook signature - const webhookSecret = config.payment?.stripeWebhookSecret; - if (!webhookSecret) { - throw new Error('Stripe webhook secret is not configured'); - } - - event = stripeClient.webhooks.constructEvent(payload, sig, webhookSecret); - - // Handle the event - switch (event.type) { - case 'checkout.session.completed': - const session = event.data.object; - - // Check if payment was successful - if (session.payment_status === 'paid') { - // Get metadata - const { order_id, user_id } = session.metadata; - - if (order_id) { - // Update order status in database - await query( - 'UPDATE orders SET status = $1, payment_completed = true, payment_id = $2 WHERE id = $3', - ['processing', session.id, order_id] - ); - - console.log(`Payment completed for order ${order_id}`); - } - } - break; - - case 'payment_intent.payment_failed': - const paymentIntent = event.data.object; - console.log(`Payment failed: ${paymentIntent.last_payment_error?.message}`); - - // Handle failed payment - if (paymentIntent.metadata?.order_id) { - await query( - 'UPDATE orders SET status = $1, payment_notes = $2 WHERE id = $3', - ['payment_failed', 'Payment attempt failed', paymentIntent.metadata.order_id] - ); - } - break; - - default: - console.log(`Unhandled event type ${event.type}`); - } - - // Return a 200 success response - res.status(200).send(); - } catch (err) { - console.error(`Webhook Error: ${err.message}`); - return res.status(400).send(`Webhook Error: ${err.message}`); - } - }); router.get('/config', async (req, res, next) => { try { res.json({