【问题标题】:Bad Request while accesing Gmail API访问 Gmail API 时出现错误请求
【发布时间】:2015-06-13 18:55:58
【问题描述】:

我正在尝试连接到 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;
}

【问题讨论】:

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


    【解决方案1】:

    你需要添加:

    $cred->sub = $userEmail;
    

    在创建 $cred 之后,其中 $userEmail 是您尝试模拟的用户的电子邮件地址。如需参考,请参阅 Google Drive Service Account documentation,它使用不同的范围和 API 调用,但在其他方面与您希望使用 Gmail API 执行的操作类似。

    【讨论】:

    • ..but now write Error refresh the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }'
    • 听起来您没有在 Google 控制面板中授权客户端 ID。请参阅我的帖子中的 google drive 服务帐户文档。
    • 我通过 ref 去,但什么都没有打开 - 只有带有“选择您的帐户”的身份验证表单
    • 听起来你不是超级管理员。您确定要在此处使用服务帐号吗?
    猜你喜欢
    • 1970-01-01
    • 2019-09-22
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多