简体   繁体   English

如何使用 php 将事件插入用户谷歌日历?

[英]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 .使用 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.

$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.当您想为其他人插入事件时,您必须通过 OAuth 2.0 实现。 Your application must use OAuth 2.0 to authorize requests from authenticated user.您的应用程序必须使用 OAuth 2.0 来授权来自经过身份验证的用户的请求。 No other authorization protocols are supported.不支持其他授权协议。

Applications that use OAuth 2.0 must have credentials that identify the application to the OAuth 2.0.使用 OAuth 2.0 的应用程序必须具有向 OAuth 2.0 标识应用程序的凭据。 Applications that have these credentials can access the APIs that you enabled for your project.具有这些凭据的应用程序可以访问您为项目启用的 API。 To obtain web application credentials for your project, complete these steps:要为您的项目获取 Web 应用程序凭据,请完成以下步骤:

  • Go to Google Developers Console and Open Credentials page.转到 Google Developers Console 和 Open Credentials 页面。

  • Create OAuth 2.0 credentials by clicking Create new Client ID under the OAuth heading.通过单击 OAuth 标题下的Create new Client ID创建 OAuth 2.0 凭据。 Next, look for your application's client ID and client secret in the relevant table.接下来,在相关表中查找应用程序的client IDclient secret

  • You can also create and edit redirect URIs from this page, by clicking a client ID.您还可以通过单击客户端 ID 从此页面创建和编辑重定向 URI。 Redirect URIs are the URIs to your application's auth endpoints, which handle responses from the OAuth 2.0 server.重定向 URI 是应用程序的身份验证端点的 URI,它处理来自 OAuth 2.0 服务器的响应。

  • Download the client_secrets.json file and securely store it in a location that only your application can access.下载client_secrets.json文件并将其安全地存储在只有您的应用程序可以访问的位置。

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.在第一阶段,您会将用户重定向到 Google 服务器以授权您的应用程序进行更改。 Since you are already using Google PHP Clinet library things would be easy由于您已经在使用 Google PHP Clinet 库,所以事情会很简单

 $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:生成一个 URL 以请求来自 Google 的 OAuth 2.0 服务器的访问权限:

 $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.当用户授权您的应用程序并且 Google 使用临时令牌代码将用户重定向到您的网站时,第二阶段开始。

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:现在要为访问令牌交换授权代码,请使用 authenticate 方法:

$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插入您自己的 client_id、Email_address 和 key_file_location

There is no need for such complication you can order the users event calendar to create an event via url:不需要这样复杂的操作,您可以通过 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['title'] => 事件名称

$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"] => 这种格式的事件开始日期时间 ( YmdTHis ) T字母代表时间分隔符 (例如20151212T160000 ) - 事件开始于 2015 - 12 - 12 / 16:00h

$event_detail["datetime_end"] => same rules as for datetime - end of the event $event_detail["datetime_end"] => 与 datetime 相同的规则 - 事件结束

$location => location of the event $location => 活动地点

$details => event description $details => 活动描述

The other parameters should be the source of the event.其他参数应该是事件的来源。

$trp = false - I'm not sure what this does $trp = false - 我不确定这是做什么的

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编辑:经过一番搜索后,我在堆栈溢出上找到了它,它的解释相同: Link to add to google calendar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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