【问题标题】:PHP Google Calendar APIPHP 谷歌日历 API
【发布时间】:2020-07-17 15:43:48
【问题描述】:

在项目中进行设置的初始阶段。 我已在 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 文件,但是目录是可写的。

【问题讨论】:

    标签: php google-api-php-client


    【解决方案1】:

    怀疑 Google 代码有误。 更改第 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多