SOAP Error : rg.xml.sax.SAXException: SimpleDeserializer encountered a child element - php

I have working with SOAP in yii2 and I got an error when I tried to process a soap call
This my soap request :
$xmlInput = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.interfaces.sessions.uams.amdocs\" xmlns:util=\"http://utils.uams.amdocs\" xmlns:web=\"http://webservices.fw.jf.amdocs\"><soapenv:Header/><soapenv:Body><ws:createUser><ws:aCreateUserInfo><util:userId>" . strtoupper($Userid) . "</util:userId><util:effDate>" . $Effdate . "T00:00:09+07:00</util:effDate><util:expDate>" . $Expdate . "T00:00:09+07:00</util:expDate><util:password>" . $this->randomPassword(8) . "</util:password><util:userRoles><ws:item>" . $Role . "</ws:item></util:userRoles></ws:aCreateUserInfo><ws:_awsi_header><web:securedTicket>" . $Ticket . "</web:securedTicket></ws:_awsi_header></ws:createUser></soapenv:Body></soapenv:Envelope>";
Finally I got a response like this :
<?xml version="1.0" encoding="utf-8"?><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><soapenv:Fault><faultcode>soapenv:Server.userException</faultcode><faultstring>org.xml.sax.SAXException: SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.</faultstring><detail><faultData><cause xsi:nil="true"/><exception xsi:nil="true"/><message>SimpleDeserializer encountered a child element, which is NOT expected, in something it was trying to deserialize.</message></faultData><ns1:hostname xmlns:ns1="http://xml.apache.org/axis/">ocsbrntapp4</ns1:hostname></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>
Anybody can help me to fix this issue? Thank you

Try downloading SOAP UI and do a request from there. You will easily be able to see what you are missing.
https://www.soapui.org/downloads/latest-release.html
SOAP UI will automatically tell you exactly what the xml should look like when you post to web service so it is very easy to see where you made a mistake.

Your problem is probably caused by incorrect escaped xml file.
please examine $xmlInput
Based on your code, I would assome that the problem is inside your "$this->randomPassword(8)" function, but without seeing this function I am just asuming.
if you output $xmlInput and see illegal xml characters in there, you can escape them in 2 ways.
1) $xmlInput = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.interfaces.sessions.uams.amdocs\" xmlns:util=\"http://utils.uams.amdocs\" xmlns:web=\"http://webservices.fw.jf.amdocs\"><soapenv:Header/><soapenv:Body><ws:createUser><ws:aCreateUserInfo><util:userId>" . strtoupper($Userid) . "</util:userId><util:effDate>" . $Effdate . "T00:00:09+07:00</util:effDate><util:expDate>" . $Expdate . "T00:00:09+07:00</util:expDate><util:password><![CDATA[" . htmlentities($this->randomPassword(8), ENT_XHTML, 'UTF-8') . "]]></util:password><util:userRoles><ws:item>" . $Role . "</ws:item></util:userRoles></ws:aCreateUserInfo><ws:_awsi_header><web:securedTicket>" . $Ticket . "</web:securedTicket></ws:_awsi_header></ws:createUser></soapenv:Body></soapenv:Envelope>";
2) $xmlInput = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ws=\"http://ws.api.interfaces.sessions.uams.amdocs\" xmlns:util=\"http://utils.uams.amdocs\" xmlns:web=\"http://webservices.fw.jf.amdocs\"><soapenv:Header/><soapenv:Body><ws:createUser><ws:aCreateUserInfo><util:userId>" . strtoupper($Userid) . "</util:userId><util:effDate>" . $Effdate . "T00:00:09+07:00</util:effDate><util:expDate>" . $Expdate . "T00:00:09+07:00</util:expDate><util:password><![CDATA[" . $this->randomPassword(8) . "]]></util:password><util:userRoles><ws:item>" . $Role . "</ws:item></util:userRoles></ws:aCreateUserInfo><ws:_awsi_header><web:securedTicket>" . $Ticket . "</web:securedTicket></ws:_awsi_header></ws:createUser></soapenv:Body></soapenv:Envelope>";
Basically check the contents of $xmlInput and, make sure that all values are escaped properly.

Related

Combine 2 place request to get postal code

