为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 谷歌日历 API

PHP 谷歌日历 API

PHP
喵喔喔 2023-08-11 16:59:12
在项目中设置此功能的初始阶段。我已在 Google 开发者页面启用它并尝试遵循快速入门指南https://developers.google.com/calendar/quickstart/php然而,与大多数 Google API 教程一样,这个“快速入门”不起作用。我通过授权页面并获得了在终端中输入的代码,但很长一段时间后我才收到错误PHP Fatal error:  Uncaught RuntimeException: Unable to read from stream in [site root]/vendor/guzzlehttp/psr7/src/Stream.php    Stack trace:#0 [site root]/vendor/guzzlehttp/psr7/src/functions.php(382): GuzzleHttp\Psr7\Stream->read()    #1 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(214): GuzzleHttp\Psr7\copy_to_stream()    #2 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(133): GuzzleHttp\Handler\StreamHandler->drain()    #3 [site root]/vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php(50): GuzzleHttp\Handler\StreamHandler->createResponse()    #4 [site root]/vendor/guzzlehttp/guzzle/src/PrepareBodyMiddleware.php(66): GuzzleHttp\Handler\StreamHandler->__invoke()    #5 [site root]/vendor/guzzlehttp/guzzle/src/Middleware.php(29): GuzzleHttp\PrepareBodyMiddleware->__invoke()    #6 [site root]/vendor/guzzlehttp/guzzle/src/RedirectMiddleware.php(70): GuzzleHtt in [site root]/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php on line 52不会创建 token.json 文件,但该目录是可写的。
查看完整描述

1 回答

?
米脂

TA贡献1836条经验 获得超3个赞

怀疑谷歌代码是错误的。更改第 16 行的范围可以使其正确运行。


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

完整代码:


<?php

require __DIR__ . '/vendor/autoload.php';


if (php_sapi_name() != 'cli') {

    throw new Exception('This application must be run on the command line.');

}


/**

 * Returns an authorized API client.

 * @return Google_Client the authorized client object

 */

function getClient()

{

    $client = new Google_Client();

    $client->setApplicationName('Google Calendar API PHP Quickstart');

    //$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);

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


    $client->setAuthConfig('credentials.json');

    $client->setAccessType('offline');

    $client->setPrompt('select_account consent');


    // Load previously authorized token from a file, if it exists.

    // The file token.json stores the user's access and refresh tokens, and is

    // created automatically when the authorization flow completes for the first

    // time.

    $tokenPath = 'token.json';

    if (file_exists($tokenPath)) {

        $accessToken = json_decode(file_get_contents($tokenPath), true);

        $client->setAccessToken($accessToken);

    }


    // If there is no previous token or it's expired.

    if ($client->isAccessTokenExpired()) {

        // Refresh the token if possible, else fetch a new one.

        if ($client->getRefreshToken()) {

            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());

        } else {

            // Request authorization from the user.

            $authUrl = $client->createAuthUrl();

            printf("Open the following link in your browser:\n%s\n", $authUrl);

            print 'Enter verification code: ';

            $authCode = trim(fgets(STDIN));


            // Exchange authorization code for an access token.

            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

            $client->setAccessToken($accessToken);


            // Check to see if there was an error.

            if (array_key_exists('error', $accessToken)) {

                throw new Exception(join(', ', $accessToken));

            }

        }

        // Save the token to a file.

        if (!file_exists(dirname($tokenPath))) {

            mkdir(dirname($tokenPath), 0700, true);

        }

        file_put_contents($tokenPath, json_encode($client->getAccessToken()));

    }

    return $client;

}



// Get the API client and construct the service object.

$client = getClient();

$service = new Google_Service_Calendar($client);


// Print the next 10 events on the user's calendar.

$calendarId = 'primary';

$optParams = array(

    'maxResults' => 10,

    'orderBy' => 'startTime',

    'singleEvents' => true,

    'timeMin' => date('c'),

);

$results = $service->events->listEvents($calendarId, $optParams);

$events = $results->getItems();


if (empty($events)) {

    print "No upcoming events found.\n";

} else {

    print "Upcoming events:\n";

    foreach ($events as $event) {

        $start = $event->start->dateTime;

        if (empty($start)) {

            $start = $event->start->date;

        }

        printf("%s (%s)\n", $event->getSummary(), $start);

    }

}



查看完整回答
反对 回复 2023-08-11
  • 1 回答
  • 0 关注
  • 82 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信