SOAP request working with SOAP UI but not with code - php

I am trying to execute following WSDL request in PHP. SOAP api does not have any authentication.
When i am running this code using SOAP UI it is working fine. But through code it is not working.
Here is my code:
<?php
$soapUrl = "https://dimasys.plasticentre.be:8443/dimasys/prices/DimasysService.wsdl";
// xml post structure
$xml_post_string = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ins="http://www.infomat.eu/dimasys/insertorderrequest"><soapenv:Header/><soapenv:Body><ins:insertOrderRequest><ins:order><ins:order_no>TEST-DODE 8</ins:order_no><ins:customer><ins:customer_no></ins:customer_no><ins:besteladresnummer>1</ins:besteladresnummer><ins:customer_user_volgnr>0</ins:customer_user_volgnr></ins:customer><ins:email>helpdima#infomat.eu</ins:email><ins:created_dt>2021-02-05</ins:created_dt><ins:firma>PLC</ins:firma><ins:billingAddress><ins:address><ins:company>Test infomat</ins:company><ins:initials></ins:initials><ins:firstname></ins:firstname><ins:prefix></ins:prefix><ins:lastname></ins:lastname><ins:addressline1>Laarstraat</ins:addressline1><ins:addressline2></ins:addressline2><ins:house_number>16</ins:house_number><ins:house_number_addition></ins:house_number_addition><ins:zipcode>2610</ins:zipcode><ins:city>Wilrijk</ins:city><ins:state></ins:state><ins:country><ins:countrycode>BE</ins:countrycode><ins:name>Belgiƫ</ins:name></ins:country><ins:addressnumber></ins:addressnumber></ins:address></ins:billingAddress><ins:shippingAddress><ins:address><ins:company>Test infomat</ins:company><ins:initials></ins:initials><ins:firstname></ins:firstname><ins:prefix></ins:prefix><ins:lastname></ins:lastname><ins:addressline1>Laarstraat</ins:addressline1><ins:addressline2></ins:addressline2><ins:house_number>16</ins:house_number><ins:house_number_addition></ins:house_number_addition><ins:zipcode>2610</ins:zipcode><ins:city>Wilrijk</ins:city><ins:state></ins:state><ins:country><ins:countrycode>BE</ins:countrycode><ins:name>Belgiƫ</ins:name></ins:country><ins:addressnumber></ins:addressnumber></ins:address></ins:shippingAddress><ins:orderLines><ins:order_line><ins:line_id>10</ins:line_id><ins:sku>929740</ins:sku><ins:eancode></ins:eancode><ins:description></ins:description><ins:qty_ordered>2</ins:qty_ordered><ins:regular_price></ins:regular_price><ins:promo_price></ins:promo_price><ins:discount_percentage></ins:discount_percentage><ins:discount_amount></ins:discount_amount><ins:sales_price></ins:sales_price><ins:total_amount></ins:total_amount><ins:vat_rate></ins:vat_rate></ins:order_line></ins:orderLines><ins:shippingCosts>0</ins:shippingCosts><ins:subTotal></ins:subTotal><ins:shippingMethod></ins:shippingMethod><ins:paymentMethod></ins:paymentMethod><ins:paymentReference></ins:paymentReference></ins:order></ins:insertOrderRequest></soapenv:Body></soapenv:Envelope>'; // data from the form, e.g. some ID number
$webService = new SoapClient($soapUrl);
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: https://dimasys.plasticentre.be:8443/dimasys/insertorders",
"Content-length: ".strlen($xml_post_string),
);
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close($ch);
echo "<pre>";var_Dump($response);exit;
?>
I am getting blank response in return. Please help me how i can do it.
I tried SOAP Client as well as php CURL.

Using SoapClient I'm able to connect to the SOAPService when I'm setting the location parameter. This parameter is useful whenever the SOAPService sits behind a proxy and answers with its local IP address. When omitting this parameter I cant connect to the server.
Note that I'm sending dummy data to the Server which results in a SoapFault Server Error.
The created request from the wsdl is sent inside the parameters array.
Hope this is useful as a starting point.
<?php
try {
$wsdlUrl = 'https://dimasys.plasticentre.be:8443/dimasys/prices/DimasysService.wsdl';
$soapOptions = [
'soap_version' => SOAP_1_2,
'location' => 'https://dimasys.plasticentre.be:8443/dimasys/prices/DimasysService.wsdl',
'encoding' => 'utf-8',
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'exceptions' => true,
'cache_wsdl' => WSDL_CACHE_NONE
];
$client = new SoapClient($wsdlUrl, $soapOptions);
$return = $client->__soapCall('getPrijzen', [
'parameters' => [
'tarieflijst' => 'test',
'factuuradresnummer' => 10,
'leveradresnummer' => 10,
'taal' => 'test',
'muntcode' => 'test',
'artikelen' => [
'artikel' => [
'artikelcode' => '123',
'aantal' => 10
]
]
]
]);
var_dump($return);
} catch(Exception $e) {
var_dump($e);
}

