Google Apps Calendar free/busy query POST with curl - php

I am trying to do a free/busy query on a Google Resource Calendar (Google Apps). The API documentation for Freebusy query gives these directions about the request:
HTTP Request:
POST https://www.googleapis.com/calendar/v3/freeBusy
Request Body Structure:
{ "timeMin": {datetime},
"timeMax": {datetime},
"items": [
{"id": {string}
}
]
}
Here's my attempt, using curl:
$url = "https://www.googleapis.com/calendar/v3/freeBusy";
global $headers; // holds ClientLogin authentification
$freebusy_post = array(
"timeMin" => '2012-12-31T00:00:00',
"timeMax" => '2013-01-08T23:00:00',
"timeZone" => 'America/New York',
/*** "items" below commented out because posting a multidimensional array returns an
"Array to string conversion" error. However, I think the API requires
"items" to be an array. ***/
//"items" => array(
// "id" => "https://www.googleapis.com/calendar/v3/calendars/gdev.wellesley.edu_313736333535343332#resource.calendar.google.com"
// )
/*** My attempt at using a plain string instead of an array ***/
"items" => "gdev.wellesley.edu_313736333535343332#resource.calendar.google.com",
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);
My problem: $data doesn't print anything.
I'm brand new to PHP, curl, and the Google Apps Calendar API. I'd love any help/ lessons/ advice you can offer!

Not sure, but you have probably to convert the php array to a json first.
$freebusyjson = json_encode($freebusy_post);

i started with your code and modified it and the following worked for me...
Note how i formatted the calendar ID in the item variable. I also only needed to attach an API key to the URL as it is a public calendar. I don't think I needed it initially, but then I reached the number of requests that could be made without using an API key.
Finally, note the format of the Time/Date. I'm saying this is the only way to do it, but it worked for me.
$url = "https://www.googleapis.com/calendar/v3/freeBusy/?key=MY_API_KEY";
$freebusy_post = array(
"timeMin" => '2016-11-01T00:00:00.000Z',
"timeMax" => '2016-12-21T00:00:00.000Z',
"timeZone" => ' America/New York',
"items" => array(array('id'=>"mywebsite.com_randomlettershere#group.calendar.google.com")),
);
$freebusy_post = json_encode($freebusy_post);
$ch = curl_init();curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $freebusy_post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
print_r($data);

Related

Why isn't my XML API request accepted by the API?

I have been trying, for days, to send a simple XML request to an API. Even with the help of the tech support, absolutely nothing works. I still get an error telling me that my XML isn't well-formed or is invalid.
Here is my cURL request:
$data = array_merge([
'ssl_transaction_type' => "$transactionType",
'ssl_merchant_id' => $this->merchant_id,
'ssl_user_id' => $this->user_id,
'ssl_pin' => $this->pin
], $data);
$xml = new \SimpleXMLElement('<txn/>');
$data = array_flip($data);
array_walk_recursive($data, array ($xml, 'addChild'));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->getXMLUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/x-www-form-urlencoded'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array("xmldata=" . explode(PHP_EOL, $xml->asXML())[1])));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
$response = curl_exec($ch);
Why do I explode the XML? It's because I need to only get the part with the root, not the version, etc. according to the tech support.
I followed this: XML request is not well-formed or request is incomplete but it still doesn't work.

Not getting individual data using curl

