Files
VIES-VAT-ID-checker-API/server.js
2025-06-30 09:10:16 +00:00

68 lines
1.9 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const soap = require('soap');
const app = express();
const PORT = 3000;
app.use(cors());
app.use(bodyParser.json());
const VIES_WSDL = 'https://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
// GET endpoint for validating VAT via URL
app.get('/api/validate-vat', async (req, res) => {
const countryCode = req.query.countryCode;
const vatNumber = req.query.vatNumber;
if (!countryCode || !vatNumber) {
return res.status(400).json({ error: 'Missing countryCode or vatNumber in query parameters.' });
}
try {
const client = await soap.createClientAsync(VIES_WSDL);
const [result] = await client.checkVatAsync({ countryCode, vatNumber });
res.json({
country: countryCode.toUpperCase(),
VAT: vatNumber,
name: result.name || null,
address: result.address || null,
valid: result.valid
});
} catch (error) {
console.error('SOAP error:', error);
res.status(500).json({ error: 'Failed to validate VAT number.' });
}
});
// POST endpoint (original)
app.post('/api/validate-vat', async (req, res) => {
const { countryCode, vatNumber } = req.body;
if (!countryCode || !vatNumber) {
return res.status(400).json({ error: 'Missing required fields.' });
}
try {
const client = await soap.createClientAsync(VIES_WSDL);
const [result] = await client.checkVatAsync({ countryCode, vatNumber });
res.json({
country: countryCode.toUpperCase(),
VAT: vatNumber,
name: result.name || null,
address: result.address || null,
valid: result.valid
});
} catch (error) {
console.error('SOAP error:', error);
res.status(500).json({ error: 'Failed to validate VAT number.' });
}
});
// Start server
app.listen(PORT, () => {
console.log(`✅ Server is running at http://localhost:${PORT}`);
});