Related

I'am getting error while sending SOAP web service a post requirest with cURL

I am trying to get info with soap web service but it is giving me an error Request format is invalid: multipart/form-data; boundary=------------------------b35e9c9f375db7a5.
$id = $_POST['id'];
$servicepassword = $_POST['servicePassword'];
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://webgov.com.tr/WebService/Kontrol.asmx/PasoSorguKontrol',
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => [
'id' => $id,
'servicepassword' => $servicepassword
],
CURLOPT_FOLLOWLOCATION => 1,
));
$resp = curl_exec($ch);
curl_close($ch);
echo $resp;
this web service need two variables to work, student id and web service password. and giving xml output. i could not make the code working. i am a newbie btw.
The solution is using CURLOPT_HTTPHEADER. I even make a function with this codes and it solved my problem.
function httpPost($url,$params) {
$postData = '';
foreach($params as $k => $v) {
$postData .= $k . '='.$v.'&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}

PHP stream post request not working, but works with curl

I want to send post request as php stream
$aruguments = http_build_query(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);
$opts_stream = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/json' .
'x-requested-with: XMLHttpRequest',
'content' => $aruguments
)
);
$context_stream = stream_context_create($opts_stream);
$json_stream = file_get_contents('https://api.example.de/Search', false, $context_stream);
$data_stream = json_decode($json_stream, TRUE);
For some reason i get error saying:
failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
If i send this same request with cUrl it works normaly but its very slow.
Here is my cUrl request that works
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.example.de/Search');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ \"apikey\": \"xxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"min\": 20, \"appid\": 730, \"items_per_page\": $number_of_items_per_request }");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Requested-With: XMLHttpRequest';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close ($ch);
There are a couple of issues with the posted code.
Headers
When you're adding headers, you set them all in one single string. For the target server to know when one header ends and the other begins, you need to separate them using new lines (\r\n):
'header' => "Content-Type: application/json\r\n"
. "x-requested-with: XMLHttpRequest\r\n",
Post data
The big difference between your stream context and your cURL code is that your cURL code are posting the data in json-format, while you're stream context are posting the data as a x-www-form-urlencoded string. You're still telling the server that the content is json though, so I guess the server gets a bit confused.
Post the data as json instead by changing:
$aruguments = http_build_query(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);
to
$aruguments = json_encode(
array(
'apikey' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'appid' => 730,
'min' => 20,
'items_per_page' => 100
)
);

PHP - How to set https headers to soap ws request

I'm using SoapUI 5.3.0 to test a SOAP ws request.
I was requested to send user and password via https headers not via soap headers.
It works well when I use this SoapUi tool:
However, when I try to do it from php I always get an authentication error, exactly the same error I get when I use a wrong password on purpose, I've tried several combinations but none of them gave me expected results
code example:
$data['Contrato'] = '123456';
$data['FechaInicio'] = '11/07/2017';
$data['FechaFin'] ='11/07/2017';
$client = new SoapClient( "https://example.com/WebService?WSDL", array(
"exceptions" => 0,
"trace" => 1,
'stream_context' => stream_context_create(array(
'http' => array(
'header' => 'Username:xxx#gmail.com\\n\\r Password:notrealpwd'
),
)),
));
$result = $client->__soapCall('depositos', $data);
Does any of you knows what I am doing wrong?
try with:
$client = new SoapClient($wsdl, array("trace" => 1, "exceptions" => 0,
"login" => $login, "password" => $password) );
At the end I finished using curl to set the needed headers, that solved it.
<?php
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hub="https://example.com/WebService?WSDL">
<soapenv:Header/>
<soapenv:Body>
<hub:depositos>
<!--Optional:-->
<hub:solicitud>
<Contrato>123456</Contrato>
<FechaInicio>11/07/2017</FechaInicio>
<!--Optional:-->
<FechaFin>11/07/2017</FechaFin>
</hub:solicitud>
</hub:depositos>
</soapenv:Body>
</soapenv:Envelope>';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: ''",
"Content-length: ".strlen($xml_post_string),
"Username: xxx#gmail.com",
"Password: notrealpwd"
);
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $ws_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);

php soap:ServerServer was unable to process request. ---> Sequence contains no elements

