Parse XML SOAP to Object JSON with PHP 7 - php

I have the following problem, I need to transform the SOAP response from $ response = $ client -> __ getLastResponse (); And transform into a JSON object. Here is the image of the response I get in PHP with the above method.
stdClass return for $result:
stdClass Object ( [RealizarConsultaSQLResult] => AEC4 - AEC7 - )
Response SOAP:
<NewDataSet><Resultado> <CODTURMA>AEC4</CODTURMA><NOME>-</NOME></Resultado><Resultado><CODTURMA>AEC7</CODTURMA><NOME>-</NOME>
</Resultado></NewDataSet>
Observation: My code works normally, just need to receive the answer in the format below: (expected output):
{
"NewDataSet": {
"Resultado": [
{
"CODTURMA": "AEC4",
"NOME": "-"
},
{
"CODTURMA": "AEC7",
"NOME": "-"
}
]
}
}
My Code
<?php
require("wsdls.php");
//Cabeçalho de autenticação básica no SOAP
$soapParams = array('login' => $usuario,
'password' => base64_decode($pass),
'authentication' => SOAP_AUTHENTICATION_BASIC,
'trace' => 1,
'exceptions' => 0
);
$client = new SoapClient($WsdlRMSQL, $soapParams);
$params = array('codSentenca' => 'TOTVS.MDA.402', 'codColigada'=>'1', 'codSistema'=>'S','parameters'=>'CODCOLIGADA=1;CODFILIAL=1;IDPERLET=2;IDHABILITACAOFILIAL=10');
//Resultado do Webservice
$result = $client->realizarConsultaSQL($params);
//Resposta do SOAP
$response = $client->__getLastResponse();
//$xmlString = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
//var_dump($response);
print_r($response);
?>
Image form SOAP response

try{
$xml = $client->__getLastResponse();
// SimpleXML seems to have problems with the colon ":" in the <xxx:yyy> response tags, so take them out
$xml = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $xml);
$xml = simplexml_load_string($xml);
$json = json_encode($xml);
$responseArray = json_decode($json,true);
// dd($responseArray['soapenvHeader']['headResponseHeader']['headStatusMessages']['headMessageDescription']);
Log::info("bill payment response".json_encode($result));
Log::info("bill payment response xml".$client->__getLastResponse());
if(!empty($responseArray['soapenvBody'])):
return redirect()->back()->with('status', $responseArray['soapenvHeader']['headResponseHeader']['headStatusMessages']['headMessageDescription']);
else:
return redirect()->back()->with('err', "We could not complete your request, please try again");
endif;
} catch (\SoapFault $fault) {
Log::info("bill payment error".json_encode($fault));
return redirect()->back()->with('err', $fault->getMessage());
}

Related

PHP - Get data from Soap response

My soap response using SOAP UI
<S:Body>
<ns2:listIpMemberResponse xmlns:ns2="http://whoisservice.*.com/">
<listResult>
<memberInfo>
<issuedDate>29/11/2010</issuedDate>
<memberName>Ngân hàng Thương mại Cổ phần An Bình</memberName>
<netName>ABBANK-VN</netName>
<order>1</order>
</memberInfo>
<memberInfo>
<issuedDate>07/10/2010</issuedDate>
<memberName>Ngân hàng thương mại Cổ phần Á Châu</memberName>
<netName>ACB-VN</netName>
<order>2</order>
</memberInfo>
<memberInfo>
<issuedDate>11/05/2012</issuedDate>
<memberName>Công ty TNHH Chứng khoán ACB</memberName>
<netName>ACBS-VN</netName>
<order>3</order>
</memberInfo>
</listResult>
</ns2:listIpMemberResponse>
</S:Body>
I am trying to get listResult by using:
$context = stream_context_create();
$whoisService_wsdl = 'https://url?wsdl';
$whoisService_client = new SoapClient($whoisService_wsdl, array('cache_wsdl' => WSDL_CACHE_NONE, 'stream_context' => $context));
$result = $whoisService_client->listIpMember();
$list = $result->listResult;
But when I print_r $list the result is stdClass Object ( ) 1.
How can I put the listResult into an array?

can't get soapUI into PHP function

