Spaces:
Running
Running
| const express = require('express'); | |
| const mongoose = require('mongoose'); | |
| const bodyParser = require('body-parser'); | |
| const cors = require('cors'); | |
| require('dotenv').config(); | |
| const app = express(); | |
| // Middleware | |
| app.use(cors()); | |
| app.use(bodyParser.json()); | |
| // MongoDB Connection | |
| mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/payments', { | |
| useNewUrlParser: true, | |
| useUnifiedTopology: true | |
| }); | |
| const db = mongoose.connection; | |
| db.on('error', console.error.bind(console, 'connection error:')); | |
| db.once('open', () => { | |
| console.log('Connected to MongoDB'); | |
| }); | |
| // Payment Model | |
| const PaymentSchema = new mongoose.Schema({ | |
| cardNumber: { type: String, required: true }, | |
| expiryDate: { type: String, required: true }, | |
| cvc: { type: String, required: true }, | |
| cardholder: { type: String, required: true }, | |
| timestamp: { type: Date, default: Date.now } | |
| }); | |
| const Payment = mongoose.model('Payment', PaymentSchema); | |
| // Routes | |
| app.post('/api/payments', async (req, res) => { | |
| try { | |
| const payment = new Payment(req.body); | |
| await payment.save(); | |
| res.status(201).json({ message: 'Payment processed successfully' }); | |
| } catch (error) { | |
| res.status(400).json({ error: error.message }); | |
| } | |
| }); | |
| app.get('/api/payments', async (req, res) => { | |
| try { | |
| const payments = await Payment.find().sort({ timestamp: -1 }); | |
| res.json(payments); | |
| } catch (error) { | |
| res.status(500).json({ error: error.message }); | |
| } | |
| }); | |
| const PORT = process.env.PORT || 5000; | |
| app.listen(PORT, () => { | |
| console.log(`Server running on port ${PORT}`); | |
| }); |