【问题标题】:Error connecting Google Service API to retrieve message with end-user连接 Google Service API 以检索最终用户的消息时出错
【发布时间】:2015-09-10 02:43:40
【问题描述】:

我已经按照 Google 文档中关于如何将 Google Service API 与 PHP 函数一起使用的一些步骤进行操作。

到目前为止,我已经通过包括库甚至密钥来做到这一点。最后我到达最后一步,但它要求我登录。正是我想在不要求登录的情况下检索自己的消息,因为我已经有了自己的密码和 gmail 帐户。

我的代码有什么问题?你能告诉我吗?

 public function retrieving_message()
        {
            $client_id  = '10521XXXX456-XXXXX.apps.googleusercontent.com'; //Client ID
            $client_email = '1XXXXX56244-XXXX@developer.gserviceaccount.com'; //Email Address
            $key_file_location = 'API Project-0f1afd2a0615.p12'; //key.p12
            $this->load->library('google');
            $client = new Google_Client();

            // Replace this with your application name.
            $client->setApplicationName("API Project");
            // Replace this with the service you are using.

            // We only need permissions to compose and send emails
            // $client->addScope("https://www.googleapis.com/auth/gmail.readonly");
            $service = new Google_Service_Gmail($client);

            $this->listMessages($service, 'hXXtpluXXXX.cam@gmail.com');

        }

获取消息的代码:

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;
    }

输出:

An error occurred: Error calling GET https://www.googleapis.com/gmail/v1/users/hostplus.cam%40gmail.com/messages: (401) Login Required

【问题讨论】:

  • 对于服务帐户,您是否对服务帐户进行了域范围的委派? developer.google.com/identity/protocols/OAuth2ServiceAccount。当您未授权您的服务帐户访问数据时,会发生此错误。检查此链接 code.google.com/p/google-api-php-client/source/browse/trunk/... 以获取服务帐户中的示例 php 代码。检查此链接stackoverflow.com/questions/24779138/…

标签: php google-api gmail gmail-api


【解决方案1】:

这段代码对你有帮助:

$client->setApplicationName('API Project');
        $client->setScopes(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));

        $client->setAuthConfigFile('key/client_secret.json');


        $client->setAccessType('offline');

你必须生成新的json文件但不要选择web或service,请检查已安装。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-25
    • 2018-03-16
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2021-05-16
    相关资源
    最近更新 更多