Php 访问Gmail API时请求错误

Php 访问Gmail API时请求错误,php,google-api-php-client,gmail-api,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

我正在尝试连接到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;
}
您需要添加:

$cred->sub = $userEmail;

在创建$cred之后,其中$userEmail是您试图模拟的用户的电子邮件地址。作为参考,请参阅n,它使用不同的作用域和API调用,但在其他方面类似于您希望对Gmail API执行的操作。

。但是现在刷新OAuth2令牌时出现写入错误,消息:“{错误:未授权的\u客户端,错误描述:请求中未授权的客户端或作用域。}”'听起来你没有在谷歌控制面板中授权客户端id。请参阅我文章中的google drive服务帐户文档。特别是:我按ref进行操作,但没有打开任何内容-只有带有“选择您的帐户”的身份验证表单听起来您不是超级管理员。您确定要在此处使用服务帐户吗?