Google 日历 API - PHP

its*_*rty 4 php google-calendar-api google-api google-oauth google-api-php-client

我目前正在将Google Calendar API用于网络应用程序。但是,每小时都会提示我一个链接来验证快速启动访问权限。有谁知道如何解决这一问题?

细节:

  • 我创建了一个新的 Gmail ID:redu@gmail.com
  • redu@gmail.com 有关联的日历
  • 我的基于 php 的 Web 应用程序需要对日历执行以下操作:
  • 为每个注册用户创建一个新日历(作为 redu@gmail.com 的附加日历)
  • 为登录用户创建活动并将另一个注册用户添加为受邀者

我尝试过使用 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);
     }

Run Code Online (Sandbox Code Playgroud)

当我尝试使用 $service 对象创建日历或创建事件时,我收到一条错误消息,指出未设置域范围权限。但是,当我创建服务帐户时,我确实启用了域范围委派。

编辑:

下面是我使用服务帐户密钥创建 Google_Client 并使用客户端为 redu@gmail.com 创建新日历的代码。请注意,我与 reduservice@subtle-breaker-280602.iam.gserviceaccount.com 共享了 redu@gmail.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();
}
Run Code Online (Sandbox Code Playgroud)

错误:

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."
}'
Run Code Online (Sandbox Code Playgroud)

DaI*_*mTo 6

OAUTH2 与服务帐户

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

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

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

带有刷新令牌的 Oauth2 示例。

问题是您的访问令牌即将过期。如果过期,则用户将需要再次授予您的应用程序对其数据的访问权限。为了避免这种情况,我们使用刷新令牌并将其存储在会话变量中,当访问令牌过期时,我们只需请求一个新的令牌。

请注意我如何请求$client->setAccessType("offline"); 这将给我一个刷新令牌。

现在设置会话变量来存储这些数据

    $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();  
Run Code Online (Sandbox Code Playgroud)

然后我可以检查访问令牌是否过期,如果是的话我刷新它

 if ($client->isAccessTokenExpired()) {             
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            $client->setAccessToken($client->getAccessToken());   
            $_SESSION['access_token'] = $client->getAccessToken();                
        }       
Run Code Online (Sandbox Code Playgroud)

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));
    }
Run Code Online (Sandbox Code Playgroud)

认证.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();
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

服务帐户代码

凭证文件不同,请勿混淆。

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();
}
Run Code Online (Sandbox Code Playgroud)

}

错误

客户端未被授权使用此方法检索访问令牌,或者客户端未被授权访问任何请求的范围。

有两种类型的客户端 Oauth2 客户端和服务帐户客户端。您下载的 .json 文件对于每个客户端都不同。您将为每个客户端使用的代码也是如此。您无法互换此代码。

您收到的错误统计信息表明您正在使用的客户端无法用于您正在使用的代码。尝试再次下载服务帐户的客户端密钥 .json。,

  • 应该注意的是,您的环境变量 GOOGLE_APPLICATION_CREDENTIALS 应设置为从服务帐户下载的 .JSON 文件的文件路径。putenv('GOOGLE_APPLICATION_CREDENTIALS=credentials-169991-ac1f887b4f8f.json'); (2认同)