PHP passing parameters via SOAP - php

I am struggling to get to grips with creating the "xml" data for a PHP based SOAP client. I need to produce something like the following:
<SOAP-ENV:Body>
<ns1:check_stock_level>
<ns1:api_credentials>
<ns1:username>*****</ns1:username>
<ns1:password>***</ns1:password>
</ns1:api_credentials>
<productsku>ABC-123</productsku>
</ns1:check_stock_level>
</SOAP-ENV:Body>
I can create the authorisation section, but my code fails to create the productsku - the code looks like this:
$client = new SoapClient("https://www.example.net/wh_api.asmx?WSDL",array("trace"=> 1, "exceptions" => 0));
$auth = array ('api_credentials' => array ('username'=>'******', 'password'=>'******'));
$sku = array('productsku'=>'ABC-123');
$result = $client->check_stock_level($auth, $sku);
which produces this:
<SOAP-ENV:Body>
<ns1:check_stock_level>
<ns1:api_credentials>
<ns1:username>*****</ns1:username>
<ns1:password>***</ns1:password>
</ns1:api_credentials>
</ns1:check_stock_level>
<param1>
<item>
<key>product_sku</key>
<value>ABC-123</value>
</item>
</param1>
</SOAP-ENV:Body>
Where the productsku is outside of the <check_stock_level> tag set and is surrounded by extra tags.
Most examples I can find on SOAP use NuSOAP but I want to use the native pHP SOAP functionality. Can anyone give me any pointers?

Resolved it myself, the two arrays needed to be combined - by having them as separate arrays, the productsku data was moved outside of the tag set.

Related

Getting the correct data from an XML file for a SoapClient request

To have a point of reference, let's use this public WSDL: https://www.dataaccess.com/webservicesserver/NumberConversion.wso?WSDL
Now this thing should accept the following xml:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<NumberToWords xmlns="http://www.dataaccess.com/webservicesserver/">
<ubiNum>500</ubiNum>
</NumberToWords>
</soap:Body>
</soap:Envelope>
And here is the code:
$requestData = simplexml_load_file($file);
//enabling or disabling the following line does not seem to make a difference, but I used it at some point to see that it does load something in there
$requestData->registerXPathNamespace("soap", "http://www.w3.org/2003/05/soap-envelope");
//print_r($requestData->xpath('//soap:Body')); //I was using this to check that the data is actually there, and it is...
$webService = new SoapClient($url);
$result = $webService->NumberToWords($requestData);
print_r($result)
And I'm getting this beautiful response:
stdClass Object
(
[NumberToWordsResult] => zero
)
I think it has something to do with how simpleXML load the data in, but I had no luck figuring out what I should do.
As a side note, if I try just manually setting the data:
$requestData = ["ubiNum"=>500];
it works, but I really want to figure out what is going on with the xml parsing/sending
Also if interested, my commented out print_r's result is the following
Array
(
[0] => SimpleXMLElement Object
(
[NumberToWords] => SimpleXMLElement Object
(
[ubiNum] => 500
)
)
)
If you're using SoapClient, you don't need to also construct the whole XML yourself. Depending on the service, you either need to pass style individual variables, or the contents of the "body".
As you say, you can just run:
$webService = new SoapClient($url);
$result = $webService->NumberToWords(["ubiNum"=>500]);
Underneath, the SoapClient class is generating the rest of the XML for you and sending it as an HTTP request.
If you want to get the data to send out of an XML document, you need to extract just that part, rather than trying to send the whole SOAP envelope inside the parameter. In this example, you need to navigate to the "NumberToWords" element; see this reference question for tips on navigating the XML namespaces but in this example you'd use something like this:
$requestData = simplexml_load_file($file);
$soapBody = $requestData->children('http://schemas.xmlsoap.org/soap/envelope/')->Body;
$numberToWords = $soapBody->children('http://www.dataaccess.com/webservicesserver/')->NumberToWords;
// Or to get the 500 directly:
$ubiNum = (int)$numberToWords->ubiNum;
Alternatively, you can just ignore the SoapClient class, construct the XML yourself, and post it with an HTTP client like Guzzle. Often the only extra step you'll need is to set the correct "SOAPAction" HTTP header.

