我目前正在使用 Google Calendar API 作为网络应用程序。但是,每小时都会提示我一个验证快速启动访问的链接。
详情:
[email protected]
的附加日历)我尝试过使用 OAUTH 和服务帐户,但没有成功。
下面是使用服务帐户凭据创建 Google_Client 和 Service 对象的代码
function __construct()
{
Service account based client creation.
$this->client = new Google_Client();
$this->client->setApplicationName("Redu");
$this->client->setAuthConfig(CREDENTIALS_PATH);
$this->client->setScopes([SCOPES]);
$this->client->setSubject('[email protected]');
$this->client->setAccessType('offline');
$this->service = new Google_Service_Calendar($this->client);
}
当我尝试使用
$service
对象创建日历或创建事件时,我收到一条错误消息,指出未设置域范围权限。 但是,当我创建服务帐户时,我确实启用了域范围委派。
下面是我的代码,用于使用服务帐户密钥创建 Google_Client 并使用客户端为 [电子邮件受保护] 创建新日历。请注意,我与 [email protected]
共享了
[电子邮件受保护]的日历,并将权限设置为“管理更改和管理共享”。 我收到的错误位于代码下方:
require (__DIR__.'/../../../vendor/autoload.php');
define('CREDENTIALS_PATH', __DIR__ . '/redu_service_account_credentials.json');
define('SCOPES', Google_Service_Calendar::CALENDAR);
function createNewCalendar($userName) {
//Service account based client creation.
$client = new Google_Client();
$client->setApplicationName("REdu");
// path to the credentials file obtained upon creating key for service account
$client->setAuthConfig(CREDENTIALS_PATH);
$client->setScopes([SCOPES]);
$client->setSubject('[email protected]');
$client->setAccessType('offline');
$service = new Google_Service_Calendar($client);
$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary($userName);
$calendar->setTimeZone('America/Los_Angeles');
$createdCalendar = $service->calendars->insert($calendar);
// Make the newly created calendar public
$rule = new Google_Service_Calendar_AclRule();
$scope = new Google_Service_Calendar_AclRuleScope();
$scope->setType("default");
$scope->setValue("");
$rule->setScope($scope);
$rule->setRole("reader");
// Make the calendar public
$createdRule = $service->acl->insert($createdCalendar->getId(), $rule);
return $createdCalendar->getId();
}
错误:
Fatal error: Uncaught exception 'Google_Service_Exception' with message '{
"error": "unauthorized_client",
"error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
}'
Oauth2 和服务帐户是两个不同的东西。 如果您尝试访问用户数据,请使用 oauth2。您提到的同意窗口将支持并要求他们授予您的应用程序访问其数据的权限。
另一方面,服务帐户是虚拟用户,可以预先批准访问开发人员控制的数据。 您可以与服务帐户共享日历,授予其访问该日历的权限,而无需以与用户相同的方式进行身份验证。
服务帐户永远不会弹出并再次请求访问。
问题是您的访问令牌即将过期。 如果过期,则用户将需要再次授予您的应用程序对其数据的访问权限。为了避免这种情况,我们使用刷新令牌并将其存储在会话变量中,当访问令牌过期时,我们只需请求一个新的令牌。
注意我如何请求
$client->setAccessType("offline");
这会给我一个刷新令牌。
会话变量现在已设置为存储此数据
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
然后我可以检查访问令牌是否过期,如果是的话我刷新它
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* @return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* @return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* @return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* @return A google client object.
*/
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
?>
凭证文件不同,请勿混淆。
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope([YOUR SCOPES HERE]);
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
客户端无权使用此方法检索访问令牌,或者客户端未获得任何请求范围的授权。
有两种类型的客户端:Oauth2 客户端和服务帐户客户端。 您下载的 .json 文件对于每个客户端都不同。 您将为每个客户端使用的代码也是如此。 您无法互换此代码。
您收到的错误统计信息表明您正在使用的客户端无法用于您正在使用的代码。 尝试再次下载服务帐户的客户端密钥 .json。,
这是一个使用服务帐户的 JSON 文件生成身份验证对象的工作示例
$client = new Google\Client();
$client->setApplicationName(APP_NAME);
$client->setAuthConfig(PATH_TO_JSON_FILE);
$client->setScopes(['YOUR_SCOPE1','YOUR_SCOPE2']);
$client->setSubject(EMAIL_OF_PERSON_YOURE_IMPERSONATING);
$client->setAccessType('offline');
$service = new Google_Service_Drive($client);
// Do stuff with the $service object
相关视频:https://youtu.be/-LbGCMCBoLQ?si=Im4y5Gmb8J9pvkGY
您可以在 GCC 中通过转到“帐户”>“创建服务帐户”来转到“服务”来执行此操作。
通过复制/粘贴电子邮件将该服务帐户添加到项目中
通过转到“密钥”>“创建新密钥”来生成 JSON 身份验证配置文件
您可以在 Google Workspace 中执行此操作,方法是转至安全 > 访问和数据控制 > API 控制 > 新建 > 输入您在 GCC 中创建的服务帐号 ID,并指定您希望其具有的范围