我已经按照Google的文档中的一些步骤了解了如何使用带有PHP功能的Google Service API。
到目前为止,我已经通过包含图书馆甚至是密钥来完成它。最后我到达最后一步,但它要求我登录。我确实想要在不要求登录的情况下检索我自己的消息,因为我已经拥有自己的密码和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;
}
Out Put:
An error occurred: Error calling GET https://www.googleapis.com/gmail/v1/users/hostplus.cam%40gmail.com/messages: (401) Login Required
答案 0 :(得分:1)
这段代码我帮助你:
$client->setApplicationName('API Project');
$client->setScopes(implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));
$client->setAuthConfigFile('key/client_secret.json');
$client->setAccessType('offline');
您必须生成新的json文件,但不要选择网络或服务,请检查已安装。