|
| 1 | +const fetch = require("node-fetch"); |
| 2 | +const { config } = require("../../../config.js"); |
| 3 | + |
| 4 | +/** |
| 5 | + * Receives the request, validates the VAT ID and sends the response. |
| 6 | + * |
| 7 | + * @param {Object} requestEvent the request event built by Netlify Functions |
| 8 | + * @returns {Promise<{statusCode: number, body: string}>} the response object |
| 9 | + */ |
| 10 | +async function handler(requestEvent) { |
| 11 | + try { |
| 12 | + const cartDetails = JSON.parse(requestEvent.body); |
| 13 | + const vatNumber = cartDetails["_embedded"]["fx:customer"]["tax_id"]; |
| 14 | + |
| 15 | + const vatlayer_access_key = config.vatlayer.accessKey; |
| 16 | + |
| 17 | + if (vatNumber !== "") { |
| 18 | + const response = await fetch( |
| 19 | + `http://apilayer.net/api/validate?access_key=${vatlayer_access_key}&vat_number=${vatNumber}` |
| 20 | + ); |
| 21 | + const data = await response.json(); |
| 22 | + |
| 23 | + if (data.valid === true) { |
| 24 | + console.log("VAT ID is valid", data); |
| 25 | + return { |
| 26 | + body: JSON.stringify({ details: "VAT ID is valid", ok: true }), |
| 27 | + statusCode: 200, |
| 28 | + }; |
| 29 | + } else if (data.valid === false) { |
| 30 | + console.log("VAT ID is not valid", data); |
| 31 | + return { |
| 32 | + body: JSON.stringify({ |
| 33 | + details: |
| 34 | + "Your VAT ID does not appear to be valid. Please review your VAT ID and try again.", |
| 35 | + ok: false, |
| 36 | + }), |
| 37 | + statusCode: 200, |
| 38 | + }; |
| 39 | + } else { |
| 40 | + console.error("Error:", data.error.info); |
| 41 | + return { |
| 42 | + body: JSON.stringify({ |
| 43 | + details: "An internal error has occurred when validating VAT ID", |
| 44 | + ok: false, |
| 45 | + }), |
| 46 | + statusCode: 200, |
| 47 | + }; |
| 48 | + } |
| 49 | + } else { |
| 50 | + console.log("No VAT ID is provided"); |
| 51 | + return { |
| 52 | + body: JSON.stringify({ details: "No VAT ID is provided", ok: true }), |
| 53 | + statusCode: 200, |
| 54 | + }; |
| 55 | + } |
| 56 | + } catch (error) { |
| 57 | + console.error(error); |
| 58 | + return { |
| 59 | + body: JSON.stringify({ |
| 60 | + details: "An internal error has occurred when validating VAT ID", |
| 61 | + ok: false, |
| 62 | + }), |
| 63 | + statusCode: 500, |
| 64 | + }; |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +module.exports = { |
| 69 | + handler, |
| 70 | +}; |
0 commit comments