我遇到了Gmail API服务帐户的问题,我希望从Gmail API获取我的个人电子邮件,而无需验证Gmail帐户和密码。确实,它可能有兴趣从我的后端代码中获取它们。
我试图实现这个功能但是没有用。
public function list_email()
{
$this->load->library('google');
$client = new Google_Client();
$service = new Google_Service_Gmail($client);
$client->setApplicationName('airxpress-message-api');
$client_email = '867003685660-dk6896nclmfdql86cudt65q2c06f8ooa@developer.gserviceaccount.com';
$private_key = file_get_contents(base_url().G_API.'p12/airxpress-message-api-45eb6393e620.p12');
$scopes = array('https://mail.google.com/');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$credentials->sub = 'notifications-vd@gmail.com';
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}
$messages = array();
try
{
$opt_param['labelIds'] = 'INBOX';
$opt_param['q'] = 'subject:"reservation request"';
$messagesResponse = $service->users_messages->listUsersMessages('me', $opt_param);
if ($messagesResponse->getMessages())
{
$messages = array_merge($messages, $messagesResponse->getMessages());
}
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
print_r($messages);
}
我遇到了这条消息错误:
致命错误:未捕获的异常' Google_Auth_Exception'有消息'错误刷新OAuth2令牌,消息:' {"错误" :" unauthorized_client"," error_description" :"请求中未经授权的客户或范围。" }''
所以,我得到了参考:
https://developers.google.com/api-client-library/php/auth/service-accounts
有谁能告诉我如何解决它?