I'm finally able to get an Access Token, now I'm very confused as how to add a Calendar using only Google's provided apiClient.
$apiClient = SiteController::getApiClient();
$service = new apiCalendarService($apiClient);
$calendar = new Calendar();
$calendar->description = "What";
$service->calendars->insert($calendar);
This produces:
Error calling POST https://www.googleapis.com/calendar/v3/calendars?key=mykey: (400) Required
Is there some documentation/examples on adding a Calendar? There are a ton of examples, it seems like, for simply adding an Event.
I'm a little closer now, I get
apiServiceException
Error calling POST
https://www.googleapis.com/calendar/v3/users/me/calendarList?key=mykey: (404) Not Found
Using the boilerplate code they gave on the documentation
$calendarListEntry = new CalendarListEntry();
$calendarListEntry->setId("calendarId");
$createdCalendarListEntry = $service->calendarList->insert($calendarListEntry);
echo $createdCalendarListEntry->getSummary();
Inserting a new calendarEntry in google calendar API v3 returns a 404
How do I change my request URL from
https://www.googleapis.com/calendar/v3/users/me/calendarList?key=mykey
to
https://www.googleapis.com/calendar/v3/calendars
This worked:
// Create new calendar
$apiClient = SiteController::getApiClient();
$service = new apiCalendarService($apiClient);
$calendar = new Calendar();
$calendar->setSummary(Home::model()->count() . '-' . $model->name);
$createdCalendar = $service->calendars->insert($calendar);
You can reference Google Calendar API v1 Developers' Guide.
Related
I m trying to fetch share count of youtube video using YouTube Analytics API v3. I am using google php client library to upload videos. I am able to find count of likes, dislikes, etc using this url:
https://www.googleapis.com/youtube/v3/videos?part=statistics&id=Nyk_ltlr6pc&key={APP_KEY}
But not able to find any such resource to fetch count of share.
I have seen this post: How to get share count of a youtube video using youtube api?
But I am unable to get anything from this post, as this post is old and it is using YouTube Analytics API v1 compare to current YouTube Analytics API v3.
Kindly guide me. Thank you.
I know it's late, but still I think I should share the code, so if any need person looking for such functionality similar to this, it would help him.
set_include_path($_SERVER['DOCUMENT_ROOT'] . '/library/Youtube/src/');
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
session_start();
$startdate = <DATE_WHEN_YOUR_GET_UPLOADED>;
$video_id = <YOUR_VIDEO_ID>;
$video_id = "video==" .$video_id;
$key = file_get_contents('the_key.txt'); //YOUR_ACCESS_TOKEN
$OAUTH2_CLIENT_ID = <YOUR_OAUTH2_CLIENT_ID>;
$OAUTH2_CLIENT_SECRET = <YOUR_OAUTH2_CLIENT_SECRET>;
$scope = array("https://www.googleapis.com/auth/youtube.force-ssl", "https://www.googleapis.com/auth/youtubepartner-channel-audit", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.readonly", "https://www.googleapis.com/auth/yt-analytics.readonly", "https://www.googleapis.com/auth/yt-analytics-monetary.readonly","https://www.googleapis.com/auth/youtubepartner");
try{
// Client init
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
if ($client->getAccessToken()) {
//Check to see if our access token has expired. If so, get a new one and save it to file for future use.
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('the_key.txt', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_id = <YOUR_CHANNEL_ID>;
$ids = 'channel=='.$channel_id;
$end_date = date("Y-m-d"); //current date
$start_date = startdate; //date when you uploaded your video
$optparams = array(
'filters' => $video_id,
);
$metric = 'likes,shares'; //what you want to fetch
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
print_r(json_encode($api->rows[0]));
} else{
// #TODO Log error
echo 'Problems creating the client';
}
}catch (Google_Service_Exception $e) {
echo sprintf('<p>A service error occurred: <code>%s</code></p>',htmlspecialchars($e->getMessage()));
}
Kindly feel free to review my code and suggest any suitable changes.
I'm trying to display some basic Google Analytics information about my website using the Google Analytics Reporting API and Oauth 2.0. I've been trying to make it work for hours, but in vain.
I've copied and edited the code from this topic. Everything should work correctly, but somehow when I view the page in my browser, I only see a blank page.
I have:
Created a Service Account in the Google API Console.
Enabled the Google Analytics API in the Google API Console.
Added the e-mail address of the service account to Google Analytics.
The code ('XXXX' means I've filtered out personal information):
<?php
require_once 'google-api/src/Google/Client.php';
require_once 'google-api/src/Google/Service/Analytics.php';
$keyfile = 'XXXX.p12';
// Initialise the Google Client object
$client = new Google_Client();
$client->setApplicationName('Application Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'XXXX#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('XXXX.apps.googleusercontent.com');
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'XXXX';
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
?>
I've struggled with this for a very long time, any help would be greatly appreciated!
I am encountering a problem with my code when I am trying to retrieve events on the google calendar. Below is my code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Calendar PHP Starter Application");
// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('client id');
$client->setClientSecret('client secret');
$client->setRedirectUri('redirect uri');
$client->setDeveloperKey('developer key');
$cal = new Google_CalendarService($client);
$events = $cal->events->listEvents('email address for google calendar');
echo $events;
?>
When I print out the events of my google calendar, all I get is an empty array. However I am sure that I have several events in my google calendar.
In fact, I event tried to add an event by using the code below:
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-08-23T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-08-23T10:25:00.000-07:00');
$event->setEnd($end);
echo $events;
$createdEvent = $cal->events->insert('email address for google calendar', $event);
However, when I do this code I end up receiving an error that says:
Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/'email address for google calendar'/events?key='key'......................................lib/google-api-php-client/src/io/Google_REST.php on line 66
Can someone help me on this?
As it's an array you need to use print_r instead of echo. Try replacing:
echo $events;
with
print"<pre>".print_r($events, true)."</pre>";
I have a working script which is creating events in my google calendar - using google-api-php-client. I'm trying to add a gadget to each event it creates with the following code:
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_CalendarService.php";
define('CLIENT_ID', 'xxx...');
define('SERVICE_ACCOUNT_NAME', 'xxx...');
define('KEY_FILE', 'xxx...');
$client = new Google_Client();
$client->setApplicationName("WEB ACCTION");
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(SERVICE_ACCOUNT_NAME,'xxx...',$key));
$client->setClientId(CLIENT_ID);
$service = new Google_CalendarService($client);
$event = new Google_Event();
$event->setSummary($variable1);
$event->setLocation($variable2 . ", " . $variable3);
$start = new Google_EventDateTime();
$start->setDateTime(date(DATE_ATOM, strtotime($variable4) + $time_offset));
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime(date(DATE_ATOM, strtotime($variable5) + $time_offset));
$event->setEnd($end);
//The not working section
//$gadget = new Google_EventGadget();
//$gadget->setIconLink('xxx...');
//$gadget->setTitle('xxx...');
//$gadget->setHeight('xxx...');
//$gadget->setWidth('xxx...');
//$gadget->setLink('xxx...');
//$gadget->setType('xxx...');
//$gadget->setDisplay('xxx...');
//$event->setGadget($gadget);
$createdEvent = $service->events->insert($g_calendar , $event);
Unfortunately - I can not make it work and I was not able to find any information about creating the gadgets with google-api-php-client. The library includes a Google_EventGadget class and setGadget function but there is no information how to use ithem. Could anyone help me?
I have found the solution - it occures that the google-api-php-client supports only the certified links to the gadget and its icon. It didnĀ“t work until I used the https://www... links.
It works fine even though the hosting I used for tests has no security certificate.
$gadget->setIconLink('https://www...');
$gadget->setLink('https://www....');
$gadget->setDisplay('chip');
$gadget->setWidth('400');
$gadget->setHeight('100');
$event->setGadget($gadget);
$createdEvent = $service->events->insert($g_calendar , $event);
Hope it will save someone some time!
I'm trying to get some info of my Google Analytics account using PHP. I already followed the steps for creating a Service Account in the Google Console API in this answer. I'm using the Google API Client for PHP.
This is the code I've got so far:
<?php
$path_to_src = 'src';
// These files are in /src, upload its contents to your web server
require_once $path_to_src . '/Google_Client.php';
require_once $path_to_src . '/contrib/Google_AnalyticsService.php';
$path_to_keyfile = '***'; //my private key
// Initialise the Google Client object
$client = new Google_Client();
// Your 'Product name'
$client->setApplicationName('My App Name');
$client->setAssertionCredentials(
new Google_AssertionCredentials(
'**', //gserviceaccount mail
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents($path_to_keyfile)
)
);
// Get this from the Google Console, API Access page
$client->setClientId('***'); // my cliente ID
$client->setAccessType('offline_access');
$analytics = new Google_AnalyticsService($client);
// create service and get data
$service = new Google_AnalyticsService($client);
// We have finished setting up the connection,
// now get some data and output the number of visits this week.
// Your analytics profile id. (Admin -> Profile Settings -> Profile ID)
$analytics_id = 'ga:****'; // my profile id
$lastWeek = date('Y-m-d', strtotime('-1 week'));
$today = date('Y-m-d');
try {
$results = $analytics->data_ga->get($analytics_id,
$lastWeek,
$today,'ga:visits');
echo '<b>Number of visits this week:</b> ';
echo $results['totalsForAllResults']['ga:visits'];
} catch(Exception $e) {
echo 'There was an error : - ' . $e->getMessage();
}
I've enabled the openssl extension in PHP:
When browsing to the location of the php script, I just get a almost forever loading and the following error:
I'm using PHP 5.4.7:
After debuging the Google API Client code, it looks like the script is breaking at this line:
if (!openssl_sign($data, $signature, $this->privateKey, "sha256"))
Anything below this line does not get called. Looks like the error happens in this line. Is there a incompatibility here, or something?
One thing for starters you should change:
You instantiate the AnalyticsService twice. Take out the one you're not using:
$service = new Google_AnalyticsService($client);
See if that helps your problem at all.