Uncaught exception 'Google_Auth_Exception' with message 'Invalid code' - php

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();
}
?>

Related

Google API error

I am trying to use google API to get events off calendars on an account. I am using a service account. I am receiving two errors when I attempt to manually echo the code or it will remain a blank page if I use foreach(...).
Here are the two errors:
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found' in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
( ! ) Google_Service_Exception: Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList/primary: (404) Not Found in C:\wamp\www\newOLP\scripts\oAuth2\Google\Http\REST.php on line 110
Here is my code:
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = $jsonDecode['client_id'];
$Email_address = $jsonDecode['client_email'];
$key_file_location = 'privateKey.p12';
$client = new Google_Client();
$client->setApplicationName("CalCon");
$key = file_get_contents($key_file_location);
// separate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.readonly";
$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
$calendarList = $service->calendarList->listCalendarList();
echo $service->calendars->get('primary')->getSummary()."<br />";
echo $service->calendarList->get('primary')->getSummary();
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry;
echo "hi";
echo $calendarListEntry->getSummary()."<br>\n";
// get events
$events = $service->events->listEvents($calendarListEntry->id);
foreach ($events->getItems() as $event) {
echo "-----".$event->getSummary()."<br>";
}
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
?>
</body></html>

Google Calendar API inserting event

So, I downloaded this API library https://github.com/google/google-api-php-client.git
And installed it on server, then set up very simple script to add an event to my google calendar, first part of script makes sure your connection is good, second part tries to add event. So, connection is good, but adding event is not.. it gives me back
`Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars/primary/events: (403) Insufficient Permission'`
here is the script, can someone help?
<?php
session_start();
require '../google-api-php-client-master/src/Google/autoload.php';
require_once '../google-api-php-client-master/src/Google/Client.php';
require_once '../google-api-php-client-master/src/Google/Service/Calendar.php';
$client_id = '574154490008-l55646vdpf62f7nrim9dodhtg6ssv4qv.apps.googleusercontent.com';
$Email_address = '574154490008-l55646vdpf62f7nrim9dodhtg6ssv4qv#developer.gserviceaccount.com';
$key_file_location = 'someproject-9e09f9db466c.p12';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/calendar.readonly";
$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
$calendarList = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
foreach ($calendarList->getItems() as $calendarListEntry) {
echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>\n";
}
$pageToken = $calendarList->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$calendarList = $service->calendarList->listCalendarList($optParams);
} else {
break;
}
}
//--------------- trying to insert EVENT
$event = new Google_Service_Calendar_Event();
$event->setSummary('Appointment');
$event->setLocation('Somewhere');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-04-16T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-04-16T10:25:00.000-07:00');
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail('some#gmail.com');
// ...
$attendees = array($attendee1
//, ...
);
$event->attendees = $attendees;
$createdEvent = $service->events->insert('primary', $event);
echo $createdEvent->getId();
?>
</html>
Ok, So I just edited this line $scopes ="https://www.googleapis.com/auth/calendar"; I deleted ".readonly" so now I am getting eventId back as if I was inserting events successfully, but events are not showing up in the calendar.
You need share the calendar with your service account!
In the field e-mail put your e-mail (service account), that means like:
914304219907-rt42vptejtgg9fhb9btthdb2gbuctonp#developer.gserviceaccount.com

Events added through Google API PHP client not showing in Calendar

I'm using Google API PHP client to add events to my calendar. ID is returned successfully after the insert & When I fetch that event using the ID it displays summary & everything correctly & for some reason , the event is showing up in my calendar
I'm using Service Account Credentials. Is there something to be enabled to get this working?
Here's my Code
session_start();
require dirname(__FILE__).'/google-api-php-client-master/autoload.php';
$client_id = '<client ID>';
$service_account_name = '<Service Account Name>';
$key_file_location = dirname(__FILE__).'/API-Project-96c2a9122085.p12';
if (!strlen($service_account_name) || !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Calendar($client);
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials($service_account_name,array('https://www.googleapis.com/auth/calendar'),$key);
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$event = new Google_Service_Calendar_Event();
$event->setSummary("WHY IS THIS NOT WOKING?");
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime(date('Y-m-d\TH:i:s',strtotime('2014-12-24 10:00:00')));
$start->setTimeZone('Australia/Melbourne');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime(date('Y-m-d\TH:i:s',strtotime('2014-12-26 12:00:00')));
$end->setTimeZone('Australia/Melbourne');
$event->setEnd($end);
$newEvent = $service->events->insert('primary', $event);
$newEvent->getId();
$event = $service->events->get('primary', $newEvent->getId());
echo '<pre>'; print_r($event); echo '</pre>';
With the new Google_Client API, you need to share your calendar to yourself.
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType('user');
$scope->setValue( 'Your Email Goes Here' );
$rule = new Google_Service_Calendar_AclRule();
$rule->setRole( 'owner' );
$rule->setScope( $scope );
$result = $service->acl->insert('primary', $rule);
Let me know if you still have issue.

Unable to delete events in Google Calendar using php api

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

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