Cannot create object xml for client soap request - php

I am trying to make a client request for a soap web service, and when I try to create the xml with simplexml_load_string it says this:
Error: Cannot create object
With no any other errors, so I can't figure it out what am I doing wrong, my code is bellow, I hope you can help me to solve this issue
<?php
$produccion = false; //Cambiar a verdadero por producction
$url = "http://ws.maxirest.com/wsclientes/wscli06896.php";
//print_r($_POST);
$posts = $_POST;
if ($produccion == false) {
$posts['nombre'] =
$posts['apellido'] =
$posts['direccion'] =
$posts['pisodto'] =
$posts['localidad'] =
$posts['partido'] =
$posts['provincia'] =
$posts['telefono'] =
$posts['celular'] =
"PRUEBA";
}
$Datos = "<cliente>
<nombre>".$posts['nombre']."</nombre>
<apellido>".$posts['apellido']."</apellido>
<calle>".$posts['direccion']."</calle>
<altura>".$posts['altura']."</altura>
<pisodto>".$posts['pisodto']."</pisodto>
<localidad>".$posts['localidad']."</localidad>
<partido>".$posts['partido']."</partido>
<provincia>".$posts['provincia']."</provincia>
<telefono>".$posts['telefono']."</telefono>
<celular>".$posts['celular']."</celular>
<num_tarjeta>".$posts['num_tarjeta']."</num_tarjeta>
</cliente>";
$myXMLData = '<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.maxisistemas.com.ar">
<soapenv:Header/>
<soapenv:Body>
<ws:AltaSolicitud soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cXml>'.$Datos.'</cXml>
<Clave>123ClubMilaMREST5</Clave>
</ws:AltaSolicitud>
</soapenv:Body>
</soapenv:Envelope>';
$xml=simplexml_load_string($myXMLData) or die("Error: Cannot create object"); //<-Here is the error
$client = new SoapClient($url);
$result1 = $client->AltaSolicitud($xml);
$result2 = $client->ConsultaPuntos($xml);
?>

