Home » Php » How to insert event to user google calendar using php?

How to insert event to user google calendar using php?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have these following codes to insert to my specific google calendar. Well it very successful, but how to let user can add to their own calendar? Somebody can help me… My expected results was like user can login via google…. it’s means that user can add to their own google calendar. Thanks.

Codes to add to my specific calendar

require_once './vendor/google/apiclient/src/Google/autoload.php';

$key_file_location = 'Calendar-96992da17e2dda.p12'; // key.p12 to create in the Google API console

$client_id = '[email protected]';
$service_account_name = '[email protected]'; // Email Address in the console account

if (strpos($client_id, "gserviceaccount") == false || !strlen($service_account_name) || !strlen($key_file_location)) {
    echo "no credentials were set.";
    exit;
}

/** We create service access ***/
$client = new Google_Client();  

/************************************************
If we have an access token, we can carry on.  (Otherwise, we'll get one with the help of an  assertion credential.)
Here we have to list the scopes manually. We also supply  the service account
 ************************************************/
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'), // ou calendar_readonly
$key
);

$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();



// Get the API client and construct the service object.
$service = new Google_Service_Calendar($client);


    /************* INSERT ****************/
$event = new Google_Service_Calendar_Event(array(
  'summary' => 'My Summary',
  'location' => 'My Location',
  'description' => 'My Description',
  'start' => array(
    'dateTime' => '2015-12-31T09:09:00',
    'timeZone' => 'Asia/Singapore',
  ),
  'end' => array(
    'dateTime' => '2015-12-31T17:16:00',
    'timeZone' => 'Asia/Singapore',
  ),
  '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),
    ),
  ),
));

$events = $service->events->insert('primary', $event);
printf('Event created: %s', $events->htmlLink);
How to&Answers:

Uses the PHP client library.

// 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.

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

for more details please check official document from here Events: insert

Answer:

As you want to do the Event insert for others then you have to go through OAuth 2.0 implementation. Your application must use OAuth 2.0 to authorize requests from authenticated user. No other authorization protocols are supported.

Applications that use OAuth 2.0 must have credentials that identify the application to the OAuth 2.0. Applications that have these credentials can access the APIs that you enabled for your project. To obtain web application credentials for your project, complete these steps:

  • Go to Google Developers Console and Open Credentials page.

  • Create OAuth 2.0 credentials by clicking Create new Client ID under the OAuth heading. Next, look for your application’s client ID and client secret in the relevant table.

  • You can also create and edit redirect URIs from this page, by clicking a client ID. Redirect URIs are the URIs to your application’s auth endpoints, which handle responses from the OAuth 2.0 server.

  • Download the client_secrets.json file and securely store it in a location that only your application can access.

Now there are two phase of work.

First Phase

In the First Phase you will re-direct the user to Google Server to Authorise you application to make changes. Since you are already using Google PHP Clinet library things would be easy

 $client = new Google_Client();
 client->setAuthConfigFile('client_secrets.json');  //file downloaded earlier
 $client->addScope("https://www.googleapis.com/auth/calendar");

Generate a URL to request access from Google’s OAuth 2.0 server:

 $auth_url = $client->createAuthUrl();
 header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); //redirect user to Google

Second Phase

Second Phase starts when the user Authorise your application and Google re-direct the user to your website with temprory token code.

In case user denies or error response:

https://localhost/auth?error=access_denied

An authorization code response:

https://localhost/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7

Now to have exchange an authorization code for an access token, use the authenticate method:

$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();

Now set your Access Token in Library

 $client->setAccessToken($access_token);

Now, you can do things according to your need delete/insert/edit events easily

Answer:

Refer this code its working.
Insert your own client_id,Email_address and key_file_location

Answer:

There is no need for such complication you can order the users event calendar to create an event via url:

Variable values:

$event_detail['title'] => name of the event

$event_detail["datetime"] => event start datetime in this format (YmdTHis)
the T letter represents the time separator (ex 20151212T160000) – event starts on 2015 – 12 – 12 / 16:00h

$event_detail["datetime_end"] => same rules as for datetime – end of the event

$location => location of the event

$details => event description

The other parameters should be the source of the event.

$trp = false – I’m not sure what this does

So you can just insert all of this in a anchor:

Edit: After a bit of searching I found this on stack-overflow it explains the same: Link to add to google calendar