Unable to delete events in Google Calendar using php api - php

I am working on the PHP API to Google Calendar, I have previously used the Zend library and I am upgrading to the API V3 I downloaded the Git Hub client library v1.0.
I have completed oAuth 2 and I am storing Refresh tokens in a database. I can connect and write events to Google Calendar, thanks mainly to the contributors at StackOverflow. Thanks
My problem is that I cannot delete events. I am connecting with oAuth 2 and retrieving event Ids however
$service->events->delete('primary', $event->getId());
This generates Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: '0'' in C:\wamp\www\new-roster-decoder\src\Google\IO\Stream.php on line 128
I have hunted high and low and been unable to find a solution. Please help Thanks
EDITED AS SOLVED
Due to Emily's great advice this is solved
Solution downloaded the latest API from GitHub as the problem of GZIP has been sorted.
As a matter of interest I initially commented out GZIP in congig.php and this fixed it, but I then lost the performance benefits, then new library sorted it.
Lessons learnt. Stackoverflow users are very kind to give their time, and always try the lastest software
END OF EDIT
<?php
/// This works
session_start();
set_include_path("src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
require_once 'account/dbc.php';
$client_id = 'XXXXXXXXXX.apps.googleusercontent.com';
$client_secret = 'XXXXXXXXXXX';
$redirect_uri = 'http://localhost:80/new-roster-decoder/account/GoogleoAuth.php';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->setAccessType('offline');
$users_rs_settings = mysqli_query($link,"select * from users WHERE id = 118");
$users_array = mysqli_fetch_array($users_rs_settings);
$refresh_token = $users_array['refresh_token']; //2010-04-06
$client->refreshToken($refresh_token);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Positioning TX');
$event->setLocation('BRS-LGW');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2014-02-19T14:00:00.000-00:00');
$start->setTimeZone('Europe/London');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2014-02-19T17:25:00.000-00:00');
$end->setTimeZone('Europe/London');
$event->setEnd($end);
// insert ext properties
$rdname = "RosterDecoderID";
$rdvalue = 1;
$extendedProperties = New Google_Service_Calendar_EventExtendedProperties();
$extendedProperties->setPrivate(array($rdname=>$rdvalue));
$event->setExtendedProperties($extendedProperties);
// end of insert ext properties
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId()."\n\n";
$_SESSION['access_token'] = $client->getAccessToken();
var_dump($_SESSION['access_token']);
var_dump($event);
$minCheck = date(DATE_ATOM, mktime(0, 0, 0, date("m"), date("d"), date("Y") ));
$maxCheck = date(DATE_ATOM, mktime(0, 0, 0, date("m"), (date("d")+1), date("Y") ));
$optParams = array( 'privateExtendedProperty' => 'RosterDecoderID=1','timeMin' => $minCheck, 'timeMax' => $maxCheck);
$events = $service->events->listEvents('primary', $optParams);
while(true) {
foreach ($events->getItems() as $event) {
$eventID = $event->getId();
//////////////////////////////////////////////////////////
//This bit throws an error
$service->events->delete('primary', $event->getId());
/////////////////////////////////////////////////////////
// The error is
// Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect: '0'' in C:\wamp\www\new-roster-decoder\src\Google\IO\Stream.php on line 128
echo $event->getSummary();
echo $event->getId()."\n\n";
}
}
?>

I am able to delete event from google calendar..
use private key file you get from developer console.
Fore more info check this link
What is the Google API password for the OAuth PKCS p12 private key?
how-where-to-obtain-a-p12-key-file-from-the-google-developers-console
below is code please check
const KEY_FILE = '<<some location on server>>/xxx-65454f656a-xxx-560265d-privatekey.p12';
// this is my private key file location, make sure it accessible
try {
$key = file_get_contents(KEY_FILE);
$auth = new \Google_Auth_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/calendar'),
$key);
$auth->sub = $calendarId;
$client = new \Google_Client();
$client->setAssertionCredentials($auth);
$client->setApplicationName("Parabola V2");
$client->setClientId(CLIENT_ID);
$service = new \Google_Service_Calendar($client);
$service->events->delete($calendarId, $eventId);
} catch (\Exception $e) {
echo "Exception while deleting event :- ".$e->getMessage();
return null;
}

$service->events->delete('primary', $event->getId());
'primary' must be the calendar id
"myname#gmail.com" or "mhggf54gfh5#group.calendar.google.com"
thats how it work for me

Related

Updating Google Calendar - Fatal error: Call to undefined function dateTime()

