I have a PHP file that will create an event in my Google Calendar successfully from data Posted from my CRM, however, I can't find any documentation on how it can retreive the id of the event it just created and return a JSON data string.
Here is my current PHP file.
<?php
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"];
$client_email = 'xxxxxxxx#xxxxxxxx.iam.gserviceaccount.com';
$private_key = file_get_contents('xxxxxx.p12');
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = 'xxxxxxx#xxxxxxxxxxx.com';
$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();
}
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
$service = new Google_Service_Calendar($client);
$calendarId = 'southbay#unlikelylegendsmedia.com';
$event = $service->events->insert($calendarId, $event);
If you know the corresponding calendarID, you may use Events: list.
By sending HTTP request with the calendarId parameter, you can retrieve eventId. Request like:
GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events
If request is successful, this method may return a response body with either single one-off events and instances of recurring events.
Sample PHP code for this:
$events = $service->events->listEvents('primary');
while(true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
Related
Is it possible to have add/edit/delete events in Google Calendar?
Because all I have accomplished is just to read my events. I`m enabling all the "scopes" I can find about the Calendar API but still I get an error 403 about "Request had insufficient authentication scopes / PERMISSION DENIED".
I have done so many tries to fix that and everytime I get to the same point. I am using OAuth 2.0 Client IDs credentials and one more question I have is which url I should use for the Authorized redirect URIs.
<?php
require __DIR__ . '/vendor/autoload.php';
/*
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
*/
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage#example.com'),
array('email' => 'sbrin#example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
if (empty($events)) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($events as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
echo "<br>";
}
}
?>
I was able to create the event by using your same code with a minor edit. I modified the read-only scope to allow read/write access instead of read-only. This is the final result:
<?php
require __DIR__ . '/vendor/autoload.php';
/*
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
*/
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath))
{
$accessToken = json_decode(file_get_contents($tokenPath) , true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired())
{
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken())
{
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
}
else
{
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken))
{
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath)))
{
mkdir(dirname($tokenPath) , 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c') ,
);
$results = $service
->events
->listEvents($calendarId, $optParams);
$events = $results->getItems();
#--------------------------------------------------------------------------------------------
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
) ,
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
) ,
'attendees' => array(
array(
'email' => 'lpage#example.com'
) ,
array(
'email' => 'sbrin#example.com'
) ,
) ,
'reminders' => array(
'useDefault' => false,
'overrides' => array(
array(
'method' => 'email',
'minutes' => 24 * 60
) ,
array(
'method' => 'popup',
'minutes' => 10
) ,
) ,
) ,
));
$calendarId = 'primary';
$event = $service
->events
->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
#--------------------------------------------------------------------------------------------------------
if (empty($events))
{
print "No upcoming events found.\n";
}
else
{
print "Upcoming events:\n";
foreach ($events as $event)
{
$start = $event
->start->dateTime;
if (empty($start))
{
$start = $event
->start->date;
}
printf("%s (%s)\n", $event->getSummary() , $start);
echo "<br>";
}
}
?>
I am using JSON key file authorization for getting calendars list so i can enter new calendar event.
The problem is that at specific google account i am getting calendar list and when following same instruction on different google account the list is empty.
This is the code:
require_once 'vendor//autoload.php';
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credenential);
$client->useApplicationDefaultCredentials();
$client->setApplicationName("Quickstart");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
$startDateTime = DateTime::createFromFormat("Y-m-d H:i:s", $start);
$endDateTime = DateTime::createFromFormat("Y-m-d H:i:s", $end);
$event = new Google_Service_Calendar_Event(array(
'summary' => $title_event,
'location' => $where_event,
'description' => $content_event,
'start' => array(
'dateTime' => rawurldecode($start)
),
'end' => array(
'dateTime' => rawurldecode($end)
)
));
foreach($calendarList as $item) {
if ( strcasecmp( $item['summary'], $google_email ) == 0 ){
$calendarId = $item['id'];
}
}
$event = $service->events->insert($calendarId, $event);
In a laravel 5.8 project user can create new events using my app and then save those events to his google calendar via OAUTH 2 so that he can view, edit or even delete them. new conference data will be added automatically with each created event.
I want to view google meet link with each event created so that guests can click this link to attend the conference
I started by adding event data and creating new conference data and adding its entry point and using Google_Service_Calendar_ConferenceSolutionKey class to determine its type which is "hangoutsMeet" and finally I added conference data to the event
Here is the function I am using to create new events:
public function doCreateEvent(Event $evt, Request $request)
{
$this->validate($request, [
'title' => 'required',
'calendar_id' => 'required',
'datetime_start' => 'required|date',
'datetime_end' => 'required|date'
]);
$title = $request->input('title');
$calendar_id = $request->input('calendar_id');
$start = $request->input('datetime_start');
$end = $request->input('datetime_end');
$start_datetime = Carbon::createFromFormat('Y/m/d H:i', $start);
$end_datetime = Carbon::createFromFormat('Y/m/d H:i', $end);
$cal = new \Google_Service_Calendar($this->client);
$event = new \Google_Service_Calendar_Event();
$event->setSummary($title);
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDateTime($start_datetime->toAtomString());
$event->setStart($start);
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDateTime($end_datetime->toAtomString());
$event->setEnd($end);
// Create new conference
$conference = new \Google_Service_Calendar_ConferenceData();
$entryPoint = new \Google_Service_Calendar_EntryPoint();
$entryPoint->setAccessCode('wx12z3s');
$entryPoint->setEntryPointType('video');
$entryPoint->setLabel('meet.google.com/wx12z3s');
$entryPoint->setMeetingCode('wx12z3s');
$entryPoint->setPasscode('wx12z3s');
$entryPoint->setPassword('wx12z3s');
$entryPoint->setPin('wx12z3s');
$entryPoint->setUri('https://meet.google.com/wx12z3s');
$conference->setEntryPoints($entryPoint);
$conferenceSolution = new \Google_Service_Calendar_ConferenceSolution();
$conferenceSolution->setIconUri(null);
$conferenceSolution->setKey(new \Google_Service_Calendar_ConferenceSolutionKey());
$conference->setConferenceSolution($conferenceSolution);
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId($request->_token);
$conferenceSolutionKey = new \Google_Service_Calendar_ConferenceSolutionKey();
$conferenceSolutionKey->setType("hangoutsMeet");
$conferenceRequest->setConferenceSolutionKey($conferenceSolutionKey);
$conferenceRequest->setStatus(new \Google_Service_Calendar_ConferenceRequestStatus());
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
//attendee
if ($request->has('attendee_name')) {
$attendees = [];
$attendee_names = $request->input('attendee_name');
$attendee_emails = $request->input('attendee_email');
foreach ($attendee_names as $index => $attendee_name) {
$attendee_email = $attendee_emails[$index];
if (!empty($attendee_name) && !empty($attendee_email)) {
$attendee = new \Google_Service_Calendar_EventAttendee();
$attendee->setEmail($attendee_email);
$attendee->setDisplayName($attendee_name);
$attendees[] = $attendee;
}
}
$event->attendees = $attendees;
}
$created_event = $cal->events->insert($calendar_id, $event);
$evt->title = $title;
$evt->calendar_id = $calendar_id;
$evt->event_id = $created_event->id;
$evt->datetime_start = $start_datetime->toDateTimeString();
$evt->datetime_end = $end_datetime->toDateTimeString();
$evt->save();
return redirect('/event/create')
->with('message', [
'type' => 'success',
'text' => 'Event was created!'
]);
}
Event created successfully but no conference data showed on user's google calendar event card so he can not access the new created conference meet link
The question is how can I know if conference data is added to the event successfully although hangout meet link did not show on the event card?
This combination of the answers above worked for me:
$event = new \Google_Service_Calendar_Event(array(
'summary' => 'Appointment',
'location' => 'Earth',
'description' => 'Hello world',
'start' => array(
'dateTime' => Carbon::now()->format('c'),
'timeZone' => 'Europe/Zurich',
),
'end' => array(
'dateTime' => Carbon::now()->addMinutes(15)->format('c'),
'timeZone' => 'Europe/Zurich',
)
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s', $event->htmlLink);
$conference = new \Google_Service_Calendar_ConferenceData();
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId('randomString123');
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
$event = $service->events->patch($calendarId, $event->id, $event, ['conferenceDataVersion' => 1]);
printf('<br>Conference created: %s', $event->hangoutLink);
There's no information regarding how to show the meet link in calendar event card from the documentation. You will need to manually insert/input from the comment section the url of Hangout meeting.
I would like to suggest to use the Events formats from Hangouts Chat API.
$created_event = $cal->events->insert(
$calendar_id,
$event,
['conferenceDataVersion' => 1]
);
Need to set the conferenceDataVersion => 1 as one in the optional parameter set.
For example: I can copy only one file but I need opportunity to copy a few files because I have problems with the speed of application.
$fileMimeType = $this->service->files->get($googleFileId, array('fields' => 'mimeType'));
$metadata = new \Google_Service_Drive_DriveFile(
array(
'name' => uniqid(),
'uploadType' => 'multipart',
'mimeType' => isset($fileMimeType->mimeType) ? $fileMimeType->mimeType : false
)
);
$file = $this->service->files->copy($googleFileId, $metadata, array('fields' => 'id'));
Here is a sample from the docs of the google-api-client :
<?php
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
// Warn if the API key isn't set.
if (!$apiKey = getApiKey()) {
echo missingApiKeyWarning();
return;
}
$client->setDeveloperKey($apiKey);
$service = new Google_Service_Books($client);
$client->setUseBatch(true);
$batch = $service->createBatch();
$optParams = array('filter' => 'free-ebooks');
$req1 = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
$batch->add($req1, "thoreau");
$req2 = $service->volumes->listVolumes('George Bernard Shaw', $optParams);
$batch->add($req2, "shaw");
$results = $batch->execute();
In your case, i think it will look like this :
P.S : Try enabling the batch processing when creating your client as show above ($client->setUseBatch(true);)
$batch = $this->service->createBatch();
$fileMimeType = $this->service->files->get($googleFileId, array('fields' => 'mimeType'));
$metadata = new \Google_Service_Drive_DriveFile(
array(
'name' => uniqid(),
'uploadType' => 'multipart',
'mimeType' => isset($fileMimeType->mimeType) ? $fileMimeType->mimeType : false
)
);
$fileCopy = $this->service->files->copy($googleFileId, $metadata, array('fields' => 'id'));
$batch->add($fileCopy, "copy");
$results = $batch->execute();
More details here
Abdelkarim EL AMEL: Thanks, you forward me to one of solving :)
We can't use this code:
$fileCopy = $this->service->files->copy($googleFileId, $metadata, array('fields' => 'id'));
$batch->add($fileCopy, "copy");
Because method $batch->add accept Psr\Http\Message\RequestInterface, $this->service->files->copy returned Google_Service_Drive_DriveFile
But we can create GuzzleHttp\Psr7\Request as same creating method copy from $this->service->files->copy.
This code solved my problem:
private function copyFileRequest($googleFileId)
{
// build the service uri
$url = $this->service->files->createRequestUri('files/{fileId}/copy', [
'fileId' => [
'location' => 'path',
'type' => 'string',
'value' => $googleFileId,
],
]);
$request = new Request('POST', $url, ['content-type' => 'application/json']);
return $request;
}
public function batchCopy()
{
$googleFileIdFirst = 'First file';
$googleFileIdSecond = 'Second file';
$batch = $this->service->createBatch();
$batch->add($this->copyFileRequest($googleFileIdFirst));
$batch->add($this->copyFileRequest($googleFileIdSecond));
$results = $batch->execute();
/** #var Response $result */
foreach ($results as $result) {
/** #var Stream $body */
$body = (string)$result->getBody(); // Returned json body with copy file
}
}
Other way, we can set defer as true for Google_Client
$client = new \Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes([\Google_Service_Drive::DRIVE]);
// Calls should returned request not be executed
$client->setDefer(true)
$service = new \Google_Service_Drive($this->client);
And all methods from service return Psr\Http\Message\RequestInterface
$batch = $service->createBatch();
$googleServiceDriveFile = new \Google_Service_Drive_DriveFile(['name' => uniqid()]);
$request = $service->files->copy($googleFileId, $googleServiceDriveFile, ['fields' => 'id']);
$batch->add($request);
$results = $batch->execute();
I am trying to insert an event in my calendar using calendar id.
I just copied a code snippet from here
and downloaded SDK from here
Here is my code
<?php
// Refer to the PHP quickstart on how to setup the environment:
// https://developers.google.com/google-apps/calendar/quickstart/php
// Change the scope to Google_Service_Calendar::CALENDAR and delete any stored
// credentials.
include('google-api-php-client-2.0.3/vendor/autoload.php');
include('google-api-php-client-2.0.3/src/Google/Client.php');
include('google-api-php-client-2.0.3/src/Google/Service/Resource.php');
include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/vendor/google/apiclient-services/src/Google/Service/Calendar.php');
include('google-api-php-client-2.0.3/google-api-php-client-2.0.3/src/Google/Service.php');
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2015',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2015-05-28T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2015-05-28T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=2'
),
'attendees' => array(
array('email' => 'lpage#example.com'),
array('email' => 'sbrin#example.com'),
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'xxxxxxxxxxxxxx#group.calendar.google.com';
$client = new Google_Client();
$client->setApplicationName("schedular app");
$client->setClientId('xxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxx');
$service = new Google_Service_Calendar_Events_Resource($client,$event,'','');
$events = $service->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
?>
but I am getting error like
Fatal error: Cannot declare class Google_Service, because the name is already in use in D:\xampp\htdocs\gmt\google-api-php-client-2.0.3\src\Google\Service.php on line 18
How to solve this. or what i am doing wrong. please help.
I guess the root of your problem is that you are using too many includes. Use only include('google-api-php-client-2.0.3/vendor/autoload.php'); and delete the rest of them. I think that the way your code is structured should be enough to create the event, but the way I prefer doing it is this way:
<?php
session_start();
//INCLUDE PHP CLIENT LIBRARY
require_once "google-api-php-client-2.0.3/vendor/autoload.php";
$client = new Google_Client();
$client->setAuthConfig("client_creds.json");
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$client->addScope("https://www.googleapis.com/auth/calendar");
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$cal = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Event One',
'location' => 'Some Location',
'description' => 'Google API Test Event',
'start' => array(
'dateTime' => '2016-11-14T10:00:00-07:00'
),
'end' => array(
'dateTime' => '2016-11-14T10:25:00-07:00'
),
'reminders' => array(
'useDefault' => FALSE,
'overrides' => array(
array('method' => 'email', 'minutes' => 24 * 60),
array('method' => 'popup', 'minutes' => 10),
),
),
));
$calendarId = 'primary';
$event = $cal->events->insert($calendarId, $event);
printf('Event created: %s\n', $event->htmlLink);
} else {
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
Please note that for the calendar Id value I am using 'primary' because it will be the primary calendar of the authenticated user. Please refer to the documentation here for more details. I hope this helps!
Check all the files that you have include, this may have cause this error. Also you might want to start with PHP Quickstart:
Complete the steps described a simple PHP command-line application that makes requests to the Google Calendar API.
Here is their sample code:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/calendar-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
define('SCOPES', implode(' ', array(
Google_Service_Calendar::CALENDAR_READONLY)
));
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
$accessToken = json_decode(file_get_contents($credentialsPath), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
// Store the credentials to disk.
if(!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, json_encode($accessToken));
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Expands the home directory alias '~' to the full path.
* #param string $path the path to expand.
* #return string the expanded path.
*/
function expandHomeDirectory($path) {
$homeDirectory = getenv('HOME');
if (empty($homeDirectory)) {
$homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
}
return str_replace('~', realpath($homeDirectory), $path);
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => TRUE,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
if (count($results->getItems()) == 0) {
print "No upcoming events found.\n";
} else {
print "Upcoming events:\n";
foreach ($results->getItems() as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
printf("%s (%s)\n", $event->getSummary(), $start);
}
}
This shows what are the needed files to be included. Hope this helps.