Returning a JSON object from PHP SoapServer - php

How can I force my PHP SoapServer to send a JSON object as a response instead of an XML doc?
Thanks.

That is not SOAP, so no. It can incorporate a jsonstring in some xml node, that's about it. You may want just a REST server serving json.
You can bastardize it though, making it by definition NOT SOAP, but some weird hybrid:
<?php
class ThisIsNotASoapServer extends SoapServer {
}
function test(){
//should have a return
//return range(1,9);
//but totally breaks it by:
echo json_encode(range(1,9));
//the exit here is needed
exit;
}
$server = new ThisIsNotASoapServer(null, array('uri' => 'http://test-uri/','soap_version' => 1));
$server->addFunction("test");
$server->handle('<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<m:Test xmlns:m="Some-URI"/>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>');
?>
... so, technically this is possible, but I suspect there is not a single client which understands this.

Take a look at http://www.sinatrarb.com its very easy to create a restful web service to return a json object.
depends on your requirements - SOAP is a xml request it doesnt mean the format for the return also needs to be SOAP (XML) you can easily post back a JSON string.
Maybe if you can provide more information we can help more?

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.

returning soap xml response for a soap server php

I am trying to create a soap service in php using native php soap server. I have already prepared the wsdl file.
There are basically four methods that can be called with the soap service. The input soap request for one of the request ShowRemittanceDetail is shown below.
<soap-env:body>
<ns1:showremittancedetailrequest>
<username>admin</username>
<password>pass</password>
<refno>USA1956127848</refno>
</ns1:showremittancedetailrequest>
</soap-env:body>
Anyway the soap request does not have a header and I have just shown the body here. I have no problem parsing the soap request. The response should look like this
<?xml version="1.0" encoding="ISO-8859-1"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<ns2:responseType xmlns:ns2="http://tempuri.org/response">
<code>00</code>
<message>Transaction does not exist or is not available</message>
<responseBody>
<responseStr>4</responseStr>
</responseBody>
</ns2:responseType>
</soapenv:Body>
</soapenv:Envelope>
This is a particular response which is generated when the transaction with the reference number is not available in the server.
I have received the soap request and evaluated it. However I have a problem with the return type of the soap response. I cannot generate a valid response. What type of response should a soap server return?
Things I have tried:
I have tried returning an xml string. But the soap client request throws an exception with the following message.
looks like we got no xml document.
I have also tried returing a native php SoapVar() with the same result.
I have tried returning an object response that is specified in the classmap fo the soap server.
e.g. for the example above, I have tried returning a ShowRemittanceDetailResponse object with the same result. (looks like we got no xml document).
I have tried returning a DomDocument Object . The exception thrown in this case is
the encoded object does not have a responseStr property.
I have tried returning an stdClass object with the same fields as the response expects with similar result.
Please help me.
Thanks in advance.
The solution I found was returning a SoapVar object. I didnt have soapui and the client I wrote in php was incorrect. Hence, I had problem verifying the returned xml as the php soap client was throwing an exception. The correct way for me was to return a SoapVar.

PHP SoapServer addSoapHeader ignored with SoapFault

I have written a PHP SOAP Service that accepts Basic Authentication credentials as outlined at http://www.whitemesa.com/soapauth.html. I did this by defining a method BasicAuth inside the handler class of the SOAPServer instance. This all works fine.
However, when authentication fails for some reason (incorrect username, no BasicAuth header in the request) I'd like to include a BasicChallenge header in my response, like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<h:BasicChallenge xmlns:h="http://soap-authentication.org/basic/2001/10/"
SOAP-ENV:mustUnderstand="1">
<Realm>Realm</Realm>
</h:BasicChallenge>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Authentication failed</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The following code does not work (the header is not added to the response).
$soapServer->addSoapHeader(new SoapHeader("http://soap-authentication.org/basic/2001/10/", "BasicChallenge", array("Realm" => "Realm"), true));
throw new SoapFault("Client", "Authentication Failed");
Calling $soapServer->fault() instead of throw new SoapFault does not make a difference.
I've tried constructing the Fault object myself, and returning that as a regular response, but I was unable to get PHP to send a well-formed response.
Thanks in advance.
This was 2013 and I actually have exactly the same problem. Well, it 's 2019 and PHP 's current version is 7.3 and 7.4 is coming up to us with big steps. Unfortunately the SoapServer class ignores soap headers completely in a SoapFault case.
I 've written a small workaround to manipulate the XML response of the soap server. For everone who 's having the same issue, here 's a small example, how to solve it.
1. Initialise your Soap Server
$server = new SoapServer($wsdl, $options);
ob_start();
$server->setObject($service);
$server->handle();
$response = ob_get_contents();
ob_end_clean();
Actually we 're doing a simple initialization. Instead of simple returning the content we intercept the xml response with the output buffering functions. The result of the is a xml string in $response.
2. Find out if the reponse is a fault
Actually the SoapServer class is adding soap headers, if it was a valid response. We have to find out, if the response is a fault.
$doc = new DOMDocument();
$doc->loadXML($response);
$xpath = new DOMXPath($doc);
$isFault = $xpath->query('//*[local-name()="Fault"]')->length;
Just load the response xml string into the DOMDocument class. From now on we are able to access xml elements with DOM functions. For better handling I 'm using the DOMXPath class. Of course it is also possible to determine the XML nodes with the DOMDocument class. The $isFault variable is useful for the next step.
3. In fault case set a soap header
Unfortunately there is no fancy addSoapHeader function for simply setting a soap header. We have to do it manually in this case.
if ($isFault) {
$header = $doc->createElementNS('http://schemas.xmlsoap.org/soap/envelope/', 'Header');
$body = $doc->getElementsByTagNameNS('http://schemas.xmlsoap.org/soap/envelope/', 'Body')->item(0);
$realm = $doc->createElementNS('http://soap-authentication.org/basic/2001/10/', 'h:Realm');
$basicChallenge = $doc->createElementNS('http://soap-authentication.org/basic/2001/10/', 'h:BasicChallenge');
$basicChallenge->appendChild($realm);
$header->appendChild($basicChallenge);
$doc->documentElement->insertBefore($header, $body);
}
$xmlResponse = $doc->saveXML($doc->documentElement);
header('Content-Length: ' . strlen($xmlResponse));
echo $xmlResponse;
exit();
In a fault case we create a header element and add all the child nodes we need. If averything was appended insert the header before the body, save the new xml structure in a string and echo it.
Hope this helps a bit.

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);

Categories