How to convert a Curl to PHP CURL - php-curl

I'm trying to convert this curl command into php:
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer API_TOKEN" \
-d '{"image": "ubuntu-16.04"}' \
https://api.hetzner.cloud/v1/servers/42/actions/rebuild
Can anyone help please?

You can use this tool to generate PHP-CURL using curl command parameters.
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.hetzner.cloud/v1/servers/42/actions/rebuild');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"image\": \"ubuntu-16.04\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: _ENV["Bearer API_TOKEN"];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Related

Vanilla API v2 Post Request (Curl) not working?

I'm trying to add a new user to my Vanilla forum and unfortunately I don't understand what's wrong with my code. GET request to read user data works fine butPOST requests result in a "bool(false)".
As I understand it, that's already a response from the API, which obviously can't do anything with my request, right?
But what's wrong with that? Do I have to somehow send the JSON data as a 'body'? Anyone have an idea? Thank you!!!
This is what my code currently looks like:
<?php
// post with absolute url = Invalid CSRF token error
// $url = "https://example.com/app/vanilla/api/v2/users";
$url = "/app/vanilla/api/v2/users";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
$headers = array(
"Accept: application/json",
"Authorization: Bearer {va.jOh189hry7463klur_kcw8UomJU36782.HGqvdQ.RQon456}"
);
$data = array(
'bypassSpam' => 'false',
'email' => 'info#mysite.de',
'emailConfirmed' => 'true',
'name' => 'Theo Tester',
'password' => '1234567890',
'photo' => '',
'roleID' => [33]
);
$payload = json_encode(array($data));
// Attach encoded JSON string to the POST fields
curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// Return response instead of outputting
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
This is what the vanilla API documentation looks like (please see picture below or link):
(https://success.vanillaforums.com/kb/articles/202-api-v2-reference-endpoints#/Users/post_users)
And this just for completeness is the code for GET requests as it works for me:
<?php
$url = "https://example.com/app/vanilla/api/v2/roles";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Accept: application/json",
"Authorization: Bearer {va.jOh189hry7463klur_kcw8UomJU36782.HGqvdQ.RQon456}",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>

Whatsapp Cloud Api get Media Object ID

I want to upload the media via Whatsapp cloud API in order to send the media to WhatsApp, I have followed the link below, but having the stated issue.
https://developers.facebook.com/docs/whatsapp/cloud-api/reference/media#get-media-id
Array ( [error] => Array ( [message] => (#100) The parameter messaging_product is required. [type] => OAuthException [code] => 100 [fbtrace_id] => AQPftb9Bf343375gQ_QytxNen ) ) 400
My Code is
// #1640191015925.jpg on my root folder
$post = [
'file' => '#1640191015925.jpg;type=image/jpeg',
'messaging_product' => 'whatsapp'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v13.0/Phone-Number-ID/media');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$headers = array();
$YOUR_WHATSAPP_ACCESS_TOKEN = '+++++++';
$headers[] = "Authorization: Bearer $YOUR_WHATSAPP_ACCESS_TOKEN";
$headers[] = "Content-Type: image/jpeg";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = json_decode(curl_exec($ch), true);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//$MEDIA_OBJECT_ID = $result['media'][0]['id']; //MEDIA OBJECT ID
print_r($result);
print_r($httpcode);
?> ```
I had the same issue, after some digging around I wrote this function to upload a file and return the id.
function waFileUploader($token, $file, $senderid){
$mime = mime_content_type($file);
$info = pathinfo($file);
$name = $info['basename'];
$curlfile = new CURLFile($file, $mime, $name);
$filedata = array("messaging_product"=>"whatsapp", "file" => $curlfile);
$url = 'https://graph.facebook.com/v13.0/' . $senderid . '/media';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,array("Authorization: Bearer $token", "Content-Type: multipart/form-data"));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $filedata);
$r = curl_exec($ch);
curl_close($ch);
$id = json_decode($r, true);
return $id["id"];
}

return error code : 401, No license found for the given deviceId

i have use this api
curl -X POST
https://tracking.api.here.com/v2/token
-H 'Authorization: Bearer {signedRequest}'
my php code is
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/timestamp');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$result = json_decode($result);
curl_close($ch);
$timestamp = ($result->timestamp);
$accessKey = $deviceId;
$secret = $deviceSecret;
$url = "https://account.api.here.com/oauth2/token";
$nonce = mt_rand(100000,999999);
$timestamp = $timestamp;
$baseString = "grant_type=client_credentials&oauth_consumer_key=".$accessKey."&oauth_nonce=".$nonce."&oauth_signature_method=HMAC-SHA256&oauth_timestamp=".$timestamp."&oauth_version=1.0";
$workingString = array();
foreach (explode('&', $baseString) as $parameter) {
$parameter = explode('=', $parameter);
$workingString[] = urlencode($parameter[0]).'='.trim(urlencode($parameter[1]));
}
$urlEncodeParamaterString = implode('&', $workingString);
$fullBaseString = "POST&".urlencode($url)."&".urlencode($urlEncodeParamaterString);
$hashKey = $secret.'&';
function encode($data) {
return str_replace(['+', '/'], ['-', '_'], base64_encode($data));
}
function decode($data) {
return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
}
$binaryKey = decode($hashKey);
$signature = encode(hash_hmac("sha256", $fullBaseString, $binaryKey, true));
$authHeader = "OAuth oauth_consumer_key=".$accessKey.",oauth_signature_method='HMAC-SHA256',oauth_timestamp='".$timestamp."',oauth_nonce=".$nonce.",oauth_version='1.0',oauth_signature=".$signature."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://tracking.api.here.com/v2/token');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
$headers[] = 'Authorization: '.$authHeader;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo '';
print_r($result);
output
{
code: 401,
id: "312f56e5-db4f-40f5-807f-c5a0413dd668",
message: "No license found for the given deviceId.",
error: "Timestamp wrong When the request timestamp has a more than 10 second difference from the server time, the x-here-timestamp header with the current server timestamp is added to the response. Incorrect Signature If the OAuth signature is incorrect, the response will be a 401 but without the x-here-timestamp field. "
}
In order to tracking a Device using HERE Tracking Service all you'll need to login and Create your Device ID First.
Please see below getting start documentation.
https://developer.here.com/documentation/tracking/dev_guide/topics/getting-started-1-creating-a-device-licence.html

using curl to get data from opendatacommunities.org

I want to use the API from opendatacommunities.org
the following code is used for the same. But I a get a "no acceptable resource available" message
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, https://epc.opendatacommunities.org/api/v1/domestic/search?address=liverpool");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0")
$headers = array();
$headers[] = "Accept: text/json";
$headers[] = "Authorization: Basic XXXXXXXXXXXXXXX";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch); }
curl_close ($ch);
Can any one help?
Hi i was able to fix it as the code
$headers[] = "Accept: text/json";
was replaced with
$headers[] = "Accept: application/json";
thank you for the help DhamankarTejas

shorte.st new api convert to php curl

shorte.st is a url shorten service.
recently they changed the api as following:
curl commandline
curl H "public-api-token: fakekey" -X -d "urlToShorten=google.com" PUT http://api.shorte.st/v1/data/url
response:
{"status":"ok","shortenedUrl":"http:\/\/sh.st\/XXXX"}
How to change it into php curl version?
function shst($url){
$apiurl="https://api.shorte.st/v1/data/url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $apiurl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('public-api-token: fakekey','X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, "urlToShorten=".$url);
$data = curl_exec($ch);
curl_close($ch);
$obj = json_decode($data);
$ret=$obj->{'shortenedUrl'};
return $ret;
}
The sample they provided used the wrong url. should be https not http
This works:
function shst($url){
$key="";//your key
$curl_url = "https://api.shorte.st/s/".$key."/".$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curl_url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$array = json_decode($result);
$shortest = $array->shortenedUrl;
return $shortest;
}