Gmail API php listUserMesages()null

时间:2017-03-27 18:08:44

标签: php google-api gmail-api google-api-php-client

我正在使用PHP对Gmail API进行非常基本的测试。我正在使用Google提供的代码(通过OAuth成功授权,然后在API工作台上成功完成代码200测试运行。我的错误是:

  

PHP致命错误:在null

上调用成员函数listUsersMessages()

失败的行:

$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);

完整的代码:

    $userId = 'my gmail id';
    $service = 'my api client id, for example,12356686375';
    $messages = listMessages($service,$userId);
/**
 * Get list of Messages in user's mailbox.
 *
 * @param  Google_Service_Gmail $service Authorized Gmail API instance.
 * @param  string $userId User's email address. The special value 'me'
 * can be used to indicate the authenticated user.
 * @return array Array of Messages.
 */
function listMessages($service, $userId) {
  $pageToken = NULL;
  $messages = array();
  $opt_param = array();
  do {
    try {
      if ($pageToken) {
        $opt_param['pageToken'] = $pageToken;
      }
      $messagesResponse = $service->users_messages->listUsersMessages($userId, $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/>';
  }

  return $messages;
        }        

1 个答案:

答案 0 :(得分:0)

如@Morfinismo所述,$service变量应初始化Gmail服务,而不是客户端ID。

应该是:

// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);

您可以关注此quickstart