const express = require('express');
const axios = require('axios');
const crypto = require('crypto');
const router = express.Router();
// Environment variables
const GATEWAY_URL = process.env.GATEWAY_URL;
const API_KEY = process.env.MONERO_API_KEY;
const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;
// Create a new payment
router.post('/create-payment', async (req, res) => {
try {
const { amount, description, customerId, productId } = req.body;
// Validate inputs
if (!amount || amount <= 0) {
return res.status(400).json({ error: 'Invalid amount' });
}
// Create payment with the gateway
const response = await axios.get(`${GATEWAY_URL}/api/monero/new`, {
params: { amount, description },
headers: { 'X-Auth-Token': API_KEY }
});
const { id, address } = response.data;
// Store payment details in your database
await db.payments.create({
paymentId: id,
customerId,
productId,
amount,
status: 'pending',
createdAt: new Date()
});
// Return payment details to the client
return res.json({ id, address });
} catch (error) {
console.error('Error creating payment:', error);
return res.status(500).json({ error: 'Failed to create payment' });
}
});
// Check payment status
router.get('/check-payment/:id', async (req, res) => {
try {
const { id } = req.params;
// Validate payment ID
if (!id || id.length !== 16) {
return res.status(400).json({ error: 'Invalid payment ID' });
}
// Check payment with the gateway
const response = await axios.get(`${GATEWAY_URL}/api/monero/info`, {
params: { id },
headers: { 'X-Auth-Token': API_KEY }
});
// Return payment status to the client
return res.json(response.data);
} catch (error) {
console.error('Error checking payment:', error);
return res.status(500).json({ error: 'Failed to check payment' });
}
});
// Webhook handler
router.post('/webhook', async (req, res) => {
try {
const { id, status, signature, timestamp } = req.body;
// Verify webhook signature
const expectedSignature = crypto
.createHmac('sha256', WEBHOOK_SECRET)
.update(`${id}:${status}:${timestamp}`)
.digest('hex');
if (signature !== expectedSignature) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Update payment status in your database
await db.payments.update(
{ status },
{ where: { paymentId: id } }
);
// Handle completed payments
if (status === 'Received') {
const payment = await db.payments.findOne({
where: { paymentId: id }
});
// Activate the purchased product/service
await activateProduct(payment.customerId, payment.productId);
// Send confirmation email to customer
await sendConfirmationEmail(payment.customerId, payment.productId);
}
return res.status(200).json({ success: true });
} catch (error) {
console.error('Error processing webhook:', error);
return res.status(500).json({ error: 'Failed to process webhook' });
}
});
module.exports = router;