Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Code Block
languagejs
themeRDark
require('dotenv').config(); // Load local .env file into environment variables using dotenv (https://www.npmjs.com/package/dotenv)

const
  request  = require('request'),
  xml2js   = require('xml2js'),  // Parse XML using xml2js (https://www.npmjs.com/package/xml2js)
  builder  = new xml2js.Builder(),
  parser   = new xml2js.Parser(),
  xml_obj  = {
    'x:Envelope': {
      $: { // XML namespaces
        'xmlns:x': 'http://schemas.xmlsoap.org/soap/envelope/',
        'xmlns:v': 'http://api.myh2o.com/v20'
      },
      'x:Body': {
        'v:Customers_Query': {
          'v:Request': {
            'v:Credentials': {
              'v:Username': process.env.USERNAME,
              'v:Password': process.env.PASSWORD,
              'v:Client': 'CODE' // use your client code here
            },
            'v:CustomerID': 12345
          }
        }
      }
    }
  },
  xml_string = builder.buildObject(xml_obj);

console.log('REQUEST: \n', xml_string, '\n\n');

const options = {
  url: 'https://api.rev.io/v20/default.asmx',
  method: 'POST',
  headers: {
    'Content-Type': 'text/xml; charset=utf-8',
    SOAPAction: 'http://api.myh2o.com/v20/Customers_Query'
  },
  body: xml_string
};

request(options, (error, response, body) => {
  if(error !== null) return error;

  parser.parseString(body, (error, obj) => {
    if(error !== null) return error;

    error = SOAP_unwrapError(obj, 'Customers_Query');
    if(error !== null) return error;

    customer = SOAP_unwrapData(obj, 'Customers_Query', 'Customer');
    doSomethingWithCustomerInfo(customer);
  });
});

function SOAP_unwrapError (obj, endpoint) {
  const header = obj['soap:Envelope']['soap:Body'][0][endpoint+'Response'][0][endpoint+'Result'][0]['Header'][0]
  if(header.Success[0] === 'true')
    return null;
  else
    return 'Error: '+header.Message[0];
};

function SOAP_unwrapData (obj, endpoint, model) {
  return obj['soap:Envelope']['soap:Body'][0][endpoint+'Response'][0][endpoint+'Result'][0]['Customer'model][0]
};

function doSomethingWithCustomerInfo (customer) {
  console.log('RESPONSE: \n', customer, '\n\n')
};