Make a web service call in php - php

So i have this working in ruby and i want to be able to do this in php. I am using the wamp server if that matters.
Here's the ruby method:
def response(url, body)
uri = URI(url)
request = Net::HTTP::Post.new(uri.request_uri)
request.body = body
http_session = Net::HTTP.new(uri.hostname, uri.port)
http_session.use_ssl = (uri.scheme == "https")
http_session.verify_mode = OpenSSL::SSL::VERIFY_NONE
response = http_session.request(request)
return response.body
end
I tried looking up other questions and this is where that got me:
$request_info = array();
$REQUEST_BODY = 'request body';
$full_response = #http_post_data(
'url',
$REQUEST_BODY,
array(
'headers' => array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
),
'timeout' => 60,
),
$request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//#HotelName') as $HotelName) {
echo strval($HotelName) . "\n";
}

http_post_data depends on pecl_http. Unless you must use http_post_data, cURL is probably installed by default on your WAMP server.
The code below is just an example; I haven't tested it but you get the idea:
$headers = array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
);
$ch = curl_init($server_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$full_response = curl_exec($ch);
curl_close($ch);

Related

Trying to turn wp_remote_request to curl php function with php to avoid to rely on wordpress

Here's my problem:
I need a curl call in order to use it from an environment outside WordPress.
The older code was:
public function post_api($path = '', $method = '', $body = '') {
$token = $this->get_token();
$headers = array(
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8',
'Connection' => 'Keep-Alive',
'Keep-Alive' => 'timeout=30, max=100',
'X-API-Key' => $token['key'],
'X-API-Hmac' => $token['token'],
);
$args = array(
'body' => $body,
'headers' => $headers,
'method' => strtoupper($method),
'sslverify' => false
);
$response = wp_remote_request($path, $args);
$body = array();
if (is_array($response) && isset($response['response']['code'])) {
//something with those data
}
return $body;
}
But now I need an universal curl call with php that can work outside wordpress (anywhere really). Something like this:
public function post_api($path = '', $method = '', $body = '') {
$token = $this->get_token();
$headers = array(
'Accept' => 'application/json',
'Content-Type' => 'application/json; charset=utf-8',
'Connection' => 'Keep-Alive',
'Keep-Alive' => 'timeout=30, max=100',
'X-API-Key' => $token['key'],
'X-API-Hmac' => $token['token'],
);
$args = array(
'body' => $body,
'headers' => $headers,
'method' => strtoupper($method),
'sslverify' => false
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $path);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt( $ch, CURLOPT_TIMEOUT,10);
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $body );
$head = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$response = [
'statusCode' => $httpCode,
'resp' => $head
];
curl_close($ch);
$body = array();
if (is_array($response) && isset($response['response']['code'])) {
//something with these data
}
return $body;
var_dump($body);
}
The problem is that it is returning something else:
Call using wp_remote_request
Query strings
0 baumiao#bau.com
emailAddress baumiao#bau.com
call using curl
Raw Content
--------------------------761ff1dfd8c7266e
Content-Disposition: form-data; name="0"
baumiao#bau.com
--------------------------761ff1dfd8c7266e--
Is there something that I missing? I read the curl documentation for PHP and I added all the setopt for that particular case, still, I'm not able to properly make the call.
Any help?

SOAP request working with SOAP UI but not with code

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);
}

POST Request PHP with Curl

I'm working on a wordpress project where I have to modify my theme, so I can request a JSON to an external API.
I've been searching through the internet how to do that and a lot of people use CURL.
I must do a POST request, yet I don't know how it works or how to do it.
So far I've got this code running:
$url='api.example.com/v1/property/search/';
$data_array = array(
$id_company => '123456',
$api_token => 'abcd_efgh_ijkl_mnop',
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_array);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'APIKEY: 111111111111111111111',
'Content-Type: application/json'
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result){die("Connection Failure");}
curl_close($curl);
echo($result);
I don't know where exactly I should put my authentication info or how does the curl methods work in PHP. Can you guys check it out and help me solve this?
There are some answers out there that would help you, such as this one.
However, WordPress actually has built-in functions to make GET and POST requests (that actually fall back to cURL I believe?) named wp_remote_get() and wp_remote_post(). Clearly in your case, you'll want to make use of wp_remote_post().
$url = 'https://api.example.com/v1/property/search/';
$data_array = array(
'id_company' => 123456,
'api_token' => 'abcde_fgh'
);
$headers = array(
'APIKEY' => 1111111111,
'Content-Type' => 'application/json'
);
$response = wp_remote_post( $url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.0',
'blocking' => true,
'headers' => $headers,
'body' => $data_array,
'cookies' => array()
)
);
if( is_wp_error( $response ) ){
$error_message = $response->get_error_message();
echo "Something went wrong: $error_message";
} else {
echo 'Success! Response:<pre>';
print_r( $response );
echo '</pre>';
}

