Use Cookies in PHP soap calls - php

I need to use cookies in my PHP calls, currently i am using the below request:
$publish_Data ='<?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>
<publishData xmlns="http://www.birst.com/">
<token>'.$login_token.'</token>
<spaceID>'.$space_id.'</spaceID>
<date>'.$date.'</date>
</publishData>
</soap:Body>
</soap:Envelope>';
$location_URL = "https://app2104.bws.birst.com/CommandWebService.asmx?wsdl";
$action_URL = "http://www.birst.com/publishData";
$client = new SoapClient(null, array(
'location' => $location_URL,
'uri' => "",
'trace' => 1,
));
try{
$publish_data_response = $client->__doRequest($publish_Data,$location_URL,$action_URL,1);
//Get response from here
//print_r($publish_data_response);
}catch (SoapFault $exception){
var_dump(get_class($exception));
var_dump($exception);
}
I need somehow to enable and use cookies in order in next calls that will follow.
i tried using
sessions_start()
but it didn't help - In Java, something called session_maintain_property is used which allows for the program to use cookies, how do i do the same in PHP?

Problem was solved.
the issue was with the SoapClient, when i was sending a request i created a new SoapClient for every call and that gave me a different cookies per each call - kind of a different session.
basically you need to define the soap call only once:
$client = new SoapClient(null, array(
'location' => $location_URL,
'uri' => "",
'trace' => 1,
));
and use the same client for the rest of the calls.

Related

Sending and requesting SOAP

I'm trying to use an example that I found on the internet to send and receive from xml to a SOAP url, but I could not understand very well how SOAP works.
Can anyone help me? Here is the code that I'm passing:
$xml = <<<XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice" xmlns:cnes="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/cnesusuario" xmlns:fil="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/filtropesquisa" xmlns:nom="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r2/nomecompleto" xmlns:nom1="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r0/nomefamilia" xmlns:cpf="http://servicos.saude.gov.br/schema/corporativo/documento/v1r2/cpf" xmlns:mun="http://servicos.saude.gov.br/schema/corporativo/v1r2/municipio" xmlns:uf="http://servicos.saude.gov.br/schema/corporativo/v1r1/uf" xmlns:tip="http://servicos.saude.gov.br/schema/corporativo/documento/v5r0/tipodocumento"><soap:Header><wsse:Security soap:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken wsu:Id="UsernameToken-F6C95C679D248B6E3F143032021465917"><wsse:Username>CADSUS.CNS.PDQ.PUBLICO</wsse:Username><wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">kUXNmiiii#RDdlOELdoe00966</wsse:Password><wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">KkB/ki6qUjcZpGNqL4monw==</wsse:Nonce><wsu:Created>2015-04-29T15:10:14.659Z</wsu:Created></wsse:UsernameToken></wsse:Security></soap:Header><soap:Body><cad:requestPesquisar><cnes:CNESUsuario><cnes:CNES>6963447</cnes:CNES><cnes:Usuario>LEONARDO</cnes:Usuario><!--Optional:--><cnes:Senha>?</cnes:Senha></cnes:CNESUsuario><fil:FiltroPesquisa><fil:CPF><cpf:numeroCPF>66105234368</cpf:numeroCPF></fil:CPF><fil:tipoPesquisa>IDENTICA</fil:tipoPesquisa></fil:FiltroPesquisa><cad:higienizar>0</cad:higienizar></cad:requestPesquisar></soap:Body></soap:Envelope>
XML;
$wsdl = 'https://servicoshm.saude.gov.br/cadsus/CadsusService/v5r0?wsdl';
$client = new SoapClient($wsdl, array(
'cache_wsdl' => WSDL_CACHE_NONE,
'cache_ttl' => 86400,
'login'=> "CADSUS.CNS.PDQ.PUBLICO",
'password'=> "kUXNmiiii#RDdlOELdoe00966",
'trace' => true,
'exceptions' => true,
));
$xmlVar = new SoapVar($xml, XSD_ANYXML);
$client->getCustomerInfo($xml);
Error:
Fatal error: Uncaught SoapFault exception: [Client] Function ("getCustomerInfo") is not a valid method for this service in /home/itconect/www/sisam/testeJ.php:18 Stack trace: #0 /home/itconect/www/sisam/testeJ.php(18): SoapClient->__call('getCustomerInfo', Array) #1 /home/itconect/www/sisam/testeJ.php(18): SoapClient->getCustomerInfo('
I have another doubt in this code. Would I receive the result or do I have to supplement it with something yet?
If you are using the WSDL of your code, than this SOAP service does not have a method called "getCustomerInfo". The methods according to the WSDL are pesquisar, consultar, incluir, atualizar, alterarSituacao and calcularGrauDeQualidade.
I'd also recommend using the php helpers instead of writing xml yourself (Examples: How to make a PHP SOAP call using the SoapClient class).
Edit: A very basic example
<?php
$wsdl = 'http://www.webservicex.net/BibleWebservice.asmx?WSDL';
$client = new SoapClient($wsdl, array(
'cache_wsdl' => WSDL_CACHE_NONE,
'trace' => true,
'exceptions' => true,
));
$keyword = new StdClass();
$keyword->BibleWords = "god";
$result = $client->GetBibleWordsbyKeyWord($keyword);
var_dump($result);