I need to send an XML as soap request using CURL. I have created xml using
$xml = "<?xml .............." blah blah
That looks like
<?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><extLoginData xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><ThreePLKey>4dfdf34</ThreePLKey><Login>abv</Login><Password>abc</Password><FacilityID>1ee</FacilityID><CustomerID>xfs</CustomerID></extLoginData><orders xmlns='http://www.JOI.com/schemas/ViaSub.WMS/'><Order><TransInfo><ReferenceNum>Test</ReferenceNum><PONum>12345</PONum></TransInfo><ShipTo><Name></Name><CompanyName>Peter's Test</CompanyName><Address><Address1>7301 Lennox Ave Unit E3</Address1><Address2></Address2><City>Los Angeles</City><State>CA</State><Zip>90010</Zip><Country>US</Country></Address><PhoneNumber1>858-449-8022</PhoneNumber1><EmailAddress1>lshaules#mercatismedia.com</EmailAddress1><CustomerName>Elizabeth Shaules</CustomerName></ShipTo><ShippingInstructions><Carrier>USPS</Carrier><Mode>First Class Mail</Mode><BillingCode>Prepaid</BillingCode></ShippingInstructions><OrderLineItems><OrderLineItem><SKU>947</SKU><Qualifier>XXX</Qualifier><Qty>1</Qty></OrderLineItem></OrderLineItems></Order></orders></soap:Body></soap:Envelope>
And I am using following code to send CURL request
$url = 'http://someurl.com/Contracts.asmx';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 120);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'SOAPAction:"http://www.example.com/ViaSub.WMS/CreateOrders"',
'Content-Type: text/xml; charset=utf-8',
));
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $orderXml);
$result = curl_exec($curl);
But I am getting
soap:ServerServer was unable to process request. ---> Sequence contains no elements
I have searched but haven't found any thing related to it. Can you please let me know what I am doing wrong and how I do it?
This looks like a schema validation error. You don't provide a link to the definition, but a quick search showed me this documentation page. If this is the one you need take a look at the WSDL: https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL
Look for instance the element PalletCount within Order. You see it has minOccurs="1", meaning it's mandatory. But in the xml string you copy there's no such element. That's indeed a sequence with missing elements. (There may be some other schema inconsistencies, have a close look).
Also, consider using the SoapClient PHP class
$WSDL = 'https://secure-wms.com/webserviceexternal/contracts.asmx?WSDL';
$options = [
'trace' => true,
'cache' => WSDL_CACHE_NONE,
'exceptions' => true
];
$client = new SoapClient($WSDL, $options);
$payload = [
'extLoginData' => [
'ThreePLKey' => '4dfdf34',
'Login' => 'abv',
'Password' => 'abc',
'FacilityID' => '1ee',
'CustomerID' => 'xfs'
],
'orders' => [
'Order' => [
// etc...
]
]
]);
$response = $client->CreateOrders($payload);
This way the client handles the schema validation, headers setting (you can set additional headers, though), the namespacing, and the array to xml conversion.
Use this
$xml = "<?xml ..............</soap:Envelope>";
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://www.example.com/ViaSub.WMS/CreateOrders",
"Content-length: ".strlen($xml),
); //SOAPAction: your op URL
$url = 'http://someurl.com/Contracts.asmx';
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

Php curl json post returns error

I am trying a little script to create and update domain names using Digital Ocean api v2 here - https://developers.digitalocean.com/documentation/v2/#update-a-domain-record
For some reason the response from the server is that I am missing record type.
Here is my code:
$headers = array(
'Content-Type:application/json',
'Authorization: Bearer ' . file_get_contents('token.txt') );
$rawdata = array(
'type' => 'A',
'name' => 'sub',
'data' => '162.10.66.0',
'priority' => null,
'port' => null,
'weight' => null
);
$postdata = json_encode($rawdata);
$ch = curl_init(); // initiate curl
$url = "https://api.digitalocean.com/v2/domains/mydomain.org/records";
curl_setopt($ch, CURLOPTURL,$url);
curl_setopt($ch, CURLOPTPOST, true);
curl_setopt($ch, CURLOPTPOSTFIELDS, $postdata);
curl_setopt($ch, CURLOPTRETURNTRANSFER, true);
curl_setopt($ch, CURLOPTHTTPHEADER, $headers);
$output = curlexec ($ch); // execute
curl_close ($ch); // close curl handle
vardump($output); // show output
This is the error
string(81) "{"id":"unprocessable_entity","message":"Record type is not included in the list"}"
What am I missing here?
It's not a PHP error, it's an error return by the webservice you're calling. Check their documentation to see if you're sending the right stuff to them.

Categories