i am trying to get indivdual data using curl from this website http://dummy.restapiexample.com/ .. I use the following code to get all data
<?php
$url='http://dummy.restapiexample.com/api/v1/employees';
$my_curl = curl_init();
curl_setopt($my_curl, CURLOPT_URL, $url);
curl_setopt($my_curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($my_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($my_curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($my_curl, CURLOPT_SSL_VERIFYPEER, 0);
$my_data = curl_exec($my_curl);
$my_json = json_decode($my_data);
echo '<pre>'; print_r($my_json ); echo '</pre>';
?>
1) This is working . But i want to get the indvidual data , so i tried to chage url and use the same code
$url="http://dummy.restapiexample.com/api/v1/employee/1"
But it is not working .
2) Also i try to create a new record , that is working
$data = array("name" => "Hagridbo", "salary" => "123", "age" => "36");
$data_string = json_encode($data);
$ch = curl_init('http://dummy.restapiexample.com/api/v1/create');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
But how can i get the response like data is inserted ? what data is inserted ?
1. Regarding individual employee data is not coming
If you look to the http://dummy.restapiexample.com/api/v1/employees, you will see that employee id 1 is not there. That's why you are not getting any data.
for example check data of this link:- http://dummy.restapiexample.com/api/v1/employee/20276
Also it seems that v1/employees API data changing on a regular interval.
2. Regarding created an employee successfully, but not getting any response.
do var_dump($result); after $result = curl_exec($ch);and see what it give you. I think it will give you a json data response of added user.
I said it based on details of that API link, check here: http://dummy.restapiexample.com/create

Twitch API - can't get auth token using PHP

Hello stackoverflow members.
I'm not a person who likes to ask for a help but in this case it's IMO the only way to solve my problem. Google didn't help me much.
So. My problem:
I want to get some data using Twitch API. Sounds easy? I wish it was. Below I'm posting my actual code (it's small but it was modified various of times and now it look like...):
$user = json_decode(file_get_contents('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=MY_CORRECT_CLIENT_ID&redirect_uri=http://localhost/php/twitch.php&scope=user_read'), true);
print_r($user); // returns nothing
$token = $user['access_token'];
print_r($token); // same as above
$ch = curl_init();
// some stupid curls
curl_setopt($ch, CURLOPT_URL, 'https://api.twitch.tv/kraken/streams/followed');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, 'Authorization: OAuth '.$token );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$retval = curl_exec($ch);
curl_close($ch);
$result = json_decode($retval, true);
It returns... Nothing. So I used ready solution from discussions.twitch. (I wish I could write the name of the author of this code but I'm too tired to search it again. Either way thanks!):
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
$response = json_decode($data, true);
//var_dump($response);
$access_token = $response["access_token"];
echo $access_token;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$returnobj = curl_exec($ch);
curl_close($ch);
return $returnobj;
}
$testobj = json_decode(get_data("https://api.twitch.tv/kraken/user?oauth_token=".$access_token."&client_id=".$fields['client_id']));
echo "<br>Data: ";
print_r($testobj);
This code above is a bit better. Only a bit. It returns Error 401. Why? Because it can't get auth token. Well, it's something but not what I wanted to get. What should I do now? Maybe it's fault of localhost address?
FAQ(?):
Yes, I'm using correct data from my Twitch application settings page.
Yes, I'm confused
You're making two calls to the Twitch API, and you need to debug them independently.
For now, just skip the second call. Focus on the one where you grab your access token.
Try this:
// to start, just use the code you've already got:
$ch = curl_init("https://api.twitch.tv/kraken/oauth2/token");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$fields = array(
'client_id' => 'blablabla_correct',
'client_secret' => 'blablabla_also_correct',
'grant_type' => 'authorization_code',
'redirect_uri' => 'http://localhost/php/twitch.php',
'code' => $_GET['code']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$data = curl_exec($ch);
// Now, here we believe the first error comes into play, so let's check it out
print_r($data); // confirm that this is not what we want
$info = curl_getinfo($ch); // let's get some details about that last request
// print it out and see what we get
echo '<pre>';
print_r($info);
echo '</pre>';
... that should give you a starting point to figure out what's going on. If you see an auth token, then you're not accessing it in the right way. If you don't, the info will give you some information about why.
I don't know what redirect_uri is (can you link to docs that explain it?) so I can't know if the localhost reference is a problem there.

How do I make a POST using X-HTTP-Method-Override with a PHP curl request?

I'm working with the Google Translate API and there's the possibility that I could be sending in quite a bit of text to be translated. In this scenerio Google recommends to do the following:
You can also use POST to invoke the API if you want to send more data
in a single request. The q parameter in the POST body must be less
than 5K characters. To use POST, you must use the
X-HTTP-Method-Override header to tell the Translate API to treat the
request as a GET (use X-HTTP-Method-Override: GET). Google Translate API Documentation
I know how to make a normal POST request with CURL:
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);
curl_close($curl);
echo $response;
But how do I modify the header to use the X-HTTP-Method-Override?
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET') );
http://php.net/manual/en/function.curl-setopt.php
CURLOPT_HTTPHEADER
An array of HTTP header fields to set, in the format array('Content-type: text/plain', 'Content-length: 100')
Thus,
curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: GET'));
use the CURLOPT_HTTPHEADER option to add a header from a string array
Not enough for me , i need to use http_build_query fo my array post data
my full example :
$param = array(
'key' => 'YOUR_API_KEY_HERE',
'target' => 'en',
'source' => 'fr',
"q" => 'text to translate'
);
$formData = http_build_query($param);
$headers = array( "X-HTTP-Method-Override: GET");
$ch=curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$formData);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers );
curl_setopt($ch, CURLOPT_REFERER, 'http://yoursite'); //if you have refere domain restriction for your google API KEY
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,'https://www.googleapis.com/language/translate/v2');
$query = curl_exec($ch);
$info = curl_getInfo($ch);
$error = curl_error($ch);
$data = json_decode($query,true);
if (!is_array($data) || !array_key_exists('data', $data)) {
throw new Exception('Unable to find data key');
}
if (!array_key_exists('translations', $data['data'])) {
throw new Exception('Unable to find translations key');
}
if (!is_array($data['data']['translations'])) {
throw new Exception('Expected array for translations');
}
foreach ($data['data']['translations'] as $translation) {
echo $translation['translatedText'];
}
I found this help here https://phpfreelancedeveloper.wordpress.com/2012/06/11/translating-text-using-the-google-translate-api-and-php-json-and-curl/
Hope that helps

