我需要一个服务,以操纵一个gmail帐户内的一个项目开发的PHP Symfony.
我发现了这个例子:https://github.com/googleapis/google-api-php-client/blob/main/docs/oauth-server.md,但比帮助更令人困惑.
我写了这段代码:
src/Service/Gmail.php
<?php
namespace App\Service;
use Google\Client;
class Gmail
{
private \Google\Service\Gmail $api;
private function getGoogleClient(): Client
{
$credentialsPath = getenv('GOOGLE_APPLICATION_CREDENTIALS');
if (empty($credentialsPath)) {
throw new \Exception('You need to set env var GOOGLE_APPLICATION_CREDENTIALS');
}
if (!file_exists($credentialsPath)) {
throw new \Exception('Credentials file path ' . getenv('GOOGLE_APPLICATION_CREDENTIALS') . ' set in GOOGLE_APPLICATION_CREDENTIALS does not exist');
}
$client = new Client();
$client->useApplicationDefaultCredentials();
return $client;
}
private function getApi(): \Google\Service\Gmail
{
if (!isset($this->api)) {
$this->api = new \Google\Service\Gmail($this->getGoogleClient());
}
return $this->api;
}
public function getUserMessages($userId): \Google\Service\Gmail\ListMessagesResponse
{
return $this->getApi()->users_messages->listUsersMessages($userId);
}
}
然后,我遵循了Google中为开发人员描述的步骤:
创建一个新项目:https://developers.google.com/workspace/guides/create-project?hl=en
但此时我不知道我需要什么样的凭据:"OAuth客户端ID“还是”服务帐户“?如果我选择"Oauth客户端ID“,我想我必须使用服务器端url的应用程序类型"Web应用程序”?还是我选择了“服务帐户”?
通过服务帐户,我得到了以下错误:
In REST.php line 134:
{
"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.
google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Login Required.",
"domain": "global",
"reason": "required",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "CREDENTIALS_MISSING",
"domain": "googleapis.com",
"metadata": {
"service": "gmail.googleapis.com",
"method": "caribou.api.proto.MailboxService.ListMessages"
}
}
]
}
}
发布于 2022-11-29 16:58:37
您尚未预先授权您的服务帐户委托给您域中的用户。
require_once('../../vendor/autoload.php');
// Some user within your workspace domain
$user_to_impersonate = "your@domain.com";
$sender = $user_to_impersonate;
$to = 'another@domain.com';
$subject = 'Hello';
$messageText = 'How are you doing?';
// The path to your service account credentials goes here.
putenv("GOOGLE_APPLICATION_CREDENTIALS=credentials.json");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setSubject($sender);
$client->setApplicationName("Quickstart");
$client->setScopes(["https://mail.google.com/"]);
$service = new Google_Service_Gmail($client);
https://stackoverflow.com/questions/74617092
复制相似问题