Php Google日历API-刷新令牌-刷新令牌必须作为setAccessToken的一部分传入或设置

Php Google日历API-刷新令牌-刷新令牌必须作为setAccessToken的一部分传入或设置,php,google-api,google-calendar-api,google-api-php-client,Php,Google Api,Google Calendar Api,Google Api Php Client,我正在成功读取日历事件,但当访问令牌过期时,我无法刷新它。到目前为止,我一直在获得一个新的访问令牌,但这似乎不正确。我宁愿适当地刷新它 我收到这个错误: 刷新令牌必须作为setAccessToken的一部分传入或设置 从events.php function GetEvents() { $client = new \Google_Client(); $credentialsPath = '/cfg/GoogleClientSecret.json'; $client-&

我正在成功读取日历事件,但当访问令牌过期时,我无法刷新它。到目前为止,我一直在获得一个新的访问令牌,但这似乎不正确。我宁愿适当地刷新它

我收到这个错误:

刷新令牌必须作为setAccessToken的一部分传入或设置

从events.php

function GetEvents()
{
    $client = new \Google_Client();

    $credentialsPath = '/cfg/GoogleClientSecret.json';

    $client->setAuthConfig($credentialsPath);
    $client->addScope(\Google_Service_Calendar::CALENDAR_READONLY);
    $client->setAccessType('offline');

    if (isset($_SESSION['access_token']) && $_SESSION['access_token']) 
    {
        $client->setAccessToken($_SESSION['access_token']);
        if ($client->isAccessTokenExpired()) 
        {
            $refreshTokenSaved = $client->getRefreshToken();

            /**** This line fails ****/
            $client->fetchAccessTokenWithRefreshToken($refreshTokenSaved); 
            /*************************/

            $accessTokenUpdated = $client->getAccessToken();

            $accessTokenUpdated['refresh_token'] = $refreshTokenSaved;

            //Need to do more here once i have the new access token.
        }

        ReadThroughEvents($client);
   }
   else
   {
        $redirect_uri = 'oauthcallback.php';        
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
   }
oauthcallback.php

require 'google-api-php-client-2.4.0 2/vendor/autoload.php';

session_start();

$client = new \Google_Client();
$client->setAuthConfigFile('/cfg/GoogleClientSecret.json');

$callbackuri = 'oauthcallback.php';

$client->setRedirectUri($callbackuri);
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);

if (! isset($_GET['code'])) 
{
   $auth_url = $client->createAuthUrl();
   header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
else
{
     $client->authenticate($_GET['code']);
     $_SESSION['access_token'] = $client->getAccessToken();

     $redirect_uri = 'events.php';
     header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}

fetchAccessTokenWithRefreshToken应在假设您发送的刷新令牌实际上是一个刷新令牌且不为null或其他情况下工作。我会把它打印出来,这样你就可以看到它实际上是一个值

这是我的密码


fetchAccessTokenWithRefreshToken应在假设您发送的刷新令牌实际上是一个刷新令牌且不为null或其他情况下工作。我会把它打印出来,这样你就可以看到它实际上是一个值

这是我的密码


谢谢我想我可以看到我需要做什么——在我第一次设置访问令牌时获取刷新令牌。但是,它不会返回刷新令牌。我想这是因为,我读到这只是第一次发送。我找不到那篇帖子,但我认为它是关于取消对该应用程序的访问。您知道如何执行此操作吗?刷新令牌仅在您第一次对用户进行身份验证时返回。你需要保存它。将其保存到数据库或文件中由您决定。要立即获得一个,您必须撤销用户对您的应用程序的访问权限,并再次请求它。您需要再次弹出“同意”屏幕,要求您授予对其日历帐户的访问权限。如何撤消用户的访问权限?这个在吗?谢谢-我已经设法得到了一个刷新令牌。我正在存储它,现在需要等待我的访问令牌到期才能进行测试。如果一切顺利,我一定会记下答案。谢谢你的帮助。我想我可以看到我需要做什么——在我第一次设置访问令牌时获取刷新令牌。但是,它不会返回刷新令牌。我想这是因为,我读到这只是第一次发送。我找不到那篇帖子,但我认为它是关于取消对该应用程序的访问。您知道如何执行此操作吗?刷新令牌仅在您第一次对用户进行身份验证时返回。你需要保存它。将其保存到数据库或文件中由您决定。要立即获得一个,您必须撤销用户对您的应用程序的访问权限,并再次请求它。您需要再次弹出“同意”屏幕,要求您授予对其日历帐户的访问权限。如何撤消用户的访问权限?这个在吗?谢谢-我已经设法得到了一个刷新令牌。我正在存储它,现在需要等待我的访问令牌到期才能进行测试。如果一切顺利,我一定会记下答案。谢谢你的帮助。
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));
}
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();
    }
}