I would like to combine two place-api calls in one to get further information about listings.
Example:
My first script request provides Name and Address from the API. However, the Placesearch API does not provide the postal code or other information I need.
My current script shows me this:
name;adress,lnt,lng,place_id
but I need more information for each listing, like the postal code, which not included here.
How can I include a 2nd API call for each place_id and display the postal code?
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
I know, I need to run this query for each place_id:
https://maps.googleapis.com/maps/api/place/details/json?placeid=$place_id=name,rating,formatted_phone_number&key=YOUR_API_KEY
But how can I combine it together with the first results? I need:
Name;Adress;Postcode;LAT;LNG;
Update:
1st request:
$apikey = 'KEY';
$url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json = file_get_contents($url);
$obj = json_decode($json, true);
for($i=0; $i<count($obj['results']); $i++) {
echo "" . $obj['results'][$i]['name'] . ";" . $obj['results'][$i]['vicinity'] . ";" . $obj['results'][$i]['geometry']['location']['lat'] . ";" . $obj['results'][$i]['geometry']['location']['lng'] . ";" . $obj['results'][$i]['place_id'] . DISPLaY POSTCODE "<BR>";
};
this is one ex response from the first request, the ChIJidzOXaLBpEcRxEKHcEN9fuo is the place id which i have to request the details:
Flinsberger Sportplatz;Heilbad Heiligenstadt;51.3163051;10.1929773;ChIJidzOXaLBpEcRxEKHcEN9fuo
this is api call shows the neede details, which i need and can access:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJidzOXaLBpEcRxEKHcEN9fuo=name,rating,formatted_phone_number&key=YOUR_API_KEY
i need to include the 2nd request in the 1st, to get for ex. the postalcode for the specific item, which is my problem i dont know.
and the result should be:
name,adress,postalcode, ... , ... ,...
Following the comments, I came up with this. Note that I do not have an API key myself to test, the the idea is there. You might have to adjust the reference to $obj2 based on the result of the json_decode function for the second query (the one in the loop).
<?php
$apikey = 'KEY';
$url1 = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=51.374,10.1495&rankby=distance&name=keyword&language=de&key=$apikey";
$json1 = file_get_contents($url1);
$obj1 = json_decode($json1, true);
for( $i = 0; $i < count($obj1['results']); $i++)
{
$place_id = $obj1['results'][$i]['place_id'];
$url2 = "https://maps.googleapis.com/maps/api/place/details/output?json&key=" .$apikey . "&placeid=" . $place_id . "&fields=address_component"
$json2 = file_get_contents($url2);
$obj2 = json_decode($json2, true);
echo "" . $obj1['results'][$i]['name'] . ";" . $obj1['results'][$i]['vicinity'] . ";" . $obj1['results'][$i]['geometry']['location']['lat'] . ";" . $obj1['results'][$i]['geometry']['location']['lng'] . ";" . $obj1['results'][$i]['place_id'] . $obj2['result']['address_components']['postal_code'] . "<br>";
};
?>
The idea is you get the information you want form $obj1 and $obj2 based on the results of the 2 queries.

How to remove double quotes from a string from JSON response in PHP

I have a problem with the BlockChain API response. While getting the address from the wallet, the address is enclosed in double quotes like below. How to strip the quotes?
"1Dgyv8Qz1nkrJddoyLBepv1RUXSDqCBCdp"
Code:
$resp = file_get_contents($blockchain_receive_root . "v2/receive?key=" . $my_api_key . "&gap_limit=".$gap_limit. "&callback=" . urlencode($callback_url) . "&xpub=" . $my_xpub);
$response = json_decode($resp);
print json_encode($response->address);
You don't need to remove anything. The issue arises when you call json_encode over the string which adds the double quotes.
So just remove the json_encode call, and it should work like charm:
$resp = file_get_contents($blockchain_receive_root . "v2/receive?key=" . $my_api_key . "&gap_limit=".$gap_limit. "&callback=" . urlencode($callback_url) . "&xpub=" . $my_xpub);
$response = json_decode($resp);
print $response->address;

Amazon MWS PHP Client Library seems incomplete

