0
votes

I am using PHP to create a google calendar event and add attendees, but I want to create, update, delete events in the user's calendar directly.

below is my PHP code which is working fine to insert add event in my gmail clanedar but I am not able to add an event to other users calendars.

 <?php 
require  'google/vendor/autoload.php';

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

// 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);
$events = $results->getItems();

$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' => '2021-05-29T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2021-05-29T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=1'
),
'attendees' => array(
array('email' => '[email protected]'),
array('email' => '[email protected]'),
),
'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);

I want to add event direct to example1 and example2 google calendar. it is possible ?. Thanks in advance

2
In order to insert events into a users calendar you must have the users consent so they must have run your application and consented to your application access of their data.DaImTo
@DaImTo, I understand this, will this permission will need one time or every timeweb crew24
You are requesting offline access so the first time the user accepts your permissions you will be given a refresh token. If you store that refresh token you can use it in the future to request a new access token and request without needing the user to authenticate your application.DaImTo
@DaImTo Thanks , do you have working code for this or any tutorial link, that will be very helpfulweb crew24
@DaImTo May you have a look on this question stackoverflow.com/questions/65233736/…web crew24

2 Answers

0
votes

I have a feeling you may have just copied this code from somewhere and dont completely understand what it is doing.

Who, what, Where?

When your code is run the very first time. The user will be presented with a web page asking them to consent to your application accessing their data.

Once the user has consented your event will be inserted into the Primary calendar of that user.

$calendarId = 'primary';

All users have one calendar that is set to primary, besides that they can create different calendars but you have chosen to insert it into their primary calendar.

So the event will be inserted into the primary calendar of the user who authncates.

Who is the user.

Your code is requesting something called offline access.

$client->setAccessType('offline');

This means that you are asking the user to let you access their calendar when they are not present. Or offline. This would work for example if you want to automatically add events to users calendars for say meetings or something.

What it actually does is return to you a refreshToken, refresh tokens are an Oauth2 thing which will give you the ability to request a new access token when ever you need to access the users data, this being their calendar. With a refresh token you can do the following which will cause the client to load itself a new access token.

$client->fetchAccessTokenWithRefreshToken([refreshtoken]);

Which you do apear to be doing to some extent.

The thing is that you will need to have each user whos calendar you wish to access to authorize your application at least once and save the refreshtoken in the database or in a file of some kind in order to keep track of which refresh token belongs to which user.

Currently your code is only storing one user

$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
    $accessToken = json_decode(file_get_contents($tokenPath), true);
    $client->setAccessToken($accessToken);
}

.....

 // Save the token to a file.
    if (!file_exists(dirname($tokenPath))) {
        mkdir(dirname($tokenPath), 0700, true);
    }

The first time your code runs its going to request access then its going to save the token file without defining which user it is and then it will just load that file from now on. Your current code is single user. This is what you will need to change if you want other users to run your application so that you can store their refresh tokens and write to their calendars as well.

-1
votes

If you want to create, update or delete events on other user's calendars. You’ll need to ask the owner to turn on the Make changes and manage sharing permission on their calendar.

  1. On your computer, open Google Calendar. You can't share calendars from the Google Calendar app.

  2. On the left, find the "My calendars" section. You might need to click it to expand it.

  3. Hover over the calendar you want to share, click More More and then Settings and sharing. To broadly share it:

    Under "Access permissions," check the boxes of the ways you want to share and choose your options in the drop-down menu.

    To share with individuals: Under "Share with specific people," click Add people.

  4. Add the person or Google group email address. Use the drop-down menu to adjust their permission settings.

  5. Click Send.

  6. The recipient will need to click the emailed link to add the calendar to their list.

References:

https://support.google.com/calendar/answer/37082?hl=en https://support.google.com/a/users/answer/37082#permissions


In your case, they need to share their calendar using "Share with specific people". Here are the permission settings available:

Make changes & manage sharing

  • Change sharing settings
  • Add and edit events
  • Find details for all events, including private ones
  • Find the time zone setting for the calendar
  • Permanently delete the calendar
  • Restore or permanently delete events from the calendar's Trash
  • Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Make changes to events

  • Add and edit events
  • Find details for all events, including private ones
  • Find the time zone setting for the calendar
  • Restore or permanently delete events from the calendar's Trash
  • Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Find all event details

  • Find details for all events except those marked as private
  • Find the time zone setting for the calendar
  • Subscribe to email alerts when events are created, changed, cancelled, RSVPed to, or coming up

Find only free/busy (hide details)

  • Check when your calendar is booked and when it has free time, but not the names or other details of your events.

Once you were able to gain the required calendar permission, you can now create, update and delete events using the Google Calendar API. For more details regarding the Calendar Events Methods please refer here: https://developers.google.com/calendar/v3/reference#Events

Example:

I shared a calendar to User1 Test with the following configuration:

enter image description here

Then I created an event using the Calendar API using User1 Test account, using Events:insert method based on the calendar's id that was shared. enter image description here

  • Notice that in the event that was created, it indicates that the event was created by User1 Test.

In your code, you are creating events on your currently logged in user with the use of 'primary' keyword. If you want to create events on other user's calendars, you need to replace the calendar id based on the calendar that you want to modify. You can view the calendar id in the calendar's settings and sharing.

// Print the next 10 events on the user's calendar.
$calendarId = 'primary';

enter image description here