duanjiang7505 2017-07-10 04:27
浏览 66

PHP / GMail API

I have been trying to use PHP coding for accessing my Gmail, following the documentation here: https://developers.google.com/gmail/api/quickstart/php This worked well until this evening when I started back on it. I now get the following error:

Fatal error: Uncaught LogicException: refresh token must be passed in or set as part of setAccessToken in C:\Users\mcgranj\Dropbox\eBay_web\google\vendor\google\apiclient\src\Google\Client.php:258 Stack trace: #0 C:\Users\mcgranj\Dropbox\eBay_web\google\quickstart.php(71): Google_Client->fetchAccessTokenWithRefreshToken(NULL) #1 C:\Users\mcgranj\Dropbox\eBay_web\google\quickstart.php(118): getClient() #2 {main} thrown in C:\Users\mcgranj\Dropbox\eBay_web\google\vendor\google\apiclient\src\Google\Client.php on line 258

I have been troubleshooting it all night, following every suggestion I could find:

But I am still having that problem, and it is using the quick start PHP code. I am so frustrated by this. Any guidance and/or suggestions are welcome.

Here is my PHP code:

<?php
require_once __DIR__ . '/vendor/autoload.php';

date_default_timezone_set('America/Chicago');
ini_set('max_execution_time', 0); //indefinite
ini_set('memory_limit','256M'); //increase PHP memory
ini_set('display_errors', 10);

define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', '~/.credentials/gmail-php-quickstart.json');
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');

define('SCOPES', implode(' ', array(
  Google_Service_Gmail::GMAIL_READONLY)
));

function getClient() {
  $client = new Google_Client();
  $client->setApplicationName(APPLICATION_NAME);
  $client->setScopes(SCOPES);
  $client->setAuthConfig(CLIENT_SECRET_PATH);
  $client->setAccessType('offline');

  $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
  if (file_exists($credentialsPath)) {
    $accessToken = json_decode(file_get_contents($credentialsPath), true);
  } else {
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:
%s
", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    if(!file_exists(dirname($credentialsPath))) {
      mkdir(dirname($credentialsPath), 0700, true);
    }
    file_put_contents($credentialsPath, json_encode($accessToken));
    printf("Credentials saved to %s
", $credentialsPath);
  }
  $client->setAccessToken($accessToken);

  if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        $newAccessToken = $client->getAccessToken();
        $accessToken = array_merge($accessToken, $newAccessToken);
        file_put_contents($credentialsPath, json_encode($accessToken));
  }
  return $client;
}

function expandHomeDirectory($path) {
  $homeDirectory = getenv('HOME');
  if (empty($homeDirectory)) {
    $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
  }
  return str_replace('~', realpath($homeDirectory), $path);
}

$client = getClient();
$service = new Google_Service_Gmail($client);

$user = 'me';
$results = $service->users_labels->listUsersLabels($user);

function listMessages($service, $user) {
  $pageToken = NULL;
  $messages = array();
  $opt_param = array();
  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $opt_param['maxResults'] = 5; //Return only 5 messages
      $opt_param['labelIds'] = 'INBOX';
      $opt_param['q'] = "after:2017/07/08 FROM:shipment-tracking@amazon.com";
      $messagesResponse = $service->users_messages->listUsersMessages($user, $opt_param);
      if ($messagesResponse->getMessages()) {
        $messages = array_merge($messages, $messagesResponse->getMessages());
        $pageToken = $messagesResponse->getNextPageToken();
      }
    } catch (Exception $e) {
      print 'An error occurred: ' . $e->getMessage();
    }
  } while ($pageToken);

  foreach ($messages as $message) {
    print 'Message with ID: ' . $message->getId() . '<br/>';
    $id = $message->getId();
    echo "<pre>"; print_r($message); echo "</pre>";
    $gmailurl = "https://www.googleapis.com/gmail/v1/users/".$user."/messages/".$id;
    echo "<a href='$gmailurl' target='_blank'>".$gmailurl."</a><p>";
    $messagePayload = $message->getPayload();
  }

  return $messages;
}

listMessages($service, $user);

?>
  • 写回答

1条回答 默认 最新

  • dongqiao8417 2017-07-10 15:35
    关注

    Based from this thread, make sure that you have called json_encode before writing the auth result to the token.json file. You can fix it by adding json_encode like: file_put_contents($credentialsPath, json_encode($accessToken));. Also, this page suggested to add $client->setAccessType('offline'); and include force prompt to return the refresh token: $client->setApprovalPrompt('force');.

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!