我希望我的服務器使用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,我可以使其工作。只是不知道這裏出了什麼問題。
您是否已經看到過此貼子? http://stackoverflow.com/questions/29521049/bad-request-while-accesing-gmail-api –
我添加行$ cred-> sub後,它將有刷新OAuth2令牌的錯誤。由於我沒有域名,我只想訪問我自己的gmail用於該項目,我應該使用類型服務帳戶還是其他? – Yiqixueba