我已经按照Google文档中的一些步骤介绍了如何使用带有PHP函数的Google Service API。
到目前为止,我已经通过包括Library甚至密钥来做到这一点。最后,我走到了最后一步,但它要求我登录。确切地说,我想在不要求登录的情况下检索我自己的消息,因为我已经有了自己的密码和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文件,但不要选择web或服务,请检查已安装。