如何使用PHP向用户显示他们的Google日历?

时间:2015-05-13 09:11:09

标签: php google-api google-calendar-api

我想尝试在我的网站上显示用户谷歌日历。我添加了一个显示链接的代码来添加谷歌日历。谷歌访问和返回网址工作正常,但重定向后我的网站上会显示404错误。

我还添加了所有正确的详细信息,如Client API,return_uri等。

这是我的代码

require_once 'Google/autoload.php';
    session_start(); 

    // ********************************************************  //
    // Get these values from https://console.developers.google.com
    // Be sure to enable the Analytics API
    // ********************************************************    //
    $client_id = '[Your client Id]';
    $client_secret = '[Your Client Secret]';
    $redirect_uri = '[Your Redirect URI]';

    $client = new Google_Client();
    $client->setApplicationName("Client_Library_Examples");
    $client->setClientId($client_id);
    $client->setClientSecret($client_secret);
    $client->setRedirectUri($redirect_uri);
    $client->setAccessType('offline');   // Gets us our refreshtoken

    $client->setScopes(array('https://www.googleapis.com/auth/calendar.readonly'));


    //For loging out.
    if (isset($_GET['logout'])) {
    unset($_SESSION['token']);
    }


    // Step 2: The user accepted your access now you need to exchange it.
    if (isset($_GET['code'])) {

    $client->authenticate($_GET['code']);  
    $_SESSION['token'] = $client->getAccessToken();
    $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
    }

    // Step 1:  The user has not authenticated we give them a link to login    
    if (!isset($_SESSION['token'])) {

    $authUrl = $client->createAuthUrl();

    print "<a class='login' href='$authUrl'>Connect Me!</a>";
    }    


    // Step 3: We have access we can now create our service
    if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
    print "<a class='logout' href='http://www.daimto.com/Tutorials/PHP/GCOAuth.php?logout=1'>LogOut</a><br>";   

    $service = new Google_Service_Calendar($client);    

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

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

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


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


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

1 个答案:

答案 0 :(得分:0)

检查您是否在脚本和Google开发者控制台中正确设置了重定向URI,您可能忘记在复制的教程中更改它。