(cURL / PHP) API Response - Invalid HTTP method used

Hopefully a simple question, I have tried to connect to my first REST API using PHP and cURL. My code is as follows:
<?php
$zooplaKey = "mykey";
$postcode = $_GET['postcode'];
$sendData = array('api_key' => $zooplaKey,
'postcode' => $postcode,
'output_type' => "postcode");
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, 'http://api.zoopla.co.uk/api/v1/average_area_sold_price.js');
curl_setopt($curl, CURLOPT_POSTFIELDS, $sendData);
//curl_setopt($curl, CURLOPT_POST, true);
//curl_setopt($curl, CURLOPT_HTTPGET, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$raw_json = curl_exec($curl);
curl_close($curl);
$zooplaInfo = json_decode($raw_json, true);
echo "<pre>";
print_r($zooplaInfo);
echo "</pre>";
?>
Run exactly as above I get a return of:
Array
(
[error_string] => Invalid HTTP method used
[error_code] => 2
)
Uncommenting //curl_setopt($curl, CURLOPT_POST, true); or //curl_setopt($curl, CURLOPT_HTTPGET, true); just returns a blank screen.
By using the following URL I am able to get a valid result (obviously I have had to blank the api key so this link is for structure purposes only) http://api.zoopla.co.uk/api/v1/average_area_sold_price.xml?api_key=mykey&postcode=ws12dn&output_type=postcode
Thanks all.
According to the Zoopla API Documentation, what you are trying to do is to:
Retrieve the average sale price for houses in a particular area.
Retrieval is done using a GET method in the REST standard. By using CURLOPT_POSTFIELDS, cURL will automatically convert your request to a POST, which is invalid for retrieval. You should remove the post fields part, and do that instead:
curl_setopt($curl, CURLOPT_URL, 'http://full/url?'.http_build_query($sendData));
The parameters in the URL are being passed as GET. I would try appending the parameters to the CURLOPT_URL instead of putting them in the CURLOPT_POSTFIELDS array. The remote service probably requires the values be in the query string rather than being posted.

Categories