连接 Google 服务 API 以检索与最终用户的消息时出错

Error connecting Google Service API to retrieve message with end-user

我已经按照 Google 文档中的一些步骤,了解如何使用 Google 服务 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

这段代码对你有帮助:

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

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


        $client->setAccessType('offline');

您必须生成新的 json 文件但不要选择网络或服务,请检查已安装。