PHP Soap Fault: Could not connect to host

There are many question is similar like this. But I didn't got the solution when tried. Find my codes below:
Soap XML:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:pos="http://PostWebService.org/">
<soap:Header>
<pos:Authentication>
<!--Optional:-->
<pos:UserName>xxxxxxx</pos:UserName>
<!--Optional:-->
<pos:Password>yyyyyyyy</pos:Password>
</pos:Authentication>
</soap:Header>
<soap:Body>
.....
</soap:Body>
</soap:Envelope>
PHP Code:
$client = new SoapClient({soapurl},$params);
$auth = new stdClass();
$auth->UserName = 'xxxxxxx';
$auth->Password = 'yyyyyyyy';
$header = new SoapHeader('NAMESPACE','Authentication',$auth,false);
$client->__setSoapHeaders($header);
$result = $client->__soapCall('{soap function}',array()); // when this line executes it throws me the error "Could not connect to the host"
Please note, My Soap URL is in https. I tried lots other solutions from stack overflow but none of them work. I want anyone tell me why i am getting that error and what i did wrong in the request.
Another Code tried but still the same:
$opts = array(
'ssl' => array('ciphers'=>'RC4-SHA', 'verify_peer'=>false, 'verify_peer_name'=>false)
);
// SOAP 1.2 client
$params = array ('encoding' => 'UTF-8', 'verifypeer' => false, 'verifyhost' => false, 'soap_version' => SOAP_1_2, 'keep_alive' => false,'trace' => 1, 'exceptions' => 1, "connection_timeout" => 180, 'stream_context' => stream_context_create($opts) );
$client = new SoapClient({soapurl},$params);
//Remaining as the same above
When I tried with SoapUI it gives me a response.
Finally, I got the solution,
I found the problem. The host I was trying to connect is redirecting to another domain name. For some reason, PHP 5.6 doesn't carry the location automatically. So i defined the same soap url in the location options.
Eg:
$params = array('location' => {soapurl});
$client = new SoapClient({soapurl},$params);
Thanks for your time. :)
This solution worked for me.
E.g.
$client = new SoapClient('https://example.com/webservice.php?wsdl');
$client->__setLocation('https://www.somethirdparty.com');

PHP SOAP client not creating body