I have been struggling for hours now on a SOAP connection and can't get it to work, this is what I have:
$url = 'https://xxx/connector.svc?singleWsdl';
$user = 'user';
$pass = 'pass';
$options = array(
'uri'=>'http://schemas.xmlsoap.org/soap/envelope/',
'style'=>SOAP_RPC,
'use'=>SOAP_ENCODED,
'soap_version'=>SOAP_1,
'cache_wsdl'=>WSDL_CACHE_NONE,
'connection_timeout'=>15,
'trace'=>true,
'encoding'=>'UTF-8',
'exceptions'=>true,
);
try {
$soapclient = new SoapClient($url, $options);
# $soapclient = new SoapClient($url);
}
catch(Exception $e) {
die($e->getMessage());
}
I tried '?wdsl' but then I get:
PHP Fatal error: SOAP-ERROR: Parsing WSDL: <message> 'IConnector_GetProduct_ServiceFaultFault_FaultMessage' already defined
A request with no parameters works fine:
$result = $soapclient->GetVersionInfo();
$last_request = $soapclient->__getLastRequest();
$last_response = $soapclient->__getLastResponse();
print "Request: ".$last_request ."\n";
print "Response: ".$last_response."\n";
print_r($result);
Result:
Request: <?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="Unit4.AgressoWholesale.Connectors"><SOAP-ENV:Body><ns1:GetVersionInfo/></SOAP-ENV:Body></SOAP-ENV:Envelope>
Response: <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetVersionInfoResponse xmlns="Unit4.AgressoWholesale.Connectors"><GetVersionInfoResult xmlns:a="http://schemas.datacontract.org/2004/07/Unit4.AgressoWholesale.Common.Contracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:FullVersion>14.4.18.0</a:FullVersion><a:Release>14</a:Release><a:ServicePack>4</a:ServicePack><a:Fix>18</a:Fix><a:Version>0</a:Version><a:CustomCode/><a:AWBuild>38</a:AWBuild><a:AWFix>003</a:AWFix><a:AWCustomBuild/><a:AWCustomFix/><a:AWCustomCustomerCode/></GetVersionInfoResult></GetVersionInfoResponse></s:Body></s:Envelope>
stdClass Object
(
[GetVersionInfoResult] => stdClass Object
(
[FullVersion] => 14.4.18.0
[Release] => 14
[ServicePack] => 4
[Fix] => 18
[Version] => 0
[CustomCode] =>
[AWBuild] => 38
[AWFix] => 003
[AWCustomBuild] =>
[AWCustomFix] =>
[AWCustomCustomerCode] =>
)
)
So far so good, but the trouble begins trying to log in, which is a must.. In SoapUI it works with:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:unit="Unit4.AgressoWholesale.Connectors" xmlns:unit1="http://schemas.datacontract.org/2004/07/Unit4.AgressoWholesale.Common.Contracts">
<soapenv:Header/>
<soapenv:Body>
<unit:Login>
<unit:SecurityContext>
<unit1:SessionToken></unit1:SessionToken>
<unit1:UserId>user</unit1:UserId>
<unit1:Password>pass</unit1:Password>
</unit:SecurityContext>
</unit:Login>
</soapenv:Body>
</soapenv:Envelope>
But converting this to PHP, I'm stranding here.. this is what I have tried:
$data = array( 'SecurityContext' => array( 'SessionToken' => ''
,'Password' => $user
,'UserId' => $pass)
);
$data = array( 'SessionToken' => ''
,'Password' => $user
,'UserId' => $pass
);
$data = new stdClass;
$data->SecurityContext = new stdClass;
$data->SecurityContext->SessionToken = '';
$data->SecurityContext->UserId = $pass;
$data->SecurityContext->Password = $user;
#$result = $soapclient->__call('Login',array($data));
#$result = $soapclient->Login($data);
$result = $soapclient->__soapCall('Login',array($data));
But no matter what I try, event without parameters or an empty array or stdClass, I get:
PHP Fatal error: Uncaught SoapFault exception: [s:ServiceFault] An exception occurred
It's driving me nuts, I can't find anything on the internet about the fatal exeption '[s:ServiceFault]'
What am I doing wrong? Any help will be greatly appreciated!
OK, writing out the problem sometimes is enough to get to an anwer!
The solution was two-fold:
1) get better error reporting by using a try{} catch:
try {
$result = $soapclient->__call('Login',array($data));
#$result = $soapclient->Login($data);
#$result = $soapclient->__soapCall('Login',array($data));
} catch (SoapFault $e) {
$error = $e->faultcode;
echo str_replace('>',">\n",$error) ;
}
$last_request = $soapclient->__getLastRequest();
$last_response= $soapclient->__getLastResponse();
print "\nRequest: " .str_replace('>',">\n",$last_request);
print "\nResponse: ".str_replace('>',">\n",$last_response);
That way I got just that litle more information I needed! to:
2) enter password in the password field and the username in the user field
It works!
For those interested
Using the array structure and the 'new stdClass' both work
all three ways of parsing the call work (also the two commented out ones, use which one you like)

