简体   繁体   中英

How to insert event to user google calendar using php?

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 = '6094969424649-compute@developer.gserviceaccount.com';
$service_account_name = 'testsd-440@studied-zephyr-117012.iam.gserviceaccount.com'; // 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' => 'abc@gmail.com'),
    array('email' => 'def@gmail.my'),
  ),
  '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);

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

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

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

<!DOCTYPE html><html>
<head>
    <title>GOOGLE CALENDAR - insert, change and delete Google Calenda event</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="UTF-8">
    <style>
        body{
            margin: 0;
            width: 100%;
            font-family: Verdana, Arial;
        }
        #centro{
            width: 780px;
            margin: auto;
        }
        .calendario{
            position: relative;
            width: 800px;
            height: 600px;
            margin-left:-390px;
            left: 50%;
            float: left;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
        }
        #datahora{
            width: 250px;
            float: left;
        }
        #cento{
            width: 780px;
            float: left;
        }
        #centro .primo{
            width: 100%;
            background-color: #E3E9FF;
            padding: 10px;
            margin: 50px 0;
            float: left;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
        }
        label {
            width: 780px;
            margin: 5px 5px 0;
            float: left;
            padding-top: 10px;
        }

        input{
            margin: 5px;
            float: left;
            padding: 5px 10px;
            -webkit-border-radius: 5px;
            -moz-border-radius: 5px;
            border-radius: 5px;
            border: 1px #CCC solid;
        }
        input[type="text"]{
            width: 750px;
        }
        input[type="date"]{
            width: 125px;
        }
        input[type="time"]{
            width: 70px;
        }
        input[type="submit"]{

        }

        input:focus{
            border: 1px  #cc0000 solid;
            box-shadow: 0 0 5px #cc0000;
        }
        .btn {
            background: #3498db;
            background-image: -webkit-linear-gradient(top, #3498db, #2980b9);
            background-image: -moz-linear-gradient(top, #3498db, #2980b9);
            background-image: -ms-linear-gradient(top, #3498db, #2980b9);
            background-image: -o-linear-gradient(top, #3498db, #2980b9);
            background-image: linear-gradient(to bottom, #3498db, #2980b9);
            -webkit-border-radius: 5;
            -moz-border-radius: 5;
            border-radius: 5px;
            font-family: Arial;
            color: #ffffff;
            font-size: 20px;
            padding: 10px 20px 10px 20px;
            text-decoration: none;
            cursor: pointer;
        }

        .btn:hover {
            background: #3cb0fd;
            background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
            background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
            background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
            background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
            background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
            text-decoration: none;
        }

    </style>
</head>
<body>

    <?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 = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //change this
    $Email_address = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //change this
    $key_file_location = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; //change this
    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $key = file_get_contents($key_file_location);


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

    $calendarList = $service->calendarList->listCalendarList();
    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;
        }
    }


    if ($_POST) {

        $Summary = $_POST['Summary'];
        $Location = $_POST['Location'];
        $DateStart = $_POST['DateStart'];
        $TimeStart = $_POST['TimeStart'];
        $DateEnd = $_POST['DateEnd'];
        $TimeEnd = $_POST['TimeEnd'];
        $status = $_POST['status'];



        if ($status == 'Insert') {
            //--------------- trying to insert EVENT --------------- 
            $event = new Google_Service_Calendar_Event();
            $event->setSummary($Summary);
            $event->setLocation($Location);
            $start = new Google_Service_Calendar_EventDateTime();
            $datatimeI = geratime(DataIT2DB($DateStart), $TimeStart);

            $start->setDateTime($datatimeI);
            $event->setStart($start);
            $end = new Google_Service_Calendar_EventDateTime();
            $datatimeF = geratime(DataIT2DB($DateEnd), $TimeEnd);

            $end->setDateTime($datatimeF);
            $event->setEnd($end);
            $attendee1 = new Google_Service_Calendar_EventAttendee();
            $attendee1->setEmail('xxxxxxx@gmail.com');
            $attendees = array($attendee1);
            $event->attendees = $attendees;
            $createdEvent = $service->events->insert('primary', $event);
            $_SESSION['eventID'] = $createdEvent->getId();
        } else if ($status == 'Cancel') {
            //--------------- trying to del EVENT --------------- 
            $createdEvent = $service->events->delete('primary', $_SESSION['eventID']);
        } else if ($status == 'Update') {
            //--------------- trying to update EVENT --------------- 

            $rule = $service->events->get('primary', $_SESSION['eventID']);


            $event = new Google_Service_Calendar_Event();
            $event->setSummary($Summary);
            $event->setLocation($Location);
            $start = new Google_Service_Calendar_EventDateTime();
            $datatimeI = geratime(DataIT2DB($DateStart), $TimeStart);

            $start->setDateTime($datatimeI);
            $event->setStart($start);
            $end = new Google_Service_Calendar_EventDateTime();
            $datatimeF = geratime(DataIT2DB($DateEnd), $TimeEnd);

            $end->setDateTime($datatimeF);
            $event->setEnd($end);
            $attendee1 = new Google_Service_Calendar_EventAttendee();
            $attendee1->setEmail('xxxxxxxxxx@gmail.com'); //change this
            $attendees = array($attendee1);
            $event->attendees = $attendees;

            $updatedRule = $service->events->update('primary', $rule->getId(), $event);
        }
    }

    function DataIT2DB($datapega) {
        if ($datapega) {
            $data = explode('/', $datapega);
            if (count($data) > 1) {
                $datacerta = $data[2] . '-' . $data[1] . '-' . $data[0];
            } else {
                $datacerta = $datapega;
            }
        } else {
            $datacerta = $datapega;
        }
        return $datacerta;
    }

    function geratime($DateStart, $TimeStart) {
        $dataHora = $DateStart . 'T' . $TimeStart . ':00.000+02:00'; //Fuso Rome
        return $dataHora;
    }
    ?>

    <div id="contenut" style="width: 100%; float: left;">
        <div id="centro">
            <div class="primo">
                <form name="adicionar" method="POST" action="#">
                    ID evento: <?php echo ( isset($_SESSION['eventID']) ? $_SESSION['eventID'] : "" ); ?>
                    <input type="hidden" name="" value="<?php echo ( isset($_SESSION['eventID']) ? $_SESSION['eventID'] : "" ); ?>" />
                    <input type="text" name="Summary" value="<?php echo ( isset($_POST['Summary']) ? $_POST['Summary'] : "" ); ?>" placeholder="Title"/>
                    <input type="text" name="Location" value="<?php echo ( isset($_POST['Location']) ? $_POST['Location'] : "" ); ?>" placeholder="Location "/>
                    <div id="datahora">
                        <label>Starting Date</label>
                        <input type="date" name="DateStart" value="<?php echo ( isset($_POST['DateStart']) ? $_POST['DateStart'] : "" ); ?>" placeholder="DD/MM/YYYY"/>
                        <input type="time" name="TimeStart" value="<?php echo ( isset($_POST['TimeStart']) ? $_POST['TimeStart'] : "" ); ?>" placeholder="10:20"/>
                    </div>
                    <div id="datahora">
                        <label>Ending Date</label>
                        <input type="date" name="DateEnd" value="<?php echo ( isset($_POST['DateEnd']) ? $_POST['DateEnd'] : "" ); ?>" placeholder="DD/MM/YYYY"/>
                        <input type="time" name="TimeEnd" value="<?php echo ( isset($_POST['TimeEnd']) ? $_POST['TimeEnd'] : "" ); ?>" placeholder="10:20" />
                    </div>
                    <div id="cento">
                        <input class="btn" type="submit" value="Insert" name="status" />
                        <input class="btn" type="submit" value="Cancel" name="status" />
                        <input class="btn" type="submit" value="Update" name="status" />
                    </div>

                </form>
            </div>
        </div>
    </div>
</body>

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

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

$data['calendar_url']['google'] =   
    'http://www.google.com/calendar/event?action=TEMPLATE'.
    '&text='.$event_detail["title"].
    '&dates='.$event_detail["datetime"].'/'.$event_detail["datetime_end"].
    '&location='.$event_detail["location"].
    '&details='.$event_detail["details"].
    '&trp=false'.
    '&sprop=website:www.someurl.com'.
    '&sprop=name:Name'
;

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:

<a href='<?= $data["calendar_url"]["google"]; ?>'>Create google event</a>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM