2015-04-21 60 views
0

我希望我的服務器使用php代碼訪問Gmail帳戶。以下是我在網上找到的例子創建的。400使用php訪問Gmail API的錯誤請求

<?php 

session_start(); 

require_once dirname(dirname(__FILE__)) . '/utility/google-api-php-client/src/Google/autoload.php'; 

$json_file_location = 'Gmail-YQXB-7c754a18211a.json'; 

$client = new Google_Client(); 
$service = new Google_Service_Books($client); 
$sgmail = new Google_Service_Gmail($client); 

$scopes = array('https://www.googleapis.com/auth/books', 'https://mail.google.com'); 

if (isset($_SESSION['service_token'])) { 
    $client->setAccessToken($_SESSION['service_token']); 
} 

$cred = $client->loadServiceAccountJson($json_file_location, $scopes); 
$client->setAssertionCredentials($cred); 
if ($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion($cred); 
} 

$_SESSION['service_token'] = $client->getAccessToken(); 

$optParams = array('filter' => 'free-ebooks'); 
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams); 
echo "<h3>Results Of Call:</h3>"; 
foreach ($results as $item) { 
    echo $item['volumeInfo']['title'], "<br /> \r\n"; 
} 

$msg = $sgmail->users_messages->listUsersMessages('me'); 
var_dump($msg); 

?> 

代碼工作除了最後一個請求,這將引發類似:

PHP Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/gmail/v1/users/me/messages : (400) Bad Request' in C:\inetpub\wwwroot\utility\google-api-php-client\src\Google\Http\REST.php:110

$msg = $sgmail->users_messages->listUsersMessages('me'); 

該帳戶是服務帳戶。如果我使用Web應用程序類型的客戶端ID,我可以使其工作。只是不知道這裏出了什麼問題。

+0

您是否已經看到過此貼子? http://stackoverflow.com/questions/29521049/bad-request-while-accesing-gmail-api –

+0

我添加行$ cred-> sub後,它將有刷新OAuth2令牌的錯誤。由於我沒有域名,我只想訪問我自己的gmail用於該項目,我應該使用類型服務帳戶還是其他? – Yiqixueba

回答

1

如果您只想訪問一個帳戶(您自己的帳戶),則不應使用服務帳戶。服務帳戶是他們自己的帳戶,他們不是Gmail帳戶。它們適用於不需要用戶的API(例如地圖,搜索),或者當您使用Google Apps for Work域並希望爲域中的所有用戶啓用授權(通過域管理員,因此您不需要個人用戶授權)。

你想使用標準的oauth2 web認證流程。如果你想確保它可以離線使用(例如通過某些腳本/服務/ cron作業),那麼請確保你在oauth2授權Web流請求中添加離線標誌,並確保你得到一個永久刷新標誌(可以是用於請求訪問令牌)。如果你沒有設置離線,那麼它是一個只有一個小時的訪問令牌。有關更多詳細信息,請參閱https://developers.google.com/gmail/api/auth/web-server

+0

謝謝,我想我現在所擁有的與您的建議相似。我設法讓它與一個Client ID類型的Installed應用程序一起工作。除了第一次,我需要點擊並允許,以獲得刷新令牌。一旦我有刷新令牌,其餘的可以自動完成。 – Yiqixueba

+0

我在$ sgmail-> users_messages-> listUsersMessages('me'); 它顯示錯誤,如致命錯誤:未捕獲異常'Google_Service_Exception',並顯示消息'Error calling GET https://www.googleapis.com/gmail/v1/users/me/messages?key=AIzaSyA-yDBvkPmtQeU_SB3MYHDY8ddrW9Tu_xs:(400)Bad請求 –

相關問題