After over a half a day of trying and reading tutorials on creating a simple SOAP client, I am no closer to retrieving a request from API I attempting to work with.
WSDL: http://publicapi.ekmpowershop31.com/v1.1/publicapi.asmx?WSDL
I can make the request from SOAP UI with the following simple SOAP request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pub="http://publicapi.ekmpowershop.com/">
<soapenv:Header/>
<soapenv:Body>
<pub:GetOrders>
<!--Optional:-->
<pub:GetOrdersRequest>
<!--Optional:-->
<pub:APIKey>myApiKey</pub:APIKey>
</pub:GetOrdersRequest>
</pub:GetOrders>
</soapenv:Body>
</soapenv:Envelope>
This above returns the expected data.
When it comes to translating the request into a PHP I have the following:
$wsdl = 'http://publicapi.ekmpowershop31.com/v1.1/publicapi.asmx?WSDL';
$trace = true;
$exceptions = false;
$debug = true;
$client = new SoapClient($wsdl,
array(
'trace' => $trace,
'exceptions' => $exceptions,
'debug' => $debug,
));
$param = array('GetOrdersRequest' => array(
'APIKey' => 'myApiKey'
)
);
$resp = $client->GetOrders();
print_r($param);
print_r($client->__getLastRequest());
print_r($client->__getLastResponse());
If put the $param into the GetOrders function then, it breaks and nothing happens.
Even if I use an array in the $client->GetOrders(array('someArry' => $param)) then response and request still always looks the same and looks like the body of the SOAP request is never created:
Request:
?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://publicapi.ekmpowershop.com/"><SOAP-ENV:Body><ns1:GetOrders/></SOAP-ENV:Body></SOAP-ENV:Envelope>
Response:
<?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:Body><GetOrdersResponse xmlns="http://publicapi.ekmpowershop.com/"><GetOrdersResult><Status>Failure</Status><Errors><string>Object reference not set to an instance of an object.</string></Errors><Date>2017-04-03T16:00:42.9457446+01:00</Date><TotalOrders>0</TotalOrders><TotalCost xsi:nil="true" /></GetOrdersResult></GetOrdersResponse></soap:Body></soap:Envelope>
If anyone can shed some light on what I am doing wrong here that would be real big help?
P.S My experience of SOAP in PHP is limited as I am used to SOAP in a java env. Thanks
You need to pass the parameters into the $client->GetOrders() call. Also the WSDL defines some required parameters, so a minimal example is something like:
$wsdl = 'http://publicapi.ekmpowershop31.com/v1.1/publicapi.asmx?WSDL';
$trace = true;
$exceptions = false;
$debug = true;
$client = new SoapClient($wsdl,
array(
'trace' => $trace,
'exceptions' => $exceptions,
'debug' => $debug,
));
$param = array(
'GetOrdersRequest' => array(
'APIKey' => 'dummy-key',
'CustomerID' => 1,
'ItemsPerPage' => 1,
'PageNumber' => 1,
)
);
$resp = $client->GetOrders($param);
print_r($param);
print_r($client->__getLastRequest());
print_r($client->__getLastResponse());
This gives the error response:
<Errors><string>Invalid character in a Base-64 string.</string></Errors>
which presumably is because my API key is invalid.

How to remove attribute from envelope in SoapClient

Trying to use PHP-s own SoapClient, but I have come across an obstacle.
I'm using __soapCall for making requests, but the query fails, because encodingStyle attribute is set:
$client = new SoapClient(NULL, array(
'location' => 'http://myUri.com',
'uri' => 'http://namespace.com/producer'
));
$result = $client->__soapCall('GET_ALL');
Now doing $client->__getLastRequest(); shows Envolope node like this:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
How to remove SOAP-ENV:encodingStyle attribute and still use __soapCall(); ?
Apperantly I was missing "use" parameter in SoapClient construct. Solution:
$client = new SoapClient(NULL, array(
'location' => 'http://myUri.com',
'uri' => 'http://namespace.com/producer',
'use' => SOAP_LITERAL,
));

Unwanted <param0> node from PHP SoapClient non-wsdl mode

I'm trying to make a request with the PHP SoapClient in non-WSDL mode. I'm passing parameters as a multi-dimensional object as shown in the below code snippet:
$params = new stdClass;
$params->Characteristic = new stdClass;
$params->Characteristic->Name = 'PRODUCT_TYPE';
$params->Characteristic->CharacteristicValue = new stdClass;
$params->Characteristic->CharacteristicValue->Value = $type;
$params->Characteristic->CharacteristicValue->Type = 'STRING';
$client = new SoapClient(NULL, array( 'trace' => true, 'exceptions' => true, 'uri' => $uri, 'location' => $location,
'connection_timeout'=>9999,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'soap_version' => SOAP_1_1, 'encoding' => 'ISO-8859-1',
'use' => SOAP_LITERAL
));
$response = $client->thisIsTheFunction($params);
The generated XML is almost right apart from being wrapped in a tag:
<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://[removed]">
<soap-env:body>
<ns1:thisisthefunction>
<param0>
<characteristic>
<name>PRODUCT_TYPE</name>
<characteristicvalue>
<value>Adhoc</value>
<type>STRING</type>
</characteristicvalue>
</characteristic>
</param0>
</ns1:thisisthefunction>
</soap-env:body>
</soap-env:envelope>
The problem is this is being detected as malformed by the service. Is there any way we can remove this extra tag?
I think if you want remove param0 and put characteristicValue in this place, you need to use a SoapParam (http://www.php.net/manual/en/class.soapparam.php).
In fact, your call must proceed like that :
$response = $client->thisIsTheFunction(new SoapParam($params->Characteristic, 'ns1:Characteristic'));
Now, your generated XML looks like that :
<soap-env:envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://[removed]">
<soap-env:body>
<ns1:thisisthefunction>
<ns1:characteristic>
<name>PRODUCT_TYPE</name>
<characteristicvalue>
<value>Adhoc</value>
<type>STRING</type>
</characteristicvalue>
</ns1:characteristic>
</ns1:thisisthefunction>
</soap-env:body>
Good luck !

Categories