Converting wp_remote_post() to cURL - php

I have this WordPress code using wp_remote_post() to make an API call to LinkedIn.
$args = array(
'headers' => array('Content-Type' => 'text/xml'),
'body' => "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>{$nCompanyID}</id></company>"
);
$access_token = $datapass->access_token_get();
$params = array('oauth2_access_token' => $access_token);
$resource = "https://api.linkedin.com/v1/people/~/following/companies?" . http_build_query($params);
$response = wp_remote_post( $resource, $args);
$code = $response['response']['code'];
$body = wp_remote_retrieve_body($response);
$RV = ($code == '201');
return $RV;
It works. Now, I need to convert it to php cURL.
I have tried various examples of php cURL posting XML that I found online, but no luck.
Here's the latest attempt.
$access_token = "long_string_of_characters";
$nCompanyID = 2495437;
$xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>{$nCompanyID}</id></company>";
$url = 'https://api.linkedin.com/v1/people/~/following/companies?oauth2_access_token='.$access_token;
$headers = array(
"Content-type: text/xml",
"Content-length: " . strlen($xml)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array('body' => $xml));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
$data comes back with a 400 error and message saying 'Unexpected element: CDATA'. If I remove the array from CURLOPT_POSTFIELDS and use just $xml, $data comes back as an empty string.
Any help will be appreciated.

If the server is expecting an XML POST, then passing an array to CURLOPT_POSTFIELDS is not going to make it happy.
Note in your original code the method of building the URL:
$params = array('oauth2_access_token' => $access_token);
$resource = "https://api.linkedin.com/v1/people/~/following/companies?" . http_build_query($params);
You'll want to keep that. http_build_query() performs the escaping needed if your access token contains special characters.
I'd have questions whether or not your access token is valid, given the original code seems to dynamically generate it with $datapass->access_token_get();
Otherwise it looks like you have everything set the same.
<?php
$access_token = "long_string_of_characters";
$nCompanyID = 2495437;
$xml = "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><company><id>$nCompanyID</id></company>";
$params = ["oauth2_access_token" => $access_token];
$url = "https://api.linkedin.com/v1/people/~/following/companies?";
$url .= http_build_query($params);
$headers = [
"Content-type: text/xml",
"Content-length: " . strlen($xml)
];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $xml,
CURLOPT_HTTPHEADER => $headers,
]);
$data = curl_exec($ch);

Related

Convert Rest API call from PHP to RUBY

Im trying to convert a post connection to the walmart api, from php to ruby, this is the php version
$client_id = $data['client_id'];
$client_secret = $data['client_secret'];
$url = "https://marketplace.walmartapis.com/v3/token";
$uniqid = uniqid();
$authorization_key = base64_encode($client_id.":".$client_secret);
$code = "";
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_HEADER => false,
CURLOPT_POST =>1,
CURLOPT_POSTFIELDS => "grant_type=client_credentials",
CURLOPT_HTTPHEADER => array(
"WM_SVC.NAME: Walmart Marketplace",
"WM_QOS.CORRELATION_ID: $uniqid",
"Authorization: Basic $authorization_key",
"Accept: application/json",
"Content-Type: application/x-www-form-urlencoded",
),
);
curl_setopt_array($ch,$options);
$response = curl_exec($ch);
$code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
and this is what i have so far:
url = "https://marketplace.walmartapis.com/v3/token/"
uniqid = "1234567890a1b"
uri = URI.parse(url)
request = Net::HTTP::Post.new(uri)
request["WM_SVC.NAME"] = "Walmart Marketplace"
request["WM_QOS.CORRELATION_ID"] = uniqid
request.basic_auth(client_id, client_secret)
request["Accept"] = "application/json"
request.content_type = "application/x-www-form-urlencoded"
request["WM_SVC.VERSION"] = "1.0.0"
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts "error " + response.code
puts response.body
Now, im getting a 400 error, so something of the data im sending is incorrect or missing... comparing both, i dont have set the postfields option on ruby, for the POST request, not sure if the rest is required as well... any ideas?
Try adding this line:
request.body = 'grant_type=client_credentials'

Trouble with POST API using cURL

