Google Api PHP客户端 - 如何登录

时间:2017-12-07 08:52:56

标签: php api google-api google-oauth2

我正在尝试使用google的api使用php与gmail用户进行loggearme连接并检索我的日历,为此我使用此代码。 我得到的是loggearme和oauth2我返回 TOKEN 但是一旦我有了这个令牌,我就不知道如何使用它来获取我的谷歌日历的详细信息。

谢谢

的settings.php

/* Google App Client Id */
define('CLIENT_ID', 'XXXXXXXX.apps.googleusercontent.com');

/* Google App Client Secret */
 define('CLIENT_SECRET', 'XXXXXXX');

 /* Google App Redirect Url */
 define('CLIENT_REDIRECT_URL', 
 'http://localhost:8081/googleTesting/oauth2callback.php');


    <html>
<head>....</head>

<body>



 <a href="<?= 'https://accounts.google.com/o/oauth2/auth?scope=' . urlencode('https://www.googleapis.com/auth/userinfo.profile') . '&redirect_uri=' . urlencode(CLIENT_REDIRECT_URL) . '&response_type=code&client_id=' . CLIENT_ID . '&access_type=online' ?>">Login with Google</a>
<br>

   </body>
 </html>

Calendar.php

//  We have access we can now create our service
if (isset($_SESSION['datosGoogle']['access_token'])) {

$client = new Google_Client();
$client->setAccessToken($_SESSION['datosGoogle']['access_token']);
print "LogOut";

$service = new Google_Service_Calendar($client);

$calendarList  = $service->calendarList->listCalendarList();;

while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {

        echo $calendarListEntry->getSummary()."\n";


        // get events
        $events = $service->events->listEvents($calendarListEntry->id);


        foreach ($events->getItems() as $event) {
            echo "-----".$event->getSummary()."";
        }
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}

}

1 个答案:

答案 0 :(得分:1)

当您请求登录Google时,您需要在该请求中添加范围。

谷歌有更好的答案。 Google tutorialGoogle php implementation

这一部分非常重要。

//import libraries php composer.phar require google/apiclient:^2.0
require_once __DIR__ . '/vendor/autoload.php';

define('SCOPES', implode(' ', array(
  Google_Service_Calendar::CALENDAR_READONLY)
));
$client->setScopes(SCOPES);