Google calendar using php does not show shared calendar list - php

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);

Related

Can I use my php app to add events in Google Calendar?

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>";
}
}
?>

Can't create an event using google calendar api php

I've followed all the instructions, the php quickstart and the events.insert pages by google; but when i run it the consent form pops up I click allow and then nothing happens bar the consent form resetting.If i change the redirect url to another page then it no longer resets the consent form, but still nothing happens.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);
Thank you.
I have resolved my issue. The problem was I had forgotten a part of the google Oauth2.0 code required, which meant I never received the access token.
This snippet below is fully functional. Hope it helps and thank you all for answering.
$client = new Google_Client();
$client->setAuthConfig('redacted');
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/calendar.events");
$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file
$client->setAccessType('offline');
$client->setIncludeGrantedScopes(true);
$client->setPrompt('consent');
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => 'test',
'location' => 'somewhere',
'description' => 'test description',
'start' => array(
'dateTime' => '2020-09-03T09:00:00+02:00',
),
'end' => array(
'dateTime' => '2020-09-03T17:00:00+02:00',
),
));
$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);

View meet link to each event created in a google calendar

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.

How to retrieve Google Calendar event ID after creating event in PHP

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;
}
}

How to insert events into Google Calendar from server with client token by using api

I am using given below code but i am unable to insert event in google calendar through . Please help me out . If you have any info . Please reply as soon as possible.
$client = new Google_Client();
$client->setApplicationName("calender");
$client->setClientId('1065799091955-kuek7e5miai4q590v49jpntr00u3pcbp.apps.googleusercontent.com');
$client->setClientSecret('SBOs_gfbFn92bpGdBt8aQY1z');
$client->setRedirectUri('http://www.sydneywebexperts.com.au/Add-Calendar/event.php');
$client->setDeveloperKey('AIzaSyDjRKaWPdAlwvJQlKeLuxKnyzXdKZiR5_A');
//$cal = new Google_CalendarService($client);
$event = new Google_CalendarService(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);
---------------------- or------------------------
<?php
error_reporting(E_ALL);
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_CalendarService.php';
session_start();
if ((isset($_SESSION)) && (!empty($_SESSION))) {
echo "There are cookies<br>";
echo "<pre>";
print_r($_SESSION);
}
$client = new Google_Client();
$client->setApplicationName("calender");
$client->setClientId('1065799091955-kuek7e5miai4q590v49jpntr00u3pcbp.apps.googleusercontent.com');
$client->setClientSecret('SBOs_gfbFn92bpGdBt8aQY1z');
$client->setRedirectUri('http://www.sydneywebexperts.com.au/Add-Calendar/event.php');
$client->setDeveloperKey('AIzaSyDjRKaWPdAlwvJQlKeLuxKnyzXdKZiR5_A');
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
echo "<br><br><font size=+2>Logging out</font>";
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo "<br>I got a code from Google = ".$_GET['code']; // You won't see this if redirected later
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
echo "<br>I got the token = ".$_SESSION['token']; // <-- not needed to get here unless location uncommented
}
if (isset($_SESSION['token'])) {
echo "<br>Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
echo "<hr><font size=+1>I have access to your calendar</font>";
$event = new Google_Event();
$event->setSummary('Halloween');
$event->setLocation('The Neighbourhood');
$start = new Google_EventDateTime();
$start->setDateTime('2016-4-13T10:00:00.000-05:00');
$event->setStart($start);
$end = new Google_EventDateTime();
$end->setDateTime('2016-4-13T10:25:00.000-05:00');
$event->setEnd($end);
print_r($event);
$createdEvent = $cal->events->insert('primary', $event);
print_r($createdEvent);
echo "<br><font size=+1>Event created</font>";
echo "<hr><br><font size=+1>Already connected</font> (No need to login)";
} else {
$authUrl = $client->createAuthUrl();
print "<hr><br><font size=+2><a href='$authUrl'>Connect Me!</a></font>";
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
echo "<br><br><font size=+2><a href=$url?logout>Logout</a></font>";
?>
I am frustrated but i am unable to insert event in calendar.

Categories