未捕获的InvalidArgumentException:无效的令牌格式

时间:2018-08-13 10:55:12

标签: php oauth-2.0 google-api google-calendar-api google-api-php-client

我正在使用 PHP客户端库 Google Calendar Api与PHP集成,但是当我通过Command运行应用程序时,它会显示无效的令牌格式 strong>,但我的ClientIDClient Secret是正确的。 我的代码与 Google日历Api文档中提供的代码相同,但不适用于我。 如果有人可以帮助我解决这个问题。请您坚持下去,然后再说吧。

<?php
   require __DIR__ . '/vendor/autoload.php';
   if (php_sapi_name() != 'cli') {
     throw new Exception('This application must be run on the command line.');
   }
function getClient(){
   $client = new Google_Client();
   $client->setApplicationName('Google Calendar API PHP Quickstart');
   $client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
   $client->setAuthConfig('client_secret.json');
   $client->setAccessType('offline');

  // Load previously authorized credentials from a file.
  $credentialsPath = 'client_secret.json';
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } 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);

    // Check to see if there was an error.
    if (array_key_exists('error', $accessToken)) {
        throw new Exception(join(', ', $accessToken));
    }

    // Store the credentials to disk.
    if (!file_exists(dirname($credentialsPath))) {
        mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s\n", $credentialsPath);
  }
   $client->setAccessToken($accessToken);

  // Refresh the token if it's expired.
  if ($client->isAccessTokenExpired()) {
     $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
     file_put_contents($credentialsPath, 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);
}
}

0 个答案:

没有答案