Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express');
- var soap = require('soap');
- var fs = require('fs');
- var https = require('https');
- var path = require('path');
- var axios = require('axios');
- var util = require('util');
- const xml2js = require('xml2js');
- var app = express();
- // Middleware to parse JSON bodies
- app.use(express.json());
- // Check
- app.get('/CheckVoucherFunction', async function (req, res) {
- try {
- // Extract parameters from the request
- let codiceVoucher = req.query.codiceVoucher || req.body.codiceVoucher;
- let tipoOperazione = req.query.tipoOperazione || req.body.tipoOperazione || "1";
- let partitaIvaEsercente = req.query.partitaIvaEsercente || req.body.partitaIvaEsercente || 'LA TUA PARTITA IVA';
- // Validate required parameters
- if (!codiceVoucher || !tipoOperazione) {
- return res.status(400).json({
- error: "MissingParameters",
- message: "Please provide both codiceVoucher and tipoOperazione."
- });
- }
- // Path to your certificate and key
- const certPath = path.join(__dirname, 'cert', 'result.pem');
- const caPath = path.join(__dirname, 'cert', 'ca-chain.pem');
- const passphrase = "*********";
- // Read the certificate and key
- const cert = fs.readFileSync(certPath);
- const key = fs.readFileSync(certPath); // If key is in the same file
- const ca = fs.readFileSync(caPath);
- // Create an HTTPS agent with your certificate
- const agentOptions = {
- cert: cert,
- key: key,
- passphrase: passphrase,
- ca: ca,
- rejectUnauthorized: true, // Set to true in production
- };
- const httpsAgent = new https.Agent(agentOptions);
- // Path to your local WSDL file
- const wsdlPath = path.join(__dirname, 'VerificaVoucher.wsdl');
- const parser = new xml2js.Parser({
- explicitArray: false,
- tagNameProcessors: [xml2js.processors.stripPrefix],
- attrNameProcessors: [xml2js.processors.stripPrefix],
- attrkey: '$'
- });
- // Create a custom HttpClient that uses axios
- class MyHttpClient extends soap.HttpClient {
- request(rurl, data, callback, exheaders, exoptions) {
- const method = exoptions && exoptions.method ? exoptions.method : 'POST';
- const headers = exheaders || {};
- headers['Content-Type'] = 'text/xml;charset=UTF-8';
- headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
- const axiosOptions = {
- method: method,
- url: rurl,
- headers: headers,
- data: data,
- httpsAgent: httpsAgent,
- validateStatus: function (status) {
- return true; // Resolve the promise for all HTTP status codes
- },
- };
- axios(axiosOptions)
- .then((response) => {
- callback(null, response, response.data);
- })
- .catch((error) => {
- callback(error);
- });
- }
- }
- // Options for the SOAP client
- const options = {
- httpClient: new MyHttpClient(),
- };
- // Create the SOAP client using Promises
- const createClientAsync = util.promisify(soap.createClient);
- const client = await createClientAsync(wsdlPath, options);
- // Set the endpoint
- client.setEndpoint('https://ws.cartadeldocente.istruzione.it/VerificaVoucherDocWEB/VerificaVoucher');
- // Prepare the request parameters
- const args = {
- checkReq: {
- tipoOperazione: tipoOperazione,
- codiceVoucher: codiceVoucher,
- partitaIvaEsercente: partitaIvaEsercente,
- },
- };
- // Promisify client.Check
- const checkAsync = util.promisify(client.Check.bind(client));
- // Make the SOAP call and wait for it to complete
- try {
- const result = await checkAsync(args);
- console.log(client.lastRequest);
- console.error(client.lastResponse);
- // Return the result of the SOAP call
- return res.status(200).json(result);
- } catch (err) {
- // console.error('Error invoking Check:', err);
- // Build custom error response
- // let errorBody = {
- // error: "SOAPError",
- // message: "An error occurred during the SOAP call.",
- // details: err.response?.data || err.message
- // };
- //
- // return res.status(400).json(errorBody);
- parser.parseString(err.body, function(parseErr, parsedResult) {
- console.log(client.lastRequest);
- console.error(client.lastResponse);
- if (parseErr) {
- console.error('Error parsing XML:', parseErr);
- return res.status(500).json({
- error: "InternalServerError",
- message: "Failed to parse XML error response."
- });
- } else {
- // Access exception code and message
- const exceptionCode = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionCode ||'Nessun codice di errore fornito';
- const exceptionMessage = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionMessage || 'Nessun messaggio di errore fornito';
- // Send a simplified JSON response
- return res.status(200).json({
- checkResp: {
- error: "RemoteError",
- exceptionCode: exceptionCode,
- exceptionMessage: exceptionMessage
- }
- });
- }
- });
- }
- } catch (err) {
- console.error('Error:', err);
- return res.status(500).json({
- error: "InternalServerError",
- message: "An error occurred while processing your request."
- });
- }
- });
- app.get('/ConfirmVoucherFunction', async function (req, res) {
- try {
- // Extract parameters from the request
- let codiceVoucher = req.query.codiceVoucher || req.body.codiceVoucher;
- let tipoOperazione = req.query.tipoOperazione || req.body.tipoOperazione || "1";
- let importo = req.query.importo || req.body.importo;
- // Validate required parameters
- if (!codiceVoucher || !tipoOperazione) {
- return res.status(400).json({
- error: "MissingParameters",
- message: "Please provide both codiceVoucher and tipoOperazione."
- });
- }
- // Path to your certificate and key
- const certPath = path.join(__dirname, 'cert', 'result.pem'); //certificate loaded in a CERT folder
- const caPath = path.join(__dirname, 'cert', 'ca-chain.pem');
- const passphrase = "************";
- // Read the certificate and key
- const cert = fs.readFileSync(certPath);
- const key = fs.readFileSync(certPath); // If key is in the same file
- const ca = fs.readFileSync(caPath);
- // Create an HTTPS agent with your certificate
- const agentOptions = {
- cert: cert,
- key: key,
- passphrase: passphrase,
- ca: ca,
- rejectUnauthorized: false, // Set to true in production
- };
- const httpsAgent = new https.Agent(agentOptions);
- // Path to your local WSDL file
- const wsdlPath = path.join(__dirname, 'VerificaVoucher.wsdl');
- const parser = new xml2js.Parser({
- explicitArray: false,
- tagNameProcessors: [xml2js.processors.stripPrefix],
- attrNameProcessors: [xml2js.processors.stripPrefix],
- attrkey: '$'
- });
- // Create a custom HttpClient that uses axios
- class MyHttpClient extends soap.HttpClient {
- request(rurl, data, callback, exheaders, exoptions) {
- const method = exoptions && exoptions.method ? exoptions.method : 'POST';
- const headers = exheaders || {};
- headers['Content-Type'] = 'text/xml;charset=UTF-8';
- headers['Content-Length'] = Buffer.byteLength(data, 'utf8');
- const axiosOptions = {
- method: method,
- url: rurl,
- headers: headers,
- data: data,
- httpsAgent: httpsAgent,
- validateStatus: function (status) {
- return true; // Resolve the promise for all HTTP status codes
- },
- };
- axios(axiosOptions)
- .then((response) => {
- callback(null, response, response.data);
- })
- .catch((error) => {
- callback(error);
- });
- }
- }
- // Options for the SOAP client
- const options = {
- httpClient: new MyHttpClient(),
- };
- // Create the SOAP client using Promises
- const createClientAsync = util.promisify(soap.createClient);
- const client = await createClientAsync(wsdlPath, options);
- // Set the endpoint
- client.setEndpoint('https://ws.cartadeldocente.istruzione.it/VerificaVoucherDocWEB/VerificaVoucher');
- // Prepare the request parameters
- const args = {
- checkReq: {
- tipoOperazione: tipoOperazione,
- codiceVoucher: codiceVoucher,
- importo: importo,
- },
- };
- // Promisify client.Check
- //const checkAsync = util.promisify(client.Check.bind(client));
- const confirmAsync = util.promisify(client.Confirm.bind(client));
- // Make the SOAP call and wait for it to complete
- try {
- const result = await confirmAsync(args);
- console.log(client.lastRequest);
- console.error(client.lastResponse);
- // Return the result of the SOAP call
- return res.status(200).json(result);
- } catch (err) {
- // console.error('Error invoking Check:', err);
- // Build custom error response
- // let errorBody = {
- // error: "SOAPError",
- // message: "An error occurred during the SOAP call.",
- // details: err.response?.data || err.message
- // };
- //
- // return res.status(400).json(errorBody);
- console.log(client.lastRequest);
- console.error(client.lastResponse);
- parser.parseString(err.body, function(parseErr, parsedResult) {
- if (parseErr) {
- console.error('Error parsing XML:', parseErr);
- return res.status(500).json({
- error: "InternalServerError",
- message: "Failed to parse XML error response."
- });
- } else {
- // Access exception code and message
- const exceptionCode = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionCode;
- const exceptionMessage = parsedResult?.Envelope?.Body?.Fault?.detail?.FaultVoucher?.exceptionMessage?.trim();
- // Send a simplified JSON response
- return res.status(200).json({
- checkResp: {
- error: "RemoteError",
- exceptionCode: exceptionCode,
- exceptionMessage: exceptionMessage
- }
- });
- }
- });
- }
- }
- catch (remoteError) {
- console.error('Error:', remoteError);
- return res.status(500).json({
- error: "InternalServerError",
- message: "Errore di comunicazione con ws.cartadeldocente.istruzione.it."
- });
- }
- });
- // Start the server
- var port = process.env.PORT || 3000;
- app.listen(port, function () {
- console.log(`Server is running on port ${port}`);
- });
Advertisement
Add Comment
Please, Sign In to add comment