I am trying to update Google Calendar using the PHP API. I have successfully been able to create Google Calendar Events and automatically get the ID for the event, but when I try and update the event, I get this error:
PHP Fatal error: Call to undefined function dateTime() in public_html/googleapi/calendarupdate.php on line 45. It is referring to the line:
$event->setStart.dateTime($startdatetime);
Here is my current PHP Code for the error:
<?php
header('Content-type: application/json');
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$clientemail = $_POST["clientemail"];
$privatekey = $_POST["privatekey"];
$useremail = $_POST["useremail"];
$calendarid = $_POST["calendarid"];
$client_email = $clientemail;
$private_key = file_get_contents($privatekey);
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = $useremail;
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new Google_Service_Calendar($client);
$event = $service->events->get($useremail, $calendarid);
$event->setSummary($summary);
$event->setLocation($location);
$event->setStart.dateTime($startdatetime);
$event->setStart.timeZone('America/Los_Angeles');
$event->setEnd.dateTime($enddatetime);
$event->setEnd.timeZone('America/Los_Angeles');
$event->setDescription($description);
$updatedEvent = $service->events->update($useremail, $event->getId(), $event);
echo json_encode($updatedEvent);
My PHP code is based off of Google's API Documentation found here.
Ok, I actually managed to figure it out. I just had to change the line:
$event->setStart.dateTime($startdatetime);
To This:
$event->start->setDateTime($startdatetime);
I do the same general thing for the end datetime, except where it says start, I just put end. Just tested it and it worked perfectly. The site that helped me out can be found here.

Getting 'Forbidden error' when trying to execute youtube analytic API

I am receiving an error message when trying to execute youtube analytics API.
A service error occurred: Error calling GET
https://www.googleapis.com/youtube/analytics/v1/reports?ids=channel%3D%3DUCaayLD9i5x4MmIoVZxXSv_g&start-date=2016-08-01&end-date=2016-08-07&metrics=views&dimensions=7DayTotals:
(403) Forbidden
Here is my code:
require_once __DIR__.'\google-api-php-client-1-master\src\Google\autoload.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Client.php';
require_once __DIR__.'\google-api-php-client-1-master\src\Google\Service\YouTube.php';
session_start();
$key = file_get_contents('mykey.json');
$OAUTH2_CLIENT_ID = 'xx-xx-xx';
$OAUTH2_CLIENT_SECRET = 'xxx';
$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");
$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('mykey.json', $client->getAccessToken());
}
$analytics = new Google_Service_YouTubeAnalytics($client);
$channel_url = 'UCaayLD9i5x4MmIoVZxXSv_g';
$ids = 'channel==' . $channel_url . '';
$end_date = '2016-08-07';
$start_date = '2016-08-01';
$optparams = array(
'dimensions' => '7DayTotals',
);
$metric = 'views';
$api = $analytics->reports->query($ids, $start_date, $end_date, $metric, $optparams);
echo '<pre>';print_r($api);die;
}
I have already enable 'youtube analytic API' and I get the access_token from here
What is wrong with my code ,Or do we need to do some more stuff to get rid from this?
Looking at your code, it seems that you are generating a new access token at the point you save it to file (invalidating the first one).
Try :
if($client->isAccessTokenExpired()) {
//refresh your access token if it's expired
$newToken = json_decode($client->getAccessToken());
$client->refreshToken($newToken->refresh_token);
file_put_contents('mykey.json', $newToken);
}

Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'