I am trying to develop an application that uses the ListMatchingProducts method.
The end result will be an application that searches for a given product which is already in an internal stock database and present the results to the user so they can select which Amazon product is a correct match for the one in their database.
The PHP Client Library I found is linked here.
I have edited Samples/.config.inc.php correctly (I have removed the comments and redacted the sensitive information):
define('AWS_ACCESS_KEY_ID', '/*REDACTED BUT SET CORRECTLY*/');
define('AWS_SECRET_ACCESS_KEY', '/*REDACTED BUT SET CORRECTLY*/');
define('APPLICATION_NAME', 'STES_MWS_STOCK_SYNC_APP');
define('APPLICATION_VERSION', '0.1');
define ('MERCHANT_ID', '/*REDACTED BUT SET CORRECTLY*/');
define ('MARKETPLACE_ID', 'A1F83G8C2ARO7P'); // Marketplace ID for the UK
I have also uncommented the appropriate line in Samples/ListMatchingProductsSample.php:
$serviceUrl = "https://mws-eu.amazonservices.com/Products/2011-10-01";
Executing this script, however, yeilds the following message (I've redacted some of the XML response):
Caught Exception: Required parameter MarketplaceId not found
Response Status Code: 400
Error Code: MissingParameter
Error Type: Sender
Request ID: /*REDACTED UUID-LIKE STRING*/
XML: <?xml version="1.0"?>
<ErrorResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01"><Error><Type>Sender</Type><Code>MissingParameter</Code><Message>Required parameter MarketplaceId not found</Message><Detail/></Error><RequestID>/*REDACTED UUID-LIKE STRING*/</RequestID></ErrorResponse>
ResponseHeaderMetadata: RequestId: /*REDACTED UUID-LIKE STRING*/, ResponseContext: /*REDACTED LONG STRING*/, Timestamp: 2017-04-24T13:25:33.533Z, Quota Max: 719.0, Quota Remaining: 719.0, Quota Resets At: 2017-04-24T14:03:00.000Z
As this client library has been around since 2011 I find it difficult to believe this is actually incorrect code in the sample, but I can't seem to find where I've gone wrong; scanning through the code I can't find a reference to the MARKETPLACE_ID constant defined in Samples/.config.inc.php
Before I write my own client library (which I had hoped to avoid for such a simple app) I wondered:
Has anyone else had come across this problem and fixed it (and if so, how)?
Is there a newer version of the library I'm not finding?
Can anyone suggest an alternate library if this one really is broken?
-- EDIT --
For completeness, here is the code I am trying to run - the sample code - minus comments:
require_once('.config.inc.php');
$serviceUrl = "https://mws-eu.amazonservices.com/Products/2011-10-01";
$config = array (
'ServiceURL' => $serviceUrl,
'ProxyHost' => null,
'ProxyPort' => -1,
'ProxyUsername' => null,
'ProxyPassword' => null,
'MaxErrorRetry' => 3,
);
$service = new MarketplaceWebServiceProducts_Client(
AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY,
APPLICATION_NAME,
APPLICATION_VERSION,
$config);
$request = new MarketplaceWebServiceProducts_Model_ListMatchingProductsRequest();
$request->setSellerId(MERCHANT_ID);
invokeListMatchingProducts($service, $request);
function invokeListMatchingProducts(MarketplaceWebServiceProducts_Interface $service, $request)
{
try {
$response = $service->ListMatchingProducts($request);
echo ("Service Response\n");
echo ("=============================================================================\n");
$dom = new DOMDocument();
$dom->loadXML($response->toXML());
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
echo $dom->saveXML();
echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");
} catch (MarketplaceWebServiceProducts_Exception $ex) {
echo("Caught Exception: " . $ex->getMessage() . "\n");
echo("Response Status Code: " . $ex->getStatusCode() . "\n");
echo("Error Code: " . $ex->getErrorCode() . "\n");
echo("Error Type: " . $ex->getErrorType() . "\n");
echo("Request ID: " . $ex->getRequestId() . "\n");
echo("XML: " . $ex->getXML() . "\n");
echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
}
}
Frankly it seems like the "samples" are a bit naff.
Looking at the code, it seems likely you need to set the marketplaceId manually, either in the constructor via an associative array or as a setter method call.
e.g.
$request->setMarketplaceId(MARKETPLACE_ID)

XML Premature end of data

when running the code below I get the following errors:
Failed loading XML Premature end of data in tag Request line 2
Fatal error: Call to a member function asXml() on a non-object in /home4/viptrav3/public_html/wp-content/themes/voyage-child/transfer.php on line 61
Line 61 is $requestFile->asXml('trequest.xml');
But I don't see the premature closing of the XML. I want to save this as a XML file trequest.xml
//Build XML Request
$requestData = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$requestData .= '<Request>';
// Create Request Header
$requestData .= '<Source>';
// Add Requestor ID data
$requestData .= '<RequestorID Client="' . $clientID . '" EMailAddress="' . $email . '" Password="' . $password . '" />';
// Add Requestor Preferences data
$requestData .= '<RequestorPreferences Language="' . $language . '" Currency="USD" Country="US" >';
$requestData .= '<RequestMode>' . $requestMode . '</RequestMode>';
$requestData .= '</RequestorPreferences>';
$requestData .= '</Source>';
// Create Request Body
$requestData .= '<RequestDetails>
<SearchTransferPriceRequest>
<TransferPickUp>
<PickUpCityCode>LON</PickUpCityCode>
<PickUpCode>A</PickUpCode>
<PickUpPointCode>LCY</PickUpPointCode>
</TransferPickUp>
<TransferDropOff>
<DropOffCityCode>EDI</DropOffCityCode>
<DropOffCode>H</DropOffCode>
</TransferDropOff>
<TransferDate>
2013-11-11</TransferDate>
<NumberOfPassengers>2</NumberOfPassengers>
<PreferredLanguage>E</PreferredLanguage>
</SearchTransferPriceRequest>
</RequestDetails>';
//Save Request & Display XML errors
libxml_use_internal_errors(true);
$sxe = simplexml_load_string($requestData);
if ($sxe === false) {
echo "Failed loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
}
$requestFile = simplexml_load_string($requestData);
$requestFile->asXml('trequest.xml');
You have to close <Request> tag at the end.
Also it's not good to build XML by hand. Use DOMDocument class instead.

Microsoft CRM 3.0 web service via PHP Soap class

I would like to create new contacts and leads using php. I can't quite figure out how to call the methods of the mscrm 3 web service.
The php soap class seems quite simple to use. I am able to connect and authenticate to the crm web service and get a list of available functions however I am unsure how to go about calling them.
I have seen examples for mscrm 4.0 which seem to involve masses of XML including soap headers and envelopes.
I am under the impression that using a soap class bypasses this and will write all the extra xml for me so all I need to do is call a function with an array of parameters?
Am I completely wrong here ?
Has anyone done this with mscrm 3 that can provide some sample code, or perhaps give me a few pointers as how to correctly call the Create() method ?
I have been able to get this working by using Nusoap and after construction the XML message as a series of strings using the send method instead of call. This now works as expected. It seemed that using the call method was returning different XML than what was required by the ms crm 3 web service.
Any decent SOAP toolkit will automagically spit out the correct XML. Check out this guy:
http://us2.php.net/xmlrpc_encode_request
require_once ('/var/mtp/lib/vendor/nusoap/lib/nusoap.php');
$login ='domain\username';
$pass ='password';
$useCURL = true;
$client = new nusoap_client('http://server:5555/mscrmservices/2006/crmservice.asmx?wsdl', 'wsdl');
$client->setCredentials($login, $pass, 'ntlm');
$client->setUseCurl($useCURL);
$client->useHTTPPersistentConnection();
$client->soap_defencoding = 'UTF-8';
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
exit();
}
$soapHeader='<soap:Header>' .
'<CallerId xmlns="http://schemas.microsoft.com/crm/2006/WebServices">'.
'<CallerGuid xmlns="http://schemas.microsoft.com/crm/2006/CoreTypes">00000000-0000-0000-0000-000000000000</CallerGuid></CallerId>' .
'</soap:Header>';
$soapBody='<soap:Body>' .
'<entity xmlns="http://schemas.microsoft.com/crm/2006/WebServices" xsi:type="lead">' .
'<ownerid type="Owner">2408c7dc-c0a3-dd11-b3cd-001a4bd3009a</ownerid>' .
'<firstname>Fred</firstname>' .
'<lastname>Bloggs</lastname>' .
'</entity>' .
'</soap:Body>';
$xml = '<?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/">' .
$soapHeader .
$soapBody .
'</soap:Envelope>';
//SOAP call
$result = $client->send($xml,'http://schemas.microsoft.com/crm/2006/WebServices/Create' );
//result
if ($client->fault) { //check for fault
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
}
else { //no fault
$err = $client->getError();
if ($err) { // error
echo 'Error: ' . $err . '';
echo "\n\n# # # # # # # Request # # # # # # #\n";
var_dump($client->request);
echo "\n\n# # # # # # Response # # # # # # #\n";
var_dump($client->response);
}
else { // display the result
print_r($result);
}
}
I was also struggling to get Dynamics CRM SOAP working with PHP but after a while I managed to get it working; http://www.ifc0nfig.com/working-with-microsoft-dynamics-crm-4-0-soap-interface-with-php-and-nusoap/ - You can download a small class I created which may be of use :)

Categories