首页 > 解决方案 > 如何使用 Google Calendar API quickstart.php 解决重定向 URI 错误

问题描述

我在用着

我按照https://developers.google.com/calendar/quickstart/php上的指示 打开命令提示符并执行命令PHP quickstart.php时出现错误:

First statement in the php.
Finished Outer IF isAccessTokenExpired.
PHP Fatal error:  Uncaught InvalidArgumentException: missing the required redirect URI in C:\PHP\vendor\google\auth\src\OAuth2.php:637
    Stack trace:
    #0 C:\PHP\vendor\google\apiclient\src\Google\Client.php(328): Google\Auth\OAuth2->buildFullAuthorizationUri(Array)
    #1 C:\Apache24\htdocs\quickstart.php(60): Google_Client->createAuthUrl()
    #2 C:\Apache24\htdocs\quickstart.php(81): getClient()
    #3 {main}
      thrown in C:\PHP\vendor\google\auth\src\OAuth2.php on line 637

我正在使用 QuickStart 中的代码

<?php
/**
 * Copyright 2018 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// [START calendar_quickstart]
//require __DIR__ . '/vendor/autoload.php';
print "First statement in the php.\n";

require 'C:\php\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->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    $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()) {
        print "Finished Outer IF isAccessTokenExpired.\n";
    // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            print "Finished Inner IF getRefreshToken.\n";
            $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);
    }
}
// [END calendar_quickstart]

似乎它在声明上失败了, if ($client->getRefreshToken()) 我不明白为什么我会在快速入门代码上收到错误。任何想法为什么会发生这种情况?

标签: phpgoogle-calendar-api

解决方案


Quickstart.php 存在问题。我用谷歌搜索了这个错误,他们给了我一个立即修复。删除旧的$client->setRedirectUri('http://' . $_SERVER['localhost'] . '/oauth2callback.php'); Then,就在语句之后:$client = new Google_Client();添加新行:$client->setRedirectUri("urn:ietf:wg:oauth:2.0:oob");我还通过转到控制台创建了新凭据,然后选择:创建 OAuth 客户端 ID。我使用了 Application Type: Other然后下载了 Client Secret 文件并将其重命名为 credentials.json。现在一切正常。


推荐阅读