legendaryjs
Version:
LegendaryJS – The ultimate backend framework for speed, power, and simplicity.
50 lines (38 loc) • 1.66 kB
JavaScript
// hooks/webhook.js
require('dotenv').config();
const config = require('./legendary.config');
const stripe = require('stripe')(process.env.STRIPE_SECRET || 'sk_test_placeholder');
const bodyParser = require('body-parser');
function registerWebhooks(app) {
if (!config.webhooks) return;
app.post('/webhook/stripe', bodyParser.raw({ type: 'application/json' }), (req, res) => {
const sig = req.headers['stripe-signature'];
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET || 'whsec_placeholder';
let event;
try {
event = stripe.webhooks.constructEvent(req.body, sig, endpointSecret);
} catch (err) {
console.error('⚠️ Stripe webhook error:', err.message);
return res.status(400).send(`Webhook Error: ${err.message}`);
}
switch (event.type) {
case 'payment_intent.succeeded':
console.log('✅ Stripe Payment Succeeded:', event.data.object);
break;
case 'payment_intent.payment_failed':
console.log('❌ Stripe Payment Failed:', event.data.object);
break;
}
res.status(200).json({ received: true });
});
app.post('/webhook/paypal', bodyParser.json(), (req, res) => {
const eventBody = req.body;
console.log('📩 PayPal Webhook Event:', eventBody.event_type);
if (eventBody.event_type === 'CHECKOUT.ORDER.APPROVED') {
console.log('✅ PayPal Order Approved:', eventBody.resource);
}
res.status(200).json({ received: true });
});
console.log('📡 Webhook endpoints ready at /webhook/stripe & /webhook/paypal');
}
module.exports = { registerWebhooks };