I can't get an answer but
=> "ERROR. ACCESO NO PERMITIDO"
But with the right credentials and data you should be able to get the information you need with below class.
Simply set your data in the setData() function / call it first and then call AltoSolicitud() with Clave as parameter
class Request extends \SoapClient
{
public $Datos;
public function __construct(array $options = [], $wsdl = 'http://ws.maxirest.com/wsclientes/wscli06896.php?wsdl')
{
$options = [
'features' => 1,
];
parent::__construct($wsdl, $options);
}
/**
* #param string $Clave
* #return string
*/
public function AltaSolicitud()
{
$Data = $this->getData();
try {
return $this->__soapCall('AltaSolicitud', [
$Data
]);
} catch (\SoapFault $e) {
return ($e->getMessage());
}
}
public function setData($posts,$produccion = false)
{
if ( ! $produccion) {
$posts['nombre'] =
$posts['apellido'] =
$posts['direccion'] =
$posts['pisodto'] =
$posts['localidad'] =
$posts['partido'] =
$posts['provincia'] =
$posts['telefono'] =
$posts['celular'] =
"PRUEBA";
}
$Datos = "<cliente><nombre>".$posts['nombre']."</nombre>
<apellido>".$posts['apellido']."</apellido>
<calle>".$posts['direccion']."</calle>
<altura>".$posts['altura']."</altura>
<pisodto>".$posts['pisodto']."</pisodto>
<localidad>".$posts['localidad']."</localidad>
<partido>".$posts['partido']."</partido>
<provincia>".$posts['provincia']."</provincia>
<telefono>".$posts['telefono']."</telefono>
<celular>".$posts['celular']."</celular>
<num_tarjeta>".$posts['num_tarjeta']."</num_tarjeta></cliente>";
$Clave = '123ClubMilaMREST5';
$myXMLData = <<<XML
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="http://ws.maxisistemas.com.ar">
<soapenv:Header/>
<soapenv:Body>
<ws:AltaSolicitud soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<cXml xsi:type="xsd:string">' . str_replace(PHP_EOL,'',$Datos) . '</cXml>
<Clave xsi:type="xsd:string">' . $Clave . '</Clave>
</ws:AltaSolicitud>
</soapenv:Body>
</soapenv:Envelope>
XML;
$this->Datos = $myXMLData;
return $this;
}
/**
* #param string $Cod_Tarj
* #param string $Clave
* #return string
*/
public function ConsultaPuntos($Cod_Tarj, $Clave)
{
return $this->__soapCall('ConsultaPuntos', [$Cod_Tarj, $Clave]);
}
public function getData(){
return $this->Datos;
}
$request = (new Request)->setData($_POST,false)->AltaSolicitud();
var_dump($request);

#Ricardo
I was able to make your code work by adding "wsdl" to the url. After this change I did not see the error "Cannot create object".
$url = "http://ws.maxirest.com/wsclientes/wscli06896.php?wsdl";
I made some other minor changes, but I don't think they are important:
$xml = simplexml_load_string( $myXMLData ); //or die("Error: Cannot create object"); //<-Here is the error
$client = new SoapClient( $url , array('trace' => 1 ));
$result1 = $client->AltaSolicitud($xml);
echo "Response:\n" . $client->__getLastResponse() . "\n";
And the result was the same "ERROR. ACCESO NO PERMITIDO" already noted. To me it appears that the soap parameter <Clave>123ClubMilaMREST5</Clave>is incorrect or expired. I noticed this because the word is almost the same in Italian (chiave = clave = key). I assume this is an API key like many web services require?
SOAP Response
<?xml version="1.0" encoding="ISO-8859-1"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:AltaSolicitudResponse xmlns:ns1="http://ws.maxisistemas.com.ar">
<return xsi:type="xsd:string">ERROR. ACCESO NO PERMITIDO</return>
</ns1:AltaSolicitudResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

Related

Can't gzdecode on base64decode from soap response

I got a problem with this SOAP response :
<?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:Body>
<GetStockResponse xmlns="http://retailexpress.com.au/">
<GetStockResult>base64Binary</GetStockResult>
</GetStockResponse>
</soap:Body>
</soap:Envelope>
So, my code for handle this response look like this :
public function getStock()
{
$soapClient = $this->getSoapClient();
$xmlRequest = soapHead . '<ret:GetStock></ret:GetStock>' . soapFoot;
try {
$request = $soapClient->__anotherRequest('GetStock', $xmlRequest);
$requestDecoded = base64_decode($request);
$stock = gzdecode($requestDecoded);
} catch (SoapFault $e ){
var_dump($e);
exit();
}
$response = new Response($stock);
$response->headers->set('Content-Type', 'text/xml');
return $response;
}
With this code I always got this error :
Warning: gzdecode(): data error
But if I var_dump $request decoded and I try to gzdecode this string it works !
I can't find my mistake here ...
And for each try I got to wait 5 minutes ^^'
I hope I'm enough understandable
Thanks by advance
Tanguy
I find the solution,
The soap response is an xml so you need to create a SimpleXmlElement to get the content
$request = $soapClient->__anotherRequest('GetStock', $xmlRequest);
$xmlRequest = new \SimpleXMLElement($request);
$response = $xmlRequest->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->GetStockResponse;
$result = (string) $response->GetStockResult;
$requestDecoded = base64_decode($result);
$stock = gzdecode($requestDecoded);

Soap request working in SoapUI but not in Wordpress plugin

I've been searching around for a solution to my problem, but to no avail. I'm trying to send a soap request through a Wordpress plugin using the following:
function soapRequest($soapUsername, $soapNonce, $soapDateTime, $soapPassword) {
$wsdl = 'http://www.beautyfort.com/api/wsdl/v2/wsdl.wsdl';
$trace = true;
$exceptions = false;
$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
// Must be a stdClass (and not an array)
$auth = new stdClass();
$auth->Username = $soapUsername;
$auth->Nonce = $soapNonce;
$auth->Created = $soapDateTime;
$auth->Password = $soapPassword;
$header = new SoapHeader('http://www.beautyfort.com/api/', 'AuthHeader', $auth);
$client->__setSoapHeaders($header);
$xml_array['TestMode'] = 'true';
$xml_array['StockFileFormat'] = 'JSON';
$xml_array['SortBy'] = 'StockCode';
try {
$response = $client->GetStockFile($xml_array);
}
catch (Exception $e) {
log_me("Error!");
log_me($e -> getMessage());
log_me('Last response: '. $client->__getLastResponse());
}
log_me('Last request: '. $client->__getLastRequest());
log_me($response);
}
This produces the following request:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://www.beautyfort.com/api/">
<SOAP-ENV:Header>
<ns1:AuthHeader>
<ns1:Username>joetest</ns1:Username>
<ns1:Nonce>htflFfIKM4</ns1:Nonce>
<ns1:Created>2019-02-09T10:13:51.000Z</ns1:Created>
<ns1:Password>NGFjYTJiNzJmOWY2MzBmY2M2MjJkNjg1MDgyMWRjMzQxOGY1YTNjYQ==</ns1:Password>
</ns1:AuthHeader>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns1:GetStockFileRequest>
<ns1:TestMode>true</ns1:TestMode>
<ns1:StockFileFormat>JSON</ns1:StockFileFormat>
<ns1:SortBy>StockCode</ns1:SortBy>
</ns1:GetStockFileRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
And I get an invalid credentials error. I've also been testing in SoupUI and the following request works:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:api="http://www.beautyfort.com/api/">
<soapenv:Header>
<api:AuthHeader>
<api:Username>joetest</api:Username>
<api:Nonce>tJrsRlQt6i</api:Nonce>
<api:Created>2019-02-06T23:34:11.000Z</api:Created>
<api:Password>ZTBhMmE5OGY4YTNlZWIzZTE0ZTc2ZjZiZDBhM2RhMjJmNzAxNzYwZA==</api:Password>
</api:AuthHeader>
</soapenv:Header>
<soapenv:Body>
<api:GetStockFileRequest>
<api:TestMode>true</api:TestMode>
<api:StockFileFormat>JSON</api:StockFileFormat>
<!--Optional:-->
<api:FieldDelimiter>,</api:FieldDelimiter>
<!--Optional:-->
<api:StockFileFields>
<!--1 or more repetitions:-->
<api:StockFileField>StockCode</api:StockFileField>
<api:StockFileField>Category</api:StockFileField>
<api:StockFileField>Brand</api:StockFileField>
<api:StockFileField>Collection</api:StockFileField>
<api:StockFileField>Category</api:StockFileField>
</api:StockFileFields>
<api:SortBy>StockCode</api:SortBy>
</api:GetStockFileRequest>
</soapenv:Body>
</soapenv:Envelope>
Now the only differences I can see (apart from the optional fields) is the names of the namespace, and the use of the Xml tag at the top of the request. Both of these shouldn't matter right? I'd really appreciate your help on this as I've been scratching my head for ages.
Thank you in advance!
Your perfect just need to set UTC timezone and secret format like below:
base64 encoded(sha1(Nonce . Created . Secret))

Add xmlns to SoapParam in PHP

I have the proper SOAP request being created except that I need the LogOn node to have an xmlns attribute. This is what the attribute looks like: xmlns="http://www.ultipro.com/dataservices/bidata/2". I have used SOAPUI to test the request and it appears that if I add that xmlns then the response should be a success.
Here is my current code:
function Login($username, $password, $clientaccesskey, $useraccesskey)
{
class LogOn
{
function __construct($request)
{
$this->logOnRequest = $request;
}
}
// Class handler for the request
class logOnRequest {
function __construct($usr, $pwd, $cak, $uak)
{
$this->UserName = $usr;
$this->Password = $pwd;
$this->ClientAccessKey = $cak;
$this->UserAccessKey = $uak;
}
}
// Conversion to a SOAP object
$lor = new LogOnRequest($username, $password, $clientaccesskey, $useraccesskey);
$lo = new LogOn($lor);
$logOnRequest = new SoapVar($lor, SOAP_ENC_OBJECT, 'logOnRequest');
$loi = new SoapVar($lo, SOAP_ENC_OBJECT);
$headers = array();
$headers[] = new SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', 'http://www.ultipro.com/dataservices/bidata/2/IBIDataService/LogOn');
$headers[] = new SoapHeader('http://www.w3.org/2005/08/addressing', 'To', 'https://service4.ultipro.com/services/BiDataService');
try
{
$soapclient = new SoapClient('https://service4.ultipro.com/services/BiDataService', array('soap_version' => SOAP_1_2, 'encoding' => 'UTF-8', 'exceptions' => TRUE, 'trace' => TRUE));
$soapclient->__setSoapHeaders($headers);
// Direct call to the LogOn method and SOAP parameter pass
$response = $soapclient->LogOn(new SoapParam($loi, 'LogOn'));
echo json_encode($response);
echo htmlentities($soapclient->__getLastRequest());
}
catch(SoapFault $fault){
echo $fault->faultstring;
}
}
This is what my request looks like:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://www.ultipro.com/dataservices/bidata/2" xmlns:ns2="http://www.w3.org/2005/08/addressing">
<env:Header>
<ns2:Action>http://www.ultipro.com/dataservices/bidata/2/IBIDataService/LogOn</ns2:Action>
<ns2:To>https://service4.ultipro.com/services/BiDataService</ns2:To>
</env:Header>
<env:Body>
<ns1:LogOn>
<logOnRequest>
<UserName></UserName>
<Password></Password>
<ClientAccessKey></ClientAccessKey>
<UserAccessKey></UserAccessKey>
</logOnRequest>
</ns1:LogOn>
</env:Body>
</env:Envelope>
It needs to look like this:
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://www.ultipro.com/dataservices/bidata/2" xmlns:ns2="http://www.w3.org/2005/08/addressing">
<env:Header>
<ns2:Action>http://www.ultipro.com/dataservices/bidata/2/IBIDataService/LogOn</ns2:Action>
<ns2:To>https://service4.ultipro.com/services/BiDataService</ns2:To>
</env:Header>
<env:Body>
<ns1:LogOn xmlns="http://www.ultipro.com/dataservices/bidata/2">
<logOnRequest>
<UserName></UserName>
<Password></Password>
<ClientAccessKey></ClientAccessKey>
<UserAccessKey></UserAccessKey>
</logOnRequest>
</ns1:LogOn>
</env:Body>
</env:Envelope>

Problems Calling SOAP Web Service Using PHP

This is my SOAP request:
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:impl="http://impl.user">
<soapenv:Header/>
<soapenv:Body>
<impl:UserSessionDetails soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<in0 xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">requstXml</in0>
<in1 xsi:type="impl:UserInfo">
<password xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">pwd</password>
<userName xsi:type="soapenc:string" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/">pwd</userName>
</in1>
</impl:UserSessionDetails>
</soapenv:Body>
</soapenv:Envelope>
I've tried the following PHP code:
$soapClient = new SoapClient("http://example.com/services/?WSDL");
$sh_param = array(
'userName' => 'user',
'Password' => 'pwd'
);
$headers = new SoapHeader('http://tempuri.org/', false);
$soapClient->__setSoapHeaders(array($headers));
$requestXML = '<request name= "UserSessionDetails"><UserDetails><user_name>username</user_name><from_date>fromdate</from_date><to_date>to_date</to_date><group></group></UserDetails></request>';
$result = $soapClient->UserSessionDetails(array('in0'=> $requestXML, 'in1'=> $sh_param));
$simple = $result->$simple = $result->UserSessionDetailsResponse;
$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
echo "<pre>";
print_r($vals);
echo "</pre>"
But it returns nothing. Can anybody please tell me what the problem is?
Do not use raw xml in SoapClient requests. Use objects/arrays or SoapVar instead.
Basic example:
<?php
$client = new \SoapClient('http://example.com/services/?WSDL');
// Optionally your service endpoint
$client->__setLocation('http://example.com/services');
$userDetails = new stdClass();
$userDetails->user_name = 'username';
$userDetails->from_date = 'fromdate';
$userDetails->to_date = 'to_date';
$in0 = new stdClass();
$in0->UserDetails = $userDetails;
$in1 = new stdClass();
$in1->userName = 'pwd';
$in1->Password = 'pwd';
$request = new stdClass();
$request->in0 = $in0;
$request->in1 = $in1;
$result = $client->UserSessionDetails($request);
You can debug you SOAP services with any SOAP client like SOAPUI
P.S.
Have a look at Zend_Soap_Client and SoapVar examples

How to create proper xml for SOAP Client function?

I've spend hours with SOAPClient and still get no result, hope someone can help me. I'm trying to create and send to web-service following code:
POST /PortalServices/PortalServices.asmx HTTP/1.1
Host:***.***.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://***.com/CreateUser"
<?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>
<UserCredentials xmlns="http://***.com/">
<UserName>string</UserName>
<PassWord>string</PassWord>
<ServiceName>string</ServiceName>
</UserCredentials>
</soap:Header>
<soap:Body>
<CreateUser xmlns="http://***.com/">
<user>
<Name>string</Name>
<Email>string</Email>
<PassWord>string</PassWord>
<WsServices>
<WsService>
<Id>int</Id>
</WsService>
</WsServices>
</user>
</CreateUser>
</soap:Body>
</soap:Envelope>
To get this xml I use the following code:
<?php
class WsService {
public $Id = "****";
}
class WsServices {
public $WsService;
public function __construct() {
$this->WsService = new WsService();
}
}
class WsUser {
public $Name = 'Sasha Lavasov';
public $Email = 'imsashko#gmail.com';
public $PassWord = 'test';
public $WsServices;
public function __construct() {
$this->WsServices = new WsService();
}
}
$ini = ini_set("soap.wsdl_cache_enabled","0");
$soap_url = 'http://***.***.com/PortalServices/PortalServices.asmx?wsdl';
$soapClient = new \SoapClient($soap_url, array(
'soap_version'=>SOAP_1_2,
'trace' => 1,
'exceptions' => true,
'cache_wsdl' => WSDL_CACHE_NONE
));
$hdd = new stdClass();
$hdd->UserName = '***';
$hdd->PassWord = '***';
$hdd->ServiceName = '***';
$hd = new SoapVar($hdd, SOAP_ENC_OBJECT);
$headers = new \SoapHeader('http://***.***.com/PortalServices', 'UserCredentials', $hd);
// Prepare Soap Client
$soapClient->__setSoapHeaders(array($headers));
$user = new WsUser();
// Setup the CreateUser parameters
$ap_param = array(
'Name' => 'Sasha Lavasov',
'WsUser' => $user
);
$param = new \SoapParam($user, 'WsUser');
// Call CreateUser ()
$error = 0;
try {
//Build user entity
$usr = new WsUser();
$wsServices = new StdClass();
$id = new StdClass();
$id->Id = '***';
$wsServices->WsService = $id;
$usr->WsServices = $wsServices;
$createUser = new stdClass();
$createUser->user = $usr;
$createUser = new SoapVar($createUser, SOAP_ENC_OBJECT, "WsUser", "http://***.***.com/PortalServices/PortalServices.asmx?op=CreateUser");
$pm = new SoapParam($createUser, "user");
$soapClient->CreateUser($pm);
//Here I get xml
var_dump( $soapClient->__getLastRequest()); die();
} catch (\SoapFault $fault) {
$error = 1;
print($fault->faultcode." - ".$fault->faultstring); die();
}
if ($error == 0) {
// DO SOMETHING
} else {
}
$res = $soapClient->__getLastResponse();
print_r($res); die();
But instead I get something like this:
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="http://***.***.com/PortalServices/PortalServices.asmx?op=CreateUser" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://***.com/" xmlns:ns3="http://***.***.com/PortalServices">
<env:Header>
<ns3:UserCredentials>
<UserName>***</UserName>
<PassWord>***</PassWord>
<ServiceName>***</ServiceName>
</ns3:UserCredentials></env:Header>
<env:Body>
<ns2:CreateUser xsi:type="ns1:WsUser">
<user>
<Name>Sasha Lavasov</Name>
<Email>imsashko#gmail.com</Email>
<PassWord>test</PassWord>
<WsServices><WsService><Id>***</Id></WsService></WsServices>
</user>
</ns2:CreateUser>
</env:Body>
</env:Envelope>
And get FALSE as result.
In the list of server's functions (using __getFunctions()) I've got following:
CreateUserResponse CreateUser(CreateUser $parameters)
Can anyone help me or just tell where I'm wrong?
Just a suggestion.
In your good xml you've:
<UserCredentials xmlns="http://***.com/">
but in your PHP you set:
$headers = new SoapHeader('http://***.***.com/PortalServices', 'UserCredentials', $hd);
Then you've 2 different namespaces: http://***.***.com/PortalServices instead of http://***.com/

Categories