wsdl service response once variables are sent, php

I am new to SOAP WSDL FUNCTIONS. I have a client who has been given a wsdl file from a company that deals in car testing. My client is a subcontractor for them. They have told us to upload the information about the car plate, category etc and once the details are sent through,There will be a response from server of either success or failure. Kindly assist in this.
Browsing through different information, I tried to do something like below but it is not working
<?php
$data = array('1'=>'value','2'=>'value','3'=>'value','4'='value','5'=>'value');
$wsdl ='http://181.24.80.32/ws/services/servicename';
$client = new SoapClient($wsdl);
$response = $client->servicenamerequest($data);
echo $response->servicenamereturn;
?>
First of all: Go get SoapUI if you are dealing with an unknown Soap service. SoapUI will read the WSDL file and allow you to look at nearly everything related to Soap methods, parameters, and return values (if you dare to make a call to the live service - hopefully there is a sandbox server that does nothing critical).
But SoapUI can help you there by creating a mock service that receives your request and responds with a canned request that you prepared. Here's how I got from your linked WSDL to a working code example without touching the real service.
Setting up SoapUI
Create a new project in SoapUI and give the location of the WSDL. You might name this project.
SoapUI then reads the contents of the WSDL and creates the project containing all described requests. After that you see what methods the service offers, and what kind of parameters have to go into it, as a tree. Opening this tree will get you to "Request 1" for every method detected, which displays some XML in the free version (paid version is slightly more comfortable with a form to fill) like this (from the vehiclePassedTest method):
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tr="http://tr.gov.tp.stp.ws.PassedVehicleTestService">
<soapenv:Header>
<tr:password>?</tr:password>
<tr:username>?</tr:username>
</soapenv:Header>
<soapenv:Body>
<tr:vehiclePassedTest>
<chassisNo>?</chassisNo>
<plateNo>?</plateNo>
<plateCode>?</plateCode>
<plateCategory>?</plateCategory>
<plcEmiCode>?</plcEmiCode>
<currentUserName>?</currentUserName>
</tr:vehiclePassedTest>
</soapenv:Body>
</soapenv:Envelope>
The questionmarks are where you have to provide data. This request structure has to be created by you using the SoapClient of PHP.
Let's mock this. Mocking means that SoapUI starts it's own Soap server that accepts requests. It usually runs on 127.0.0.1:8080. Right-click on the project "PassedVehicleTestService" and select "New MockService". Accept the name, press Ok.
Right-click on the method you want to mock. Select "Add to mock service" and select the created one from the previous step. Answer yes to open the mock response editor. There you see the XML structure of the answer, with question marks for the data that the service will fill out. All the responses from this service allow one answer as a string, so write something nice that will be returned. You can add the other methods to this service later if needed.
Right-click your "MockService 1" and select "Start minimized". This will start the Soap server, it will wait for an incoming request.
Setup PHP SoapClient for the mock.
You need to know two things. First the location of the WSDL. This file contains the address of the real server to be used for the requests, but PHP allows to override this. So the second info you need is the address of the running mock service.
SoapUI displays the address from the WSDL in the request editor. In your case it is http://181.24.80.32/ws/services/PassedVehicleTestService - the mock service runs on http://127.0.0.1:8080/ws/services/PassedVehicleTestService - IP and port is replaced, the path is kept.
This leads to the first lines of PHP code:
$options = array(
'location' => 'http://127.0.0.1:8080/ws/services/PassedVehicleTestService',
);
$client = new SoapClient("http://www.quickregistration.ae/temp/PassedVehicleTestService.xml", $options);
After that you have a configured SoapClient able to talk to your mock service. If later you want to use the real service, throw the line with "location" out of the array, and keep the other config parameters if you happen to add some.
Talk to the mock
With the client, you can do $client->nameOfSoapMethod(paramStructure). The parameter structure usually is a mixture of arrays or objects and scalar values like strings. So that's what I try first:
$result = $client->vehiclePassedTest(array());
var_dump($result);
Then I look at SoapUI to see what happens. Output from the php script:
Notice: Array to string conversion in [...]/soap.php on line 20
string(1) "?"
SoapUI says:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tr.gov.tp.stp.ws.PassedVehicleTestService">
<SOAP-ENV:Body>
<ns1:vehiclePassedTest>
<chassisNo>Array</chassisNo>
<plateNo/>
<plateCode/>
<plateCategory/>
<plcEmiCode/>
<currentUserName/>
</ns1:vehiclePassedTest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
That was not the right approach. The array got converted into a string "Array", and was placed as the first parameter. The rest is empty. Nice, because I know that soap calls may accept more that one parameter, and this is one of these services.
$result = $client->vehiclePassedTest('chassisNo', 'plateNo', 'plateCode', 'plateCategory', 'plcEmiCode', 'currentUserName');
This shows up correctly in SoapUI, but the headers are still missing.
Adding SoapHeader to the request
The SoapClient offers a method named __setSoapHeaders(), and there is a class SoapHeader.
The description says that setSoapHeaders() accepts one SoapHeader object or an array of SoapHeader objects. Let's create one, pass it and see what happens:
$username = new SoapHeader();
$client->__setSoapHeaders($username);
$result = $client->vehiclePassedTest('chassisNo', 'plateNo', 'plateCode', 'plateCategory', 'plcEmiCode', 'currentUserName');
var_dump($result);
PHP says: Warning: SoapHeader::SoapHeader() expects at least 2 parameters, 0 given
$username = new SoapHeader('namespace', 'username', 'MyUserName');
This works. SoapUI says:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tr.gov.tp.stp.ws.PassedVehicleTestService" xmlns:ns2="namespace">
<SOAP-ENV:Header>
<ns2:username>MyUserName</ns2:username>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:vehiclePassedTest><chassisNo>chassisNo</chassisNo><plateNo>plateNo</plateNo><plateCode>plateCode</plateCode><plateCategory>plateCategory</plateCategory><plcEmiCode>plcEmiCode</plcEmiCode><currentUserName>currentUserName</currentUserName></ns1:vehiclePassedTest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Note the TWO xmlns attributes in the SOAP-ENV:Envelope element. The original request requires the username be in the namespace "tr" - but "tr" is only a shortcut to the string that is defined as "xlmns:tr" - the string behind this is your namespace needed (although it might already work with the real service).
$username = new SoapHeader("http://tr.gov.tp.stp.ws.PassedVehicleTestService", 'username', 'myUser');
$password = new SoapHeader("http://tr.gov.tp.stp.ws.PassedVehicleTestService", 'password', 'yetAnotherPassword');
$client->__setSoapHeaders(array($username, $password));
This correctly defines the headers, as you can see:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tr.gov.tp.stp.ws.PassedVehicleTestService">
<SOAP-ENV:Header>
<ns1:username>myUser</ns1:username>
<ns1:password>yetAnotherPassword</ns1:password>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:vehiclePassedTest><chassisNo>chassisNo</chassisNo><plateNo>plateNo</plateNo><plateCode>plateCode</plateCode><plateCategory>plateCategory</plateCategory><plcEmiCode>plcEmiCode</plcEmiCode><currentUserName>currentUserName</currentUserName></ns1:vehiclePassedTest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
No two namespaces in the envelope element, and every element is of namespace "ns1". This should work.
Your final code:
$options = array(
'location' => 'http://127.0.0.1:8080/ws/services/PassedVehicleTestService',
);
$client = new SoapClient("http://www.quickregistration.ae/temp/PassedVehicleTestService.xml", $options);
$username = new SoapHeader("http://tr.gov.tp.stp.ws.PassedVehicleTestService", 'username', 'myUser');
$password = new SoapHeader("http://tr.gov.tp.stp.ws.PassedVehicleTestService", 'password', 'yetAnotherPassword');
$client->__setSoapHeaders(array($username, $password));
$result = $client->vehiclePassedTest('chassisNo', 'plateNo', 'plateCode', 'plateCategory', 'plcEmiCode', 'currentUserName');
var_dump($result);
try something like this. Works for me.
try {
$client = new SoapClient("http://wsdl", array('trace' => 1));
$data = $client->someFunction(array('parma1' => 'value1', 'param2' => 'value2'));
print_r($data);
} catch (SoapFault $fault) {
trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
exit();
}
And check is you have installed php-soap package in your server.
Greatings.

