Warm tip: This article is reproduced from serverfault.com, please click

Google Calendar API-的PHP

(Google Calendar API - PHP)

发布于 2020-06-17 04:50:42

我目前正在将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);
     }

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

错误:

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."
}'
Questioner
itsMeMoriarty
Viewed
0
2020-06-20 17:12:55

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。