I'm trying to post to an API using cURL with no luck. I've been researching this for 2-days now and I can't seem to get it to work.
Here is an example of a URL that I can paste into a web browser and it works, no problem:
http://{myserver}:{port}/api.aspx?Action=AddTicket&Key=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx&Subject=Test&Description=Test&Username={domain}\{username}
(I obviously redacted some information).
I know that cURL is up to date and working on the server because I can make a simple request out to [http://www.google.com] and it returns the page properly and I've also confirmed it on the php.info page as being ENABLED.
I've tried every layout I can find for the cURL code such as settings the POSTFIELDS as an array as well as a string. I've followed along with multiple YouTube videos and web tutorials to the 'T' with no success. I've even tried setting the URL parameter in the $ch to the entire above URL just for the heck of it... No success.
Can anyone explain or give examples of how this should be formatted so that it simply posts a URL identical to the one above??
Much appreciated!
As requested, here's my code.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = '&key=' . $key . '&subject=' . $subject . '&description=' . $details . '&username={domain}\{username}';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
And here is my attempt using an array instead of a string for the POSTFIELDS.
$url = 'http://{server}:{port}/api.aspx?Action=AddTicket';
$post_data = array(
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
$output = curl_exec($ch);
if ($output === false) {
echo "cURL Error: " . curl_error($ch);
}
curl_close($ch);
print_r($output);
EDIT
I've tried some of the examples given in the comments. Here's a small test I'm currently running.
$data = array(
'Action' => 'AddTicket',
'Key' => 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
'Subject' => 'test',
'Description' => 'test',
'Username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{server}:{port}/api.aspx?' . $query;
print_r($url);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_URL => $url
));
$resp = curl_exec($curl);
curl_close($curl);
Now, if I straight up take the $url variable from the above code and run this...
header("Location:" . $url);
die();
It works perfectly... so my problem has to be something in the cURL syntax or parameters...
EDIT
After adding the following code...
var_dump($resp);
var_dump(curl_getinfo($curl, CURLINFO_HTTP_CODE));
var_dump(curl_error($curl));
I get the following result...
string(0) ""
int(401)
string(0) ""
Anyone know what this means?
Your working example indicates that this is not a POST request at all, but instead a GET request.
Try building your URL like so:
$data = array(
'Action' => 'AddTicket',
'key' => $key,
'subject' => $subject,
'description' => $details,
'username' => '{domain}\{username}'
);
$query = http_build_query($data);
$url = 'http://{myserver}:{port}/api.aspx?' . $query;
Then you probably only need to perform a GET request to that URL.
Edit: Seeing your latest update, try using json_encode on your postfields.
The URL you're supplying uses GET parameters. Hopefully the below snippet should help;
$curl = curl_init();
// Heres our POSTFIELDS
$params = array(
'param1' => 'blah1',
'param2' => 'blah2'
);
$params_json = json_encode($params);
curl_setopt_array($curl, array(
CURLOPT_URL => 'http://example.com',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_HTTPAUTH => CURLAUTH_ANY,
CURLOPT_POSTFIELDS => $params_json
));
$response = curl_exec($curl);
$error = curl_error($curl);
curl_close($curl);

Make a web service call in 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);

Why does stream_context_create successfully return data but not my Curl?

When I first started, I thought Curl would be an excellent way of retrieving a chunk of data in the format json. It didn't work. I tried doing some Ajax request instead, but that didn't work either.
Now, this is my Curl request:
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept' => 'application/json',
'Auth' => 'code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);
... The CURL requests RETURNS a EMPTY STRING. No errors...
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: application/json\r\n" . "Auth: code",
)
);
$context = stream_context_create($opts);
$url = "";
$fp = fopen($url, 'r', false, $context);
$r = #stream_get_contents($fp);
fclose($fp);
print_r($r);
Provides a nice array with json data. Why? Isn't this literally supposed to do the same thing?
Because CURLOPT_HTTPHEADER doesn't take associated arrays. You need to add the complete header.
$ch = curl_init("url");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Auth: code',
));
$data = curl_exec($ch);
curl_close($ch);
print_r($data);

file_get_contents not working for fetching data from facebook using batch requests

file_get_contents not working for fetching fata from facebook using batch requests.Am using the code below:
$url='https://graph.facebook.com/?batch=[{ "method": "POST", "relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]& access_token=xxxxxxx&method=post';
echo $post = file_get_contents($url,true);
it produces
Warning: file_get_contents(graph.facebook.com/?batch=[{ "method": "POST", "relative_url": "method/fql.query?query=SELECT+first_name+from+user+where+uid=12345"}]&access_to‌ ​ken=xxxx&method=post): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/user/workspace/fslo/test.php on line 9
I would say the most likely answer to this is that you need to pass the URL values through urlencode() - particularly the JSON string.
Also, you should be POSTing the data.
Try this code:
NB: I presume you are building the URL from several variables. If you edit the question with your actual code, I will provide a solution using that code
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_to‌ken' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
. "Content-Length: ".strlen($requestBody)."\r\n"
. "Connection: close\r\n",
'content' => $requestBody
)
);
$context = stream_context_create($opts);
$result = file_get_contents($baseURL, FALSE, $context);
A "more standard" way to do this these days is with cURL:
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_to‌ken' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($requestBody),
'Connection: close'
));
$post = curl_exec($ch);

Categories