谷歌日历API - PHP

4

我目前正在使用Google日历API开发一个网页应用。然而,每隔一小时,我都会被提示要验证快速启动访问权限链接。有人知道如何解决这个问题吗?

细节如下:

  • 我创建了一个新的gmail id:redu@gmail.com
  • redu@gmail.com关联了一个日历
  • 我的基于PHP的网页应用需要对日历进行以下操作:
  • 为每个注册用户创建一个新的日历(作为redu@gmail.com的附加日历)
  • 为已登录用户创建一个事件,并添加另一个注册用户作为受邀者

我已经尝试使用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('redu@gmail.com');
        $this->client->setAccessType('offline');

        $this->service = new Google_Service_Calendar($this->client);
     }


当我试图使用 $service 对象创建日历或创建事件时,会出现一个错误,提示未设置域宽权限。然而,当我创建服务账号时确实启用了域宽委派。
编辑:
以下是我的代码,使用服务账号密钥创建 Google_Client 并使用客户端为 redu@gmail.com 创建新的日历。请注意,我已经将 redu@gmail.com 的日历与 reduservice@subtle-breaker-280602.iam.gserviceaccount.com 共享,并将权限设置为“管理更改和管理共享”。下面是我收到的错误:
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('redu@gmail.com');
    $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."
}'

您是否拥有一个带有自己域名的GSuite账户或客户账户(Gmail)? - ziganotschka
你可能正在使用服务账户凭据来运行该代码,但是这段代码是用于Oauth2授权的,它无法与服务账户一起工作。我很惊讶它没有直接崩溃。 - Linda Lawton - DaImTo
@ziganotschka,我们没有gsuite账户。redu@gmail.com是一个普通的(我猜是消费者?)账户。 - itsMeMoriarty
@DaImTo 感谢您下面详细的回复。我会尝试您的建议,并与您分享结果。非常感激!对于我的用例,我应该使用服务帐户还是OAuth? - itsMeMoriarty
我更新了我的答案,并回应了你的错误。 - Linda Lawton - DaImTo
如果您没有GSuite帐户,则无法使用具有域范围委派的服务帐户,请参见先决条件。虽然您在技术上可以设置该帐户,但它不会按预期工作,因为要配置它,您需要成为具有域和访问https://admin.google.com/的帐户的管理员。只有GSuite用户才能访问此功能。另请参见[此处](https://developers.google.com/admin-sdk/directory/v1/guides/delegation)和[此处](https://stackoverflow.com/a/30806648/11599789)。 - ziganotschka
2个回答

6

OAUTH2 与服务账户

OAUTH2 和服务账户是两个不同的概念。如果你要访问用户的数据,就需要使用 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();                
        }       

oauth2callback.php

    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));
    }

Authentication.php

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 文件。


1
好的,谢谢!我能够使用服务账户列出与服务账户电子邮件地址共享的日历上的事件。 - itsMeMoriarty
2
需要注意的是,您的环境变量 GOOGLE_APPLICATION_CREDENTIALS 应该设置为从服务帐户下载的 .JSON 文件的文件路径。 putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials-169991-ac1f887b4f8f.json'); - tlorens
非常有帮助,谢谢。在哪里指定服务账户的JSON文件?useApplicationDefaultCredentials()需要以某种方式知道该文件的路径,对吗?谢谢。 - Robert Sinclair

1
这里有一个可用的示例,使用服务账户的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
  1. 在 Google API 控制台中生成服务帐户
  2. 在 Google Workspace 中将域范围授权委派给该服务帐户的客户端 ID,并定义服务帐户将访问的范围
  3. 使用上面的代码,并确保包括一个或多个相关范围

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接