Why file_get_contents return error?

I'm working OAuth connect Yahoo.jp login API
I try sending http request use file_get_contents but It's return errors
Here is my code
// my apps setting
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
// the data to send
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$data = http_build_query($data);
$header = array(
"Authorization: Basic " . base64_encode($client_id . ':' . $appSecret),
"Content-Type: application/x-www-form-urlencoded",
"Content-Length: ".strlen($data)
);
// build your http request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => implode("\r\n", $header),
'content' => $data,
'timeout' => 10
)
));
// send it
$resp = file_get_contents('https://auth.login.yahoo.co.jp/yconnect/v1/token', false, $context);
$json = json_decode($resp);
echo($json->token_type . " " . $json->access_token);
The result...
file_get_contents(https://auth.login.yahoo.co.jp/yconnect/v1/token): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /var/www/html/api/auth_proc2.php on line 33
Here is another error message get using set_error_handler()
file_get_contents(): Content-type not specified assuming application/x-www-form-urlencoded
I can't understand this situation
Because I send Content-type in http header
and allow_url_fopen = on in my php.ini
Please help me~! Thanks.
The other thing I'd suggest using is CURL rather then file_get_contents for multiple reasons; first you'll have a lot more control over the request, second its more standard to use curl requests when dealing with API's, and third you'll be able to see better what your problem is.
Try replacing your code with the following and see what you get.
$client_id = 'dj0zaiZpP~~~~~~~~~~~~~~~';
$appSecret = '129ad~~~~~~~~~~~~~~~~';
$data = array(
'grant_type' => 'authorization_code',
'redirect_uri' => 'My_redierct_page',
'code' => $_GET['code']
);
$curl = curl_init('https://auth.login.yahoo.co.jp/yconnect/v1/token');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($curl, CURLOPT_USERPWD, $client_id . ':' . $appSecret);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
$info = curl_getinfo($curl);
print_r($response);
echo '<br /><br />';
print_r($info);
curl_close($curl);
I assume its probably because your using Content-Type and not Content-type and Content-Length instead of Content-length.

PHP GCM appengine

I am trying to use gcm in appengine using PHP runtime. Following is the code, which uses URLFetch service
$context = array("https"=>
array( "method" => "post",
"content" => json_encode($fields),
"header" => "Content-Type: application/json\r\n" .
"Authorization: key=" . GOOGLE_API_KEY . "\r\n"
)
);
$context = stream_context_create($context);
$result = file_get_contents($url, false, $context);
Following is the Original code that uses PHP Curl:
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
PHP code that uses Curl works well, but the code that uses urlfetch service of appengine does't work. Can someone tell me where am I doing wrong.
This is tested code.
public function sendAndroidPushNotification($registration_ids, $message)
{
// Adding devicetoken in array
$registrationIds = array($registration_ids);
$msg = array(
'message' => $message,
'title' => 'notification center',
'tickerText' => $message,
'vibrate' => 1,
'sound' => 1,
);
$fields = array(
'registration_ids' => $registrationIds,
'data' => $msg
);
$fields = json_encode($fields);
$arrContextOptions=array(
"http" => array(
"method" => "POST",
"header" =>
'Authorization: key = '. "\r\n" .
'Content-Type: application/json'. "\r\n",
"content" => $fields,
),
"ssl"=>array(
"allow_self_signed"=>true,
"verify_peer"=>false,
),
);
$arrContextOptions = stream_context_create($arrContextOptions);
$result = file_get_contents('https://android.googleapis.com/gcm/send', false, $arrContextOptions);
return $result;
}

Categories