Bad Request while accesing Gmail API

蓝咒 提交于 2019-12-11 13:43:22

问题


I'm trying to connect to Gmail but server says:

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

I can't seem to find the problem. Here's the code:

$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:


You need to add:

$cred->sub = $userEmail;

right after creating $cred where $userEmail is the email address of the user you are trying to impersonate. For reference, see the Google Drive Service Account documentation which uses a different scope and API call but is otherwise similar to what you'd want to do with Gmail API.



来源:https://stackoverflow.com/questions/29521049/bad-request-while-accesing-gmail-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!