Soap from Node.js - node.js

How to generate soap request in node.js for the below xml
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cred="http://credential.transport.v1.api.cmpublish.clickability.com" xmlns:tran="http://transport.v1.api.cmpublish.clickability.com">
<soapenv:Header>
<cred:credentials username="" password="" customerID=""/>
</soapenv:Header>
<soapenv:Body>
<tran:getSubscriberByEmail>
<email></email>
<domainID></domainID>
</tran:getSubscriberByEmail>
</soapenv:Body>
</soapenv:Envelope>

If you've got a WSDL to point things at, I've found node-soap to be straight forward.
From their readme:
var soap = require('soap');
var url = 'http://example.com/wsdl?wsdl';
var args = {name: 'value'};
soap.createClient(url, function(err, client) {
client.MyFunction(args, function(err, result) {
console.log(result);
});
});

Related

How can I make XML based API requests using Express Node.js?

I would like to send an API request to https://api-test.onlineszamla.nav.gov.hu/invoiceService/queryTaxpayer and they expect an XML, as a sample provided below. What is the appropriate syntax in Node.js that processes this request? Unfortuantely I couldn't find this out from the API documentation.
EDIT: part of the XML contents will be from user data, part of it from input fields.
<?xml version="1.0" encoding="UTF-8"?><QueryTaxpayerRequest xmlns="http://schemas.nav.gov.hu/OSA/1.0/api">
<header>
<requestId></requestId>
<timestamp></timestamp>
<requestVersion></requestVersion>
<headerVersion></headerVersion>
</header>
<user>
<login></login>
<passwordHash></passwordHash>
<taxNumber></taxNumber>
<requestSignature></requestSignature>
</user>
<software>
<softwareId></softwareId>
</software>
<taxNumber></taxNumber>
</QueryTaxpayerRequest>
Use XML parser and then Set the response type as XML like below :
var xml = require('xml');
response.set('Content-Type', 'text/xml');
response.send(xml(YOUR_XML_OBJECT));
in the above I have used XML as the parser, you should be able to use any other available packages.
You can use a library like xmlbuilder to make creating xml string easier.
var builder = require('xmlbuilder');
var obj = {
root: {
xmlbuilder: {
repo: {
'#type': 'git', // attributes start with #
'#text': 'git://github.com/oozcitak/xmlbuilder-js.git' // text node
}
}
}
};
var xml = builder.create(obj).end({ pretty: true});
console.log(xml);
And then you can use any library to make the request and use the xml string above in the body.
This works for me awesome.
var Request = require("request");
const express = require("express");
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.text())
app.post("/api/getXML", (req, res) => {
Request.post({
"headers": { "content-type": "text/plain; charset=utf-8"},
"url": "<url which return xml response>",
"body": req.body
}, (error, response, body) => {
if(error) {
console.error(error);
res.send(error)
}
console.log("XML body :",body);
res.send(body);
});
});
The idea got from the link https://www.thepolyglotdeveloper.com/2017/10/consume-remote-api-data-nodejs-application/

Node Js prints [object Object] does not print session information

I am using the following Node Js code to use the Web service. But when I run this on Postman, I got [object Object] in console. But when I run on SoapUI, it will print the Session details
my code
router.post("/register", upload.single('image'), function (req, res, next)
{
var url = 'http://smeapps.mobitel.lk:8585/EnterpriseSMSV2/EnterpriseSMSWS?wsdl';
var session = {username: 'username', password: 'password'}
soap.createClient(url, function(err, client)
{
if(err)
console.log(err)
client.createSession(session, function(err, result)
{
console.log(result);
});
})
})
SoapUI session request
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.esms.mobitel.lk/">
<soapenv:Header/>
<soapenv:Body>
<ws:createSession>
<!--Optional:-->
<arg0>
<!--Optional:-->
<customer>12</customer>
<!--Optional:-->
<id>12</id>
<!--Optional:-->
<password>password</password>
<!--Optional:-->
<username>username</username>
</arg0>
</ws:createSession>
</soapenv:Body>
</soapenv:Envelope>
SoapUI response
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://ws.esms.mobitel.lk/">
<SOAP-ENV:Body>
<ns1:createSessionResponse>
<return>
<expiryDate>2018-10-04T06:24:25+05:30</expiryDate>
<isActive>true</isActive>
<sessionId>761033662786</sessionId>
<user>0</user>
</return>
</ns1:createSessionResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
wrap the code into try catch
Error: SOAP-ENV:Server: Procedure 'createSession' not present
{"statusCode":500,"body":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>Procedure 'createSession' not present</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>\n","headers":{"date":"Thu, 04 Oct 2018 08:51:04 GMT","server":"Apache/2.2.15
(CentOS)","x-powered-by":"PHP/5.3.3","content-length":"304","connection":"close","content-type":"text/xml; charset=utf-8"},"request":{"uri":{"protocol":"http:","slashes":true,"auth":null,"host":"202.129.232.190:8585","port":"8585","hostname":"202.129.232.190","hash":null,"search":null,"query":null,"pathname":"/EnterpriseSMSV2/EnterpriseSMSWS.php","path":"/EnterpriseSMSV2/EnterpriseSMSWS.php","href":"http://202.129.232.190:8585/EnterpriseSMSV2/EnterpriseSMSWS.php"},"method":"POST","headers":{"User-Agent":"node-soap/0.8.0","Accept":"text/html,application/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8","Accept-Encoding":"none","Accept-Charset":"utf-8","Connection":"close","Host":"202.129.232.190:8585","Content-Length":0,"Content-Type":"text/xml; charset=utf-8","SOAPAction":"\"\""}}}
Seems you are requesting REST API.
Response format for SOAP UI is XML. But for REST API is JSON. Then your are getting JSON format response. Thats why you are getting [object object] when you try to print that. So check out how to handle JSON.

Node.js Twilio make calls using REST API

I am trying to make call from the Twilio REST API but I am getting an error, looks like I missed something, any help will appreciate:
var options = { method: 'POST',
url: 'https://xxxxxxxxxxxx#api.twilio.com/2010-04-01/Accounts/xxxxxxxxxxx/Calls',
headers:
{
'Cache-Control': 'no-cache',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
formData:
{ To: '+919200070974',
From: '14245060471',
Url: '<?xml version="1.0" encoding="UTF-8"?>\n<Response>\n <Say voice="woman">This is me....</Say>\n</Response>'} };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
Now I set url parameters but its showing invalid
<?xml version='1.0' encoding='UTF-8'?>
<TwilioResponse>
<RestException>
<Code>21205</Code>
<Message>Url is not a valid url: <?xml version="1.0" encoding="UTF-8"?>
<Response>
<Say voice="woman">This is me....</Say>
</Response></Message>
<MoreInfo>https://www.twilio.com/docs/errors/21205</MoreInfo>
<Status>400</Status>
</RestException>
</TwilioResponse>
I am not getting where I have to set URL parameter, I didn't find in the documentation clearly what I have to set.
Twilio developer evangelist here.
What you need to do in this case, is send to Twilio a URL. When the call connects, Twilio will then make a request to that URL to get the TwiML response.
From the documentation:
When you initiate a call through the REST API, Twilio makes a synchronous HTTP request to the URL found in the value of the 'Url' POST parameter, in order to retrieve TwiML for handling the call. This request is identical to the request Twilio sends when receiving a phone call to one of your Twilio numbers. URLs must contain a valid hostname (underscores are not permitted).
So, your formData here should be:
formData: {
To: '+919200070974',
From: '14245060471',
Url: 'https://example.com/twiml'
}
And the URL at https://example.com/twiml should respond with the TwiML you defined originally.
twilio has an npm library already.
you can follow their Node.js Guide
// Twilio Credentials
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
// require the Twilio module and create a REST client
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
to: '+15558675310',
from: '+15017122661',
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
})
.then(message => console.log(message.sid));