i'm tring to migrate my google calendar access from Zend to new google API since they closed the service in november. My web app uses google api to create some events.
I'm facing a recurring message that i could not resolve : Uncaught exception 'Google_Auth_Exception' with message 'Invalid code'
Here's my code :
define('STDIN',fopen("php://stdin","r"));
require_once '../../utils/google-api-php-client-master/autoload.php';
/**********************
OAUTH 2.0 AUTHORIZATION
***********************/
$client = new Google_Client();
// OAuth2 client ID and secret can be found in the Google Developers Console.
$client->setClientId('XXXXXX);
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
$client->addScope('https://www.googleapis.com/auth/calendar');
$service = new Google_Service_Calendar($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:";
echo(trim(fgets(STDIN)));
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Could someone please help me ?
I finally got this stuff to start working myself and a lot of searching. I was also using Zend before. There is a very good website at Daimto.com where you can see a bunch of tutorials. Here is the code that worked for me to add an event using the code form Daimto.com and adding code for adding an event in the body. Remember you need ot have the service email added to the share of your google calendar too!
<?php
session_start();
require_once './google-api-php-client/src/Google/Client.php';
require_once './google-api-php-client/src/Google/Service/Calendar.php';
$client_id = '6846057_YOUR_CLIENT_ID_HERE_pg3q8r6.apps.googleusercontent.com';
$Email_address = '68460_YOUR_SERVICE_EMAIL_HERE_developer.gserviceaccount.com';
$key_file_location = '_KEY_FILE_LOCATION_HERE_8.p12';
$client = new Google_Client();
$client->setApplicationName("_APP_NAME_HERE_");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar";
$cred = new Google_Auth_AssertionCredentials(
$Email_address,
array($scopes),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Calendar($client);
?>
<html><body>
<?php
//$service = new Google_Service_Calendar($client);
//
$event = new Google_Service_Calendar_Event();
$event->setSummary('Event 2');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-06-22T19:00:00.000+01:00');
$start->setTimeZone('Europe/London');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-06-22T19:25:00.000+01:00');
$end->setTimeZone('Europe/London');
$event->setEnd($end);
//
$calendar_id = "nm_GOOGLE_CAL_ID_HERE_#group.calendar.google.com";
//
$new_event = null;
//
try {
$new_event = $service->events->insert($calendar_id, $event);
//
$new_event_id= $new_event->getId();
} catch (Google_ServiceException $e) {
syslog(LOG_ERR, $e->getMessage());
}
//
$event = $service->events->get($calendar_id, $new_event->getId());
//
if ($event != null) {
echo "Inserted:";
echo "EventID=".$event->getId();
echo "Summary=".$event->getSummary();
echo "Status=".$event->getStatus();
}
?>

Google Calendar API v3 PHP -> Trying to create new events into a single calendar

Basic rundown: I've written a client side calendar that allows people to schedule an appointment and reserve a timeslot (e.g. reservations are logged in a database and a second person can't choose the same time slot) for ease of syndication and printing of these appointments at the provider side they've requested that I push these events to a single google calendar. I've created a google account and a calendar for it, then created API key with access to the Calendar API under this same google user. So I want my website to use this user's credentials every time to create the events. It seems like this would be a "service account", however that doesn't seem to have access to user data, not even the user that created the application.
Any ideas on how to pull this off? If seems like it should be shockingly simple and that there's no way I'm the first person to want to do something like this, but damned if I can find any examples of it.
Here's a snippet of the code
$event = new Google_Event();
$event->setSummary($title);
$event->setLocation($location);
$start = new Google_EventDateTime();
$start->setDateTime($date . 'T' . $startTime . ':00.000-06:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime($date . 'T' . $endTime . ':00.000-06:00');
$event->setEnd($end);
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail($email);
$attendees = array($attendee1);
$event->attendees = $attendees;
$client = new Google_Client();
$service = new Google_CalendarService($client);
$createdEvent = $service->events->insert('my calendar ID', $event);
and the error
Uncaught exception 'Google_ServiceException' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/projecthimcal#gmail.com/events?key=AIzaSyAfSCfLJCMSkGRmjZXRtChPPcMNmEuCZow: (401) Login Required' in /home/mydomain.com/wp-content/themes/mytheme/libs/gAPI/io/Google_REST.php:66
Maybe it is a bit too late... but you have to setup an authentification.
Here is the code I used for mine, hope it can helps people still looking for this (Note that I used the api PHP client the class name may differ from yours but the logic is still the same):
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.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->setClientSecret('');
$client->setRedirectUri('');
$client->setDeveloperKey('');
$client->setScopes(array(
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly'
));
$cal = new Google_Service_Calendar($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Service_Calendar_Event();
$event->setSummary($title);
$event->setLocation($location);
$start = new Google_Service_Calendar_EventDateTime();
$start->setTimeZone('America/Montreal');
$start->setDateTime($date . 'T' . $startTime . ':00.000-06:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setTimeZone('America/Montreal');
$end->setDateTime($date . 'T' . $endTime . ':00.000-06:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($email);
$attendees = array($attendee1);
$event->attendees = $attendees;
$cal->events->insert($email, $event);
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect me!</a>";
}

Google Calendar API v3 - Google_AuthException - Could not json decode the token issue

I've searched this Group, plus others, along with other websites and cannot find a solution to this. Error output is below. I definitely know that setAccessToken should NOT be NULL. Any guidance would be great here. the Google Calendar v3 API documentation is not so great...in fact, the samples are for older API versions.
PHP Fatal error: Uncaught exception 'Google_AuthException' with message 'Could not json decode the token' in google-api-php-client/src/auth/Google_OAuth2.php:162
Stack trace:
0 google-api-php-client/src/Google_Client.php(170): Google_OAuth2->setAccessToken(NULL)
1 Cal.php(16): Google_Client->setAccessToken(true)
2 {main}
thrown in google-api-php-client/src/auth/Google_OAuth2.php on line 162
Below is the code for my app:
<?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();
$service = new Google_CalendarService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
} else {
$client->setAccessToken($client->authenticate($_GET['code']));
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$event = new Google_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_EventDateTime();
$start->setDateTime('2013-10-05T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2013-10-05T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_EventAttendee();
$attendee1->setEmail('my#email.com');
// ...
$attendees = array($attendee1);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
} else {
echo "failed hard";
}
?>
ClientID, Key, etc are kept in my google-api-php-client/src/config.php file
I haven't reviewed the api docs in a while but I use something like the following to configure the client. Maybe it will help.
$certFile = file_get_contents('/path/to/cert.p12');
$client = new Google_Client();
$client->setApplicationName('My App');
$client->setClientId($clientId);
$client->setScopes([
'https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/calendar.readonly',
]);
if ($token = $_SESSION['google.calendar.token']) {
$client->setAccessToken($token);
}
$credentials = new Google_AssertionCredentials($service_email, $client->getScopes(), $certFile);
$client->setAssertionCredentials($credentials);
$service = new Google_CalendarService($client);

Categories