Files
Backend/src/routes/stripe.js

50 lines
1.3 KiB
JavaScript

import express, { Router } from 'express';
import Stripe from 'stripe';
import { query } from '../db.js';
const router = Router();
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY || '', {
apiVersion: '2024-06-20'
});
router.post('/api/stripe/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
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 alairas hiba.');
}
if (event.type === 'payment_intent.succeeded') {
const intent = event.data.object;
const amount = Number(intent.amount || 0);
const userId = Number(intent.metadata?.userId || 0);
if (userId && amount) {
const rows = await query(
'SELECT status FROM deposits WHERE stripe_payment_intent_id = ?',
[intent.id]
);
const status = rows[0]?.status;
if (status !== 'succeeded') {
await query(
'UPDATE deposits SET status = ? WHERE stripe_payment_intent_id = ?',
['succeeded', intent.id]
);
await query('UPDATE users SET balance = balance + ? WHERE id = ?', [amount, userId]);
}
}
}
return res.json({ received: true });
});
export default router;