Authentication in Node JS soap request

I am using strong-soap (https://www.npmjs.com/package/strong-soap) for consuming wsdl from Node JS
I have a wsdl with header like below:-
<soapenv:Header>
<wsse:Security xmlns:wsse="http://xyz.xsd">
<wsse:UsernameToken wsu:Id="UsernameToken-24" xmlns:wsu="http://secure.xsd">
<wsse:Username>userid</wsse:Username>
<wsse:Password Type="http://pwdtext">password</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
I need to add this header information while creating client.
I tried like
var url = "test?wsdl";
soap.createClient(url, {wsdl_headers: {"Username": "username","Password":"password"} }, function(err, client) {
//some logic
});
But every time I was getting soap fault "Authentication Failed".
Any idea what I am doing wrong?
Thanks in advance.
I had the same issue trying to pull data.
my mistake was that in the options of the createClient method is was using headers instead of wsdl_headers
also set the same authentication on the client before any method is called
my code looks as
var url = 'https://datahere?wsdl';
var httpOptions = {
wsdl_headers: {
'Authorization': 'Basic ' + new Buffer('username' + ':' + 'password').toString('base64')
}
};
soap.createClient(url, httpOptions, function(err, client) {
if (err) {
console.log(err.message);
response.status(401).end();
} else {
var requestArgs = {
Method1: 'dummyData',
Method2: ''
};
// client.setSecurity(new soap.BasicAuthSecurity('password', 'password'));
client.addHttpHeader('customHeader1', 'words');
client.addHttpHeader('Authorization', "Basic " + new Buffer('username-app-maker' + ':' + 'password').toString('base64'));
client.GETSOAPMETHOD(requestArgs, function(err, result) {
if (err) {
console.log(err.message);
}
console.log('i found ' + result);
response.send(result);
});
}
});
As mentioned in this answer, wsdl_header object is expecting a key 'Authentication'
So try running the following code:
var url = 'test?wsdl';
var auth = "Basic " + new Buffer("your username" + ":" + "your password").toString("base64");
soap.createClient(url, { wsdl_headers: {Authorization: auth} }, function(err, client) {
});

Error auth using soap-node

I have a problem with soap-node, my header have auth:
XML-service SOAP
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<Autentication xmlns="http://tempuri.org/">
<Pass>string</Pass>
<Us>string</Us>
</Autentication>
</soap:Header>
<soap:Body>
<getdata xmlns="http://tempuri.org/" />
</soap:Body>
</soap:Envelope>
App.js - Node.js
var soap = require('soap');
var url = "http://localhost/abc/example.asmx?WSDL"
var Autentication = {
"Autentication": {
"Pass" : "david",
"Us" : "hackro"
}
}
var args = {}
soap.createClient(url, function(err, client) {
if(err)return console.log(err)
client.addSoapHeader(Autenticacion)
client.ObtieneKey(args, function(err, result,body) {
if(err) return console.log(body)
console.log(result);
console.log(body);
})
})
But my auth fail because return empty
{ data: "" }
I see this answer but it doesn't work.
I solved my problem sending my header in this way
var Autentication ='<Autentication xmlns="http://tempuri.org/">Pass>david</Pass><Us>hackro</Us>/Autentication></soap:Header>'
Add header
client.addSoapHeader(Autentication)
Good Luck

Resources