PHP Soap - How to remove xsi:type= from XML tag

I'm sending a SOAP request that looks like:
<SOAP-ENV:Body>
<api:GetOrder xsi:type="SOAP-ENC:Struct">
<api_orderId xsi:type="xsd:int">1234</api_orderId>
</api:GetOrder>
</SOAP-ENV:Body>
But needs to look like this (SoapUI generated):
<soapenv:Body>
<api:GetOrder>
<api:orderId>1234</api:orderId>
</api:GetOrder>
</soapenv:Body>
My PHP Code:
$client = $this->getConnection();
$soap_options = array('soapaction' => $config->getValue('soapaction_url') . 'GetOrder');
$obj = new stdClass();
$obj->api_orderId = 59698;
$results = $client->__soapCall('GetOrder', array(new SoapParam($obj, "api:GetOrder")), $soap_options);
2 questions really:
1) How can I remove the "xsi:type" from the request? (If I add xsi:type in to my SoapUI request, I get back a "400 Bad Request"
2) Instead of "api_orderId" I need to send "api:orderId", but I can't name an object with a colon, so do I have to pass the name and value as an array somehow?
Appreciate any help, thank you.
EDIT:
I wasn't able to figure out any other way to send these requests and I essentially ended up doing as Mr.K suggested below.
I wrote a custom class to extend SoapClient. Then overrode the __doRequest method to send my own custom SOAP request.
The only downside is that SOAP no longer returns me an array of objects, so I also had to parse the XML of the SOAP response.
Also I suspect that the performance of doing it this way is a bit slower, but I didn't notice it.
Try with Simple XML parsing, and create the new request as you like.
Read the tag values from Original request, assign those values to a new XML object using parsing. You can create string of XML message and load it as an XML object in PHP.
Just like get it from there, put it inside this..and Send!..

