gpt4 book ai didi

php - 谷歌日历 API - PHP

转载 作者:行者123 更新时间:2023-12-03 23:06:27 27 4
gpt4 key购买 nike

我目前正在使用 Google Calendar API对于 Web 应用程序。但是,每隔一小时,我都会收到一个链接来验证快速入门访问权限。有谁知道如何解决这一问题?

细节:

  • 我创建了一个新的 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 对象创建日历或创建事件时,我收到一条错误消息,指出未设置域范围的权限。但是,当我创建服务帐户时,我确实启用了域范围的委派。

    编辑:

    下面是我使用服务帐户 key 创建 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."
    }'

    最佳答案

    OAUTH2 与服务帐户
    Oauth2 和服务帐户是两个不同的东西。如果您尝试访问用户数据,请使用 oauth2。您提到的同意窗口将支持并要求他们授予您的应用程序访问其数据的权限。
    另一方面,服务帐户是虚拟用户,可以预先批准他们访问由开发人员控制的数据。您可以与一个服务帐户共享一个日历,授予它访问该日历的权限,它不需要以与用户相同的方式进行身份验证。
    服务帐户永远不会弹出并再次请求访问。
    带有刷新 token 的 Oauth2 示例。
    问题是您的访问 token 即将过期。如果它过期,那么用户将需要再次授予您的应用程序访问其数据的权限。为了避免这种情况,我们使用刷新 token 并将其存储在 session 变量中,当访问 token 过期时,我们只需请求一个新 token 。
    请注意我的请求方式 $client->setAccessType("offline");这会给我一个刷新 token 。
    session 变量现在设置存储此数据

        $_SESSION['access_token'] = $client->getAccessToken();
    $_SESSION['refresh_token'] = $client->getRefreshToken();
    然后后者我可以检查访问 token 是否已过期,如果这样我刷新它
     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 文件因每个客户端而异。就像您将用于每个客户端的代码一样。你不能互换这个代码。
    您正在使用的客户端无法用于您正在使用的代码的统计信息的错误。再次尝试下载服务帐户的客户端 key .json。,

    关于php - 谷歌日历 API - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62421695/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com