访问Gmail API时出现错误请求

时间:2015-04-08 17:08:37

标签: php google-api-php-client gmail-api

我正在尝试连接 Gmail ,但服务器说:

Uncaught exception 'Google_Service_Exception' with message 'Error calling
GET https://www.googleapis.com/gmail/v1/users/{test}%40gmail.com/messages:
(400) Bad Request' in C:\...\google-api-php-client\src\Google\Http\REST.php on line 110

我似乎无法找到问题所在。这是代码:

$google_accounts = $this->getGoogleAccounts();
if (count($google_accounts) > 0) {

    require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/autoload.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Client.php';
    require_once $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/Google/Service/Gmail.php';

    $scopes = array(
        'https://mail.google.com',
        'https://www.googleapis.com/auth/gmail.readonly',
        'https://www.googleapis.com/auth/gmail.modify',
    );
    $key_file_location = $_SERVER['DOCUMENT_ROOT'] . '/include/google-api-php-client/src/keys/';
    foreach ($google_accounts as $one_account) {
        if (!empty($one_account->client_id) && !empty($one_account->service_mail) && !empty($one_account->key_file)) {var_dump($one_account);
            $key = file_get_contents($key_file_location . $one_account->key_file);

            $client = new Google_Client();

            $cred = new Google_Auth_AssertionCredentials($one_account->service_mail, $scopes, $key);
            $client->setAssertionCredentials($cred);
            $client->setClientId($one_account->client_id);
            $client->setAccessType('offline_access');


            $service = new Google_Service_Gmail($client);
            $opt_param = array();
            $messagesResponse = $service->users_messages->listUsersMessages($one_account->login, $opt_param);
            var_dump($messagesResponse);
        }
    }
    return $list;
}
else {
    return false;
}

1 个答案:

答案 0 :(得分:0)

您需要添加:

$cred->sub = $userEmail;

创建$ cred后,其中$ userEmail是您尝试模拟的用户的电子邮件地址。有关参考信息,请参阅Google Drive Service Account documentatio n,它使用不同的范围和API调用,但与您使用Gmail API的操作类似。