Google 日历 API - PHP

Google Calendar API - PHP

我目前正在将 Google Calendar API 用于 Web 应用程序。但是,每隔一小时,系统都会提示我 link 以验证快速入门访问权限。有谁知道如何解决这个问题?

详情:

我尝试过使用 OAUTH 和服务帐户,但没有成功。非常感谢任何帮助。

下面是使用服务帐户的凭据创建 Google_Client 和 Srvice 对象的代码

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 并将权限设置为 "Manage Changes and Manage Sharing"。我收到的错误在代码下方:

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."
}'

OAUTH2 与服务帐户

Oauth2 和服务帐户是两个不同的东西。如果您尝试访问用户数据,则使用 oauth2。您提到的同意 window 将支持并要求他们授予您的应用程序访问其数据的权限。

另一方面,服务帐户是虚拟用户,可以预先批准他们访问开发人员控制的数据。您可以与服务帐户共享一个日历,授予它对该日历的访问权限,它不需要以与用户相同的方式进行身份验证。

服务帐户永远不会弹出并再次请求访问。

带有刷新令牌的 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();
}

}

错误

Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

有两种类型的客户端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
  1. 在 Google API 控制台中生成服务帐户
  2. 在 Google 工作区中将域范围内的权限委托给该服务帐户的客户端 ID,并定义该服务帐户将有权访问的范围
  3. 使用上面的代码并确保再包含一个相关范围