How to read soap response xml in php

This is my Soap Response xml,I need to get RebillCustomerID
How I can do this?
<?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Header><eWAYHeader
xmlns="http://www.eway.com.au/gateway/rebill/manageRebill">
<eWAYCustomerID>87654321</eWAYCustomerID><Username>test#eway.com.au</Username>
<Password>test123</Password></eWAYHeader></soap:Header><soap:Body>
<CreateRebillCustomerResponse xmlns="http://www.eway.com.au/gateway/rebill/manageRebill"><CreateRebillCustomerResult>
<Result>Success</Result><ErrorSeverity /><ErrorDetails />
<RebillCustomerID>90246</RebillCustomerID></CreateRebillCustomerResult>
</CreateRebillCustomerResponse></soap:Body></soap:Envelope><pre></pre>
try the code below. I am assuming your xml response is in $soapXMLResult variable
$soap = simplexml_load_string($soapXMLResult);
$response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->CreateRebillCustomerResponse;
$customerId = (string) $response->CreateRebillCustomerResult->RebillCustomerID;
echo $customerId;
How I did, create eway soap request and get eway soap result,may help others!
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions=array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test123");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
"customerFirstName"=>"Muhammad",
"customerLastName"=>"Shahzad",
"customerAddress"=>"cust ome rAddress",
"customerSuburb"=>"customer Suburb",
"customerState"=>"ACT",
"customerCompany"=>"customer Company",
"customerPostCode"=>"2345",
"customerCountry"=>">Australia",
"customerEmail"=>"test#gamil.com",
"customerFax"=>"0298989898",
"customerPhone1"=>"0297979797",
"customerPhone2"=>"0297979797",
"customerRef"=>"Ref123",
"customerJobDesc"=>"customerJobDesc",
"customerComments"=>"customerComments",
"customerURL" => "http://www.acme.com.au"
)
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
//echo "<pre>";echo "<br/>";
// print_r($response);
echo $result = $response->CreateRebillCustomerResult->Result;echo "<br/>";
echo $customerId = $response->CreateRebillCustomerResult->RebillCustomerID;echo "<br/>";
echo "<br/>";
if($result=='Success' AND $customerId){
echo 'Member Created at eWay Successfully!...<br/>';
echo 'Creating Recurring Billing Cycle on eWay,Please wait......<br/>';
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillCustomerResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillCustomerResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
if($customerId){
$bodyoptions2 = array(
"CreateRebillEvent " => array(
"RebillCustomerID" => $customerId,
"RebillInvRef" => "Ref123",
"RebillInvDes"=>"description",
"RebillCCName"=>"Mr Andy Person",
"RebillCCNumber"=>"4444333322221111",
"RebillCCExpMonth"=>"12",
"RebillCCExpYear"=>"15",
"RebillInitAmt"=>"100",
"RebillInitDate"=>date('d/m/Y'),
"RebillRecurAmt"=>"200",
"RebillStartDate"=>date('d/m/Y'),
"RebillInterval"=>"31",
"RebillIntervalType"=>"1",
"RebillEndDate"=>"31/12/2013",
)
);
try{
$response = $client->__soapCall("CreateRebillEvent", $bodyoptions2,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//print_r($response);
echo "<br/>";
echo $result2 = $response->CreateRebillEventResult->Result;echo "<br/>";
echo $RebillCustomerID = $response->CreateRebillEventResult->RebillCustomerID;echo "<br/>";
if($result2=='Success'){
echo 'Recurring Cycle Created Successfully at eWay!...<br/>';
echo 'Member Id is ===>'.$RebillCustomerID;
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillEventResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillEventResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
}
?>
If you are writing a client for a SOAP service and you want to manipulate or test their response by placing it in a local file and parsing that (maybe their response has errors and you want to fix the errors yourself), you can override the URL that your soapClient uses to call methods by calling __soapCall() directly:
$result = $this->soap_client->__soapCall( 'function_call_name', ['location' => $file_location] );
Where $file_location is the absolute or relative path to your copy of their xml response. What you put as your function call name doesn't matter, since the soap client will get the same xml response regardless of what function you try to call this way. The only thing that matters is that your $file_location be correct and that the xml file has the correct permissions to be read by apache if you run this in a browser.
You can then var_dump($response) and find the node you need rather than using simplexml_load_string. If you do it this way you can easily swap out your xml for their response later on.

SoapClient Returns "NULL", but __getLastResponse() returns XML

The variable $response in the below code is NULL even though it should be the value of the SOAP request. (a list of tides). When I call $client->__getLastResponse() I get the correct output from the SOAP service.
Anybody know what is wrong here? Thanks! :)
Here is my code :
$options = array(
"trace" => true,
"encoding" => "utf-8"
);
$client = new SoapClient("http://opendap.co-ops.nos.noaa.gov/axis/webservices/highlowtidepred/wsdl/HighLowTidePred.wsdl", $options);
$params = array(
"stationId" => 8454000,
"beginDate" => "20060921 00:00",
"endDate" => "20060922 23:59",
"datum" => "MLLW",
"unit" => 0,
"timeZone" => 0
);
try {
$result = $client->getHLPredAndMetadata($params);
echo $client->__getLastResponse();
}
catch (Exception $e) {
$error_xml = $client->__getLastRequest();
echo $error_xml;
echo "\n\n".$e->getMessage();
}
var_dump($result);
The reason that the $result (or the response to the SoapCall) is null is indeed because the WSDL is invalid.
I just ran into the same problem - the WSDL said the response should be PackageChangeBatchResponse yet the actual XML returns has PackageChangeResponse
Changing the WSDL to match the response / changing the response to match the WSDL resolves the issue
you should give an option parameter as below :
<?php
// below $option=array('trace',1);
// correct one is below
$option=array('trace'=>1);
$client=new SoapClient('some.wsdl',$option);
try{
$client->aMethodAtRemote();
}catch(SoapFault $fault){
// <xmp> tag displays xml output in html
echo 'Request : <br/><xmp>',
$client->__getLastRequest(),
'</xmp><br/><br/> Error Message : <br/>',
$fault->getMessage();
}
?>
"trace" parameter enables the output of request. Now, you should see the SOAP request.
(source: PHP.net

Amazon MWS Product Feed Not Submitting

I am working on the Amazon API. I want to submit the product feed on amazon account.
I have validated the XML file (product feed) by the Amazon Scratch Pad and i get the Response that Feed is submitted but when i run the script, to submit the same feed by script, i don't get any response.
Here is my code :
$req = new MarketplaceWebService_Model_SubmitFeedRequest();
$req->setMerchant(MERCHANTID);
$req->setMarketplaceIdList(MARKETPLACEID);
$req->setFeedType('_POST_PRODUCT_DATA_');
$req->setContentMd5(base64_encode(md5(stream_get_contents($fh), true)));
rewind($fh);
$req->setPurgeAndReplace(true);
$req->setFeedContent($fh);
$res = $mws->submitFeed($request);
echo $res;
I am unable to get the response, when i echo the $res.
I have changed the $res = $mws->submitFeed($request); to $res = $mws->submitFeed($req);. Still no success in submitting the feed. I am not getting any response header that Amazon return while submitting the feed.
The code is like this :
$req = new MarketplaceWebService_Model_SubmitFeedRequest();
$fh = fopen('feed.xml', 'r');
$req->setMerchant(MERCHANTID);
$req->setMarketplaceIdList(MARKETPLACEID);
$req->setFeedType('_POST_PRODUCT_DATA_');
$req->setContentMd5(base64_encode(md5(stream_get_contents($fh), true)));
rewind($fh);
$req->setPurgeAndReplace(true);
$req->setFeedContent($fh);
$res = $mws->submitFeed($req);
echo $res;
Apart from other things that might go wrong: You are submitting $request, while the thing you probably want to submit is $req.
Edit: Since you corrected this mistake but still have no result...:
submitFeed() returns a MarketplaceWebService_Model_SubmitFeedResponse object.
Echo does not work with objects, unless the object has a __toString() method, which this class doesn't. Try using print_r($res) or var_dump($res) instead.
Try this
$marketplaceIdArray = array("Id" => array($MARKETPLACE_ID));
$feedHandle = #fopen('php://temp', 'rw+');
fwrite($feedHandle, $feed);
rewind($feedHandle);
$parameters = array(
'Merchant' => $MERCHANT_ID,
'MarketplaceIdList' => $marketplaceIdArray,
'FeedType' => '_POST_PRODUCT_DATA_',
'FeedContent' => $feedHandle,
'PurgeAndReplace' => false,
'ContentMd5' => base64_encode(md5(stream_get_contents($feedHandle), true))
);
rewind($feedHandle);
$request = new MarketplaceWebService_Model_SubmitFeedRequest($parameters);
$return_feed = invokeSubmitFeed($service, $request);
fclose($feedHandle);

Categories