Guest User

NodeJS cartadeldocente

a guest
Oct 21st, 2024
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var express = require('express');
  2. var soap = require('soap');
  3. var fs = require('fs');
  4. var https = require('https');
  5. var path = require('path');
  6. var axios = require('axios');
  7. var util = require('util');
  8. const xml2js = require('xml2js');
  9.  
  10.  
  11. var app = express();
  12.  
  13. // Middleware to parse JSON bodies
  14. app.use(express.json());
  15.  
  16. // Check
  17. app.get('/CheckVoucherFunction', async function (req, res) {
  18.     try {
  19.         // Extract parameters from the request
  20.         let codiceVoucher = req.query.codiceVoucher || req.body.codiceVoucher;
  21.         let tipoOperazione = req.query.tipoOperazione || req.body.tipoOperazione || "1";
  22.         let partitaIvaEsercente = req.query.partitaIvaEsercente || req.body.partitaIvaEsercente || 'LA TUA PARTITA IVA';
  23.  
  24.         // Validate required parameters
  25.         if (!codiceVoucher || !tipoOperazione) {
  26.             return res.status(400).json({
  27.                 error: "MissingParameters",
  28.                 message: "Please provide both codiceVoucher and tipoOperazione."
  29.             });
  30.         }
  31.  
  32.         // Path to your certificate and key
  33.         const certPath = path.join(__dirname, 'cert', 'result.pem');
  34.         const caPath = path.join(__dirname, 'cert', 'ca-chain.pem');
  35.         const passphrase = "*********";
  36.  
  37.         // Read the certificate and key
  38.         const cert = fs.readFileSync(certPath);
  39.         const key = fs.readFileSync(certPath); // If key is in the same file
  40.         const ca = fs.readFileSync(caPath);
  41.  
  42.         // Create an HTTPS agent with your certificate
  43.         const agentOptions = {
  44.             cert: cert,
  45.             key: key,
  46.             passphrase: passphrase,
  47.             ca: ca,
  48.             rejectUnauthorized: true, // Set to true in production
  49.         };
  50.  
  51.         const httpsAgent = new https.Agent(agentOptions);
  52.  
  53.         // Path to your local WSDL file
  54.         const wsdlPath = path.join(__dirname, 'VerificaVoucher.wsdl');
  55.         const parser = new xml2js.Parser({
  56.             explicitArray: false,
  57.             tagNameProcessors: [xml2js.processors.stripPrefix],
  58.             attrNameProcessors: [xml2js.processors.stripPrefix],
  59.             attrkey: '$'
  60.           });
  61.         // Create a custom HttpClient that uses axios
  62.         class MyHttpClient extends soap.HttpClient {
  63.             request(rurl, data, callback, exheaders, exoptions) {
  64.                 const method = exoptions && exoptions.method ? exoptions.method : 'POST';
  65.  
  66.                 const headers = exheaders || {};
  67.                 headers['Content-Type'] = 'text/xml;charset=UTF-8';
  68.                 headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
  69.  
  70.                 const axiosOptions = {
  71.                     method: method,
  72.                     url: rurl,
  73.                     headers: headers,
  74.                     data: data,
  75.                     httpsAgent: httpsAgent,
  76.                     validateStatus: function (status) {
  77.                         return true; // Resolve the promise for all HTTP status codes
  78.                     },
  79.                 };
  80.  
  81.                 axios(axiosOptions)
  82.                     .then((response) => {
  83.                         callback(null, response, response.data);
  84.                     })
  85.                     .catch((error) => {
  86.                         callback(error);
  87.                     });
  88.             }
  89.         }
  90.  
  91.         // Options for the SOAP client
  92.         const options = {
  93.             httpClient: new MyHttpClient(),
  94.         };
  95.  
  96.         // Create the SOAP client using Promises
  97.         const createClientAsync = util.promisify(soap.createClient);
  98.         const client = await createClientAsync(wsdlPath, options);
  99.  
  100.         // Set the endpoint
  101.         client.setEndpoint('https://ws.cartadeldocente.istruzione.it/VerificaVoucherDocWEB/VerificaVoucher');
  102.  
  103.         // Prepare the request parameters
  104.         const args = {
  105.             checkReq: {
  106.                 tipoOperazione: tipoOperazione,
  107.                 codiceVoucher: codiceVoucher,
  108.                partitaIvaEsercente: partitaIvaEsercente,
  109.             },
  110.         };
  111.  
  112.         // Promisify client.Check
  113.         const checkAsync = util.promisify(client.Check.bind(client));
  114.  
  115.         // Make the SOAP call and wait for it to complete
  116.         try {
  117.             const result = await checkAsync(args);
  118.             console.log(client.lastRequest);
  119.             console.error(client.lastResponse);
  120.  
  121.             // Return the result of the SOAP call
  122.             return res.status(200).json(result);
  123.         } catch (err) {
  124.            // console.error('Error invoking Check:', err);
  125.    // Build custom error response
  126.          //   let errorBody = {
  127.          //       error: "SOAPError",
  128.          //       message: "An error occurred during the SOAP call.",
  129.          //       details: err.response?.data || err.message
  130.          //   };
  131. //
  132.          //   return res.status(400).json(errorBody);
  133.  
  134.          parser.parseString(err.body, function(parseErr, parsedResult) {
  135.             console.log(client.lastRequest);
  136.             console.error(client.lastResponse);
  137.  
  138.             if (parseErr) {
  139.                 console.error('Error parsing XML:', parseErr);
  140.                 return res.status(500).json({
  141.                     error: "InternalServerError",
  142.                     message: "Failed to parse XML error response."
  143.                 });
  144.             } else {
  145.                 // Access exception code and message
  146.                 const exceptionCode = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionCode ||'Nessun codice di errore fornito';
  147.                 const exceptionMessage = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionMessage || 'Nessun messaggio di errore fornito';
  148.  
  149.                 // Send a simplified JSON response
  150.                 return res.status(200).json({
  151.                     checkResp: {
  152.  
  153.                     error: "RemoteError",
  154.                     exceptionCode: exceptionCode,
  155.                     exceptionMessage: exceptionMessage
  156.                 }
  157.                 });
  158.             }
  159.         });
  160.  
  161.         }
  162.     } catch (err) {
  163.         console.error('Error:', err);
  164.  
  165.         return res.status(500).json({
  166.             error: "InternalServerError",
  167.             message: "An error occurred while processing your request."
  168.         });
  169.     }
  170. });
  171.  
  172.  
  173.  
  174. app.get('/ConfirmVoucherFunction', async function (req, res) {
  175.     try {
  176.         // Extract parameters from the request
  177.         let codiceVoucher = req.query.codiceVoucher || req.body.codiceVoucher;
  178.         let tipoOperazione = req.query.tipoOperazione || req.body.tipoOperazione || "1";
  179.         let importo = req.query.importo || req.body.importo;
  180.  
  181.         // Validate required parameters
  182.         if (!codiceVoucher || !tipoOperazione) {
  183.             return res.status(400).json({
  184.                 error: "MissingParameters",
  185.                 message: "Please provide both codiceVoucher and tipoOperazione."
  186.             });
  187.         }
  188.  
  189.         // Path to your certificate and key
  190.         const certPath = path.join(__dirname, 'cert', 'result.pem'); //certificate loaded in a CERT folder
  191.         const caPath = path.join(__dirname, 'cert', 'ca-chain.pem');
  192.         const passphrase = "************";
  193.  
  194.         // Read the certificate and key
  195.         const cert = fs.readFileSync(certPath);
  196.         const key = fs.readFileSync(certPath); // If key is in the same file
  197.         const ca = fs.readFileSync(caPath);
  198.  
  199.         // Create an HTTPS agent with your certificate
  200.         const agentOptions = {
  201.             cert: cert,
  202.             key: key,
  203.             passphrase: passphrase,
  204.             ca: ca,
  205.             rejectUnauthorized: false, // Set to true in production
  206.         };
  207.  
  208.         const httpsAgent = new https.Agent(agentOptions);
  209.  
  210.         // Path to your local WSDL file
  211.         const wsdlPath = path.join(__dirname, 'VerificaVoucher.wsdl');
  212.         const parser = new xml2js.Parser({
  213.             explicitArray: false,
  214.             tagNameProcessors: [xml2js.processors.stripPrefix],
  215.             attrNameProcessors: [xml2js.processors.stripPrefix],
  216.             attrkey: '$'
  217.           });
  218.         // Create a custom HttpClient that uses axios
  219.         class MyHttpClient extends soap.HttpClient {
  220.             request(rurl, data, callback, exheaders, exoptions) {
  221.                 const method = exoptions && exoptions.method ? exoptions.method : 'POST';
  222.  
  223.                 const headers = exheaders || {};
  224.                 headers['Content-Type'] = 'text/xml;charset=UTF-8';
  225.                 headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
  226.  
  227.                 const axiosOptions = {
  228.                     method: method,
  229.                     url: rurl,
  230.                     headers: headers,
  231.                     data: data,
  232.                     httpsAgent: httpsAgent,
  233.                     validateStatus: function (status) {
  234.                         return true; // Resolve the promise for all HTTP status codes
  235.                     },
  236.                 };
  237.  
  238.                 axios(axiosOptions)
  239.                     .then((response) => {
  240.                         callback(null, response, response.data);
  241.                     })
  242.                     .catch((error) => {
  243.                         callback(error);
  244.                     });
  245.             }
  246.         }
  247.  
  248.         // Options for the SOAP client
  249.         const options = {
  250.             httpClient: new MyHttpClient(),
  251.         };
  252.  
  253.         // Create the SOAP client using Promises
  254.         const createClientAsync = util.promisify(soap.createClient);
  255.         const client = await createClientAsync(wsdlPath, options);
  256.  
  257.         // Set the endpoint
  258.         client.setEndpoint('https://ws.cartadeldocente.istruzione.it/VerificaVoucherDocWEB/VerificaVoucher');
  259.        
  260.         // Prepare the request parameters
  261.         const args = {
  262.             checkReq: {
  263.                 tipoOperazione: tipoOperazione,
  264.                 codiceVoucher: codiceVoucher,
  265.                 importo: importo,
  266.             },
  267.         };
  268.  
  269.         // Promisify client.Check
  270.         //const checkAsync = util.promisify(client.Check.bind(client));
  271.         const confirmAsync = util.promisify(client.Confirm.bind(client));
  272.        
  273.         // Make the SOAP call and wait for it to complete
  274.         try {
  275.             const result = await confirmAsync(args);
  276.             console.log(client.lastRequest);
  277.             console.error(client.lastResponse);
  278.    
  279.             // Return the result of the SOAP call
  280.             return res.status(200).json(result);
  281.         } catch (err) {
  282.            // console.error('Error invoking Check:', err);
  283.    // Build custom error response
  284.          //   let errorBody = {
  285.          //       error: "SOAPError",
  286.          //       message: "An error occurred during the SOAP call.",
  287.          //       details: err.response?.data || err.message
  288.          //   };
  289. //
  290.          //   return res.status(400).json(errorBody);
  291.          console.log(client.lastRequest);
  292.          console.error(client.lastResponse);
  293.  
  294.          parser.parseString(err.body, function(parseErr, parsedResult) {        
  295.  
  296.             if (parseErr) {
  297.                 console.error('Error parsing XML:', parseErr);
  298.                 return res.status(500).json({
  299.                     error: "InternalServerError",
  300.                     message: "Failed to parse XML error response."
  301.                 });
  302.             } else {
  303.                 // Access exception code and message
  304.                 const exceptionCode = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionCode;
  305.                 const exceptionMessage = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionMessage?.trim();
  306.  
  307.                 // Send a simplified JSON response
  308.                 return res.status(200).json({
  309.                     checkResp: {
  310.                     error: "RemoteError",
  311.                     exceptionCode: exceptionCode,
  312.                     exceptionMessage: exceptionMessage
  313.                 }
  314.                 });
  315.             }
  316.         });
  317.  
  318.         }
  319.     }
  320.  
  321.     catch (remoteError) {
  322.         console.error('Error:', remoteError);
  323.  
  324.  
  325.         return res.status(500).json({
  326.             error: "InternalServerError",
  327.             message: "Errore di comunicazione con ws.cartadeldocente.istruzione.it."
  328.         });
  329.     }
  330. });
  331.  
  332.  
  333.  
  334.  
  335. // Start the server
  336. var port = process.env.PORT || 3000;
  337. app.listen(port, function () {
  338.     console.log(`Server is running on port ${port}`);
  339. });
  340.  
Advertisement
Add Comment
Please, Sign In to add comment