simplexml help how do I parse this?

I haven't done any xml projects, so I'm not quite sure what to do with this data...
I'm using curl to make a request to salesforce, and they give me back a response that I need to parse. I want to use simplexml. Here's part of the response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<loginResponse>
<result>
<metadataServerUrl>
https://na6-api.salesforce.com/services/Soap/m/18.0/
</metadataServerUrl>
<passwordExpired>
false
</passwordExpired>
<sandbox>
false
</sandbox>
<serverUrl>
https://na6-api.salesforce.com/services/Soap/u/18.0/
</serverUrl>
<sessionId>
!AQ4AQLtDIqY.
</sessionId>
<userId>
</userId>
<userInfo>
<accessibilityMode>
false
</accessibilityMode>
<currencySymbol>
$
</currencySymbol>
<orgDefaultCurrencyIsoCode>
USD
</orgDefaultCurrencyIsoCode>
<orgDisallowHtmlAttachments>
false
</orgDisallowHtmlAttachments>
<orgHasPersonAccounts>
false
</orgHasPersonAccounts>
<organizationId>
</organizationId>
<organizationMultiCurrency>
false
</organizationMultiCurrency>
<organizationName>
Ox
</organizationName>
<profileId>
sdfgsdfg
</profileId>
<roleId>
sdfgsdfg
</roleId>
<userDefaultCurrencyIsoCode xsi:nil="true"/>
<userEmail>
####gmail.com
</userEmail>
<userFullName>
### ###
</userFullName>
<userId>
asdfasdf
</userId>
<userLanguage>
en_US
</userLanguage>
<userLocale>
en_US
</userLocale>
<userName>
asdfasdf#gmail.com
</userName>
<userTimeZone>
America/Chicago
</userTimeZone>
<userType>
Standard
</userType>
<userUiSkin>
Theme3
</userUiSkin>
</userInfo>
</result>
</loginResponse>
</soapenv:Body>
</soapenv:Envelope>
Anyway, I expected to feed that stuff (we'll call it data) into
$results = simplexml_load_string($data);
var_dump($results);
And that would give me all the data back... and then to access specific parts, it would be $results->body->loginResponse->blah->blah...
But It's not giving me that, it's not really giving me anything back, just an empty simple xml object...
So one website made me think I might need an XSLT to read this correctly.
Or something else made me think it's because I don't have at the top.
Help!
You can use SimpleXML but it's not quite as simple as you hope due to the use of namespaces (e.g. soapenv). Look into using SimpleXMLElement::children like:
$sxe = new SimpleXMLElement($data);
$login_response = $sxe->children('soapenv', TRUE)->Body->children('', TRUE)->loginResponse->result;
// Now that we have the <loginResponse> lets take a look at an item within it
echo $login_response->userInfo->userEmail;
Finally, and importantly, have you had a look at salesforce's tools & examples?
SimpleXML needs a special treatment for namespaced XML (ref.)
Mate,
Name spaces usually require you to make a call using children to return the namespaced elements. I would recommend using a soap client like php soapclient, but since I've never used it before there is one other possible option.
$results = simplexml_load_string($data);
$xml = $results->children('http://schemas.xmlsoap.org/soap/envelope/');
var_dump($xml);
I believe that's how it works.
For what it's worth, you may find you have an easier time using a PHP SoapClient for this task. O'Reilly has a good tutorial on PHP SOAP.
Also checkout the PHP Toolkit for making SOAP calls to Salesforce.com
I try to follow the syntax by salathe. But children('soapenv', TRUE) doens't work for me, Jason's children('http://schemas.xmlsoap.org/soap/envelope/') work.
Therefore, to read the field value CreatedDate in Salesforce Outbound Message, I need following code:
$rcXML->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://soap.sforce.com/2005/09/outbound')->notifications->Notification->sObject->children('urn:sobject.enterprise.soap.sforce.com')->CreatedDate
To help you understand how it work, I write a post with sames code and xml which shall be easier to understand.
http://amigotechnotes.wordpress.com/2013/11/16/parse-xml-with-namespace-by-simplexml-in-php/
Parsing soap responses with SimpleXML has a brilliant and concise example of multi-namespace XML parsing.
For anyone wanting to get at the RateResponse from the UPS Rating API, here's how :
// $client is your SoapClient object
$dom = new DOMDocument;
$dom->loadXML($client->__getLastResponse());
$xml = simplexml_load_string($dom->saveXML(), NULL, NULL, 'http://schemas.xmlsoap.org/soap/envelope/');
$RateResponse = $xml->xpath('/soapenv:Envelope/soapenv:Body')[0]->children('rate', true)->RateResponse;
foreach($RateResponse->RatedShipment as $RatedShipment) {
print_r((array)$RatedShipment);
}
For SAOP request, we can parse easily with a short code by replacing the SOAP-ENV: tag with blank
$response = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>';
$response = html_entity_decode($response);
$response = str_replace(['soapenv:', 'ns1:', ':ns1', 'SOAP-ENV:'], ['', '', '', ''], $response);
$objXmlData = simplexml_load_string($response);

Set attributes for parameters in SOAP request PHP

I'm trying to use a webservice which only allows SOAP request
as far as I know I must create a request that looks like this
<?xml version="1.0" encoding="utf-8"?>
<SessionCreateRQ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<POS>
<Source PseudoCityCode="SECRET_CODE" />
</POS>
</SessionCreateRQ>
however while adding the parameter to SessionCreateRQ method I don't know how to add the POS parameter called Source and have no clue on how to set the attribute for that parameter
im trying the following in php
$body = array(
'POS' => array('source' => 'PseudoCityCode:SECRET_CODE'));
try
{
$result = $c->SessionCreateRQ($body);
}
but no luck, does anyone has a clue on how should I construct this call properly ?
thanks !
Firstly you need WSDL definition for this service (online or in local file). Any not bad SOAP service provide WSDL to users.
Secondly you need translate WSDL service definition to PHP-code. Try wsdl2php generator. Its generate file with classes, that making calls to web-services.
Your example will be approximately as follows:
require_once 'GeneratedTypes.php';
$client = new SOAPService();
$res = $client->SessionCreateRQ(SECRET_CODE);
p.s. wsdl2php not ideal but it is working :)

Categories