Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Gmail API上使用刷新令牌。跟踪旧钥匙 TL;博士_Php_Google Api_Google Oauth_Gmail Api_Google Api Php Client - Fatal编程技术网

Php 在Gmail API上使用刷新令牌。跟踪旧钥匙 TL;博士

Php 在Gmail API上使用刷新令牌。跟踪旧钥匙 TL;博士,php,google-api,google-oauth,gmail-api,google-api-php-client,Php,Google Api,Google Oauth,Gmail Api,Google Api Php Client,这里的问题是,如果不先执行setAccessToken(),我就无法执行fetchAccessTokenWithRefreshToken(),并且为了执行setAccessToken(),我需要知道之前的访问令牌 如果我尝试fetchAccessTokenWithRefreshToken()而不首先调用setAccessToken()我会得到“LogicException:刷新令牌必须传入或设置为setAccessToken的一部分” 如果我尝试仅使用刷新\u令牌值设置AccessToken()

这里的问题是,如果不先执行
setAccessToken()
,我就无法执行
fetchAccessTokenWithRefreshToken()
,并且为了执行
setAccessToken()
,我需要知道之前的访问令牌

如果我尝试
fetchAccessTokenWithRefreshToken()
而不首先调用
setAccessToken()
我会得到“LogicException:刷新令牌必须传入或设置为setAccessToken的一部分”

如果我尝试仅使用
刷新\u令牌值
设置AccessToken()
,它也会失败,因为
令牌格式无效

它工作的唯一方法是提供完整有效的身份验证令牌捆绑包,而不仅仅是刷新令牌。

我正在使用此脚本获取第一次身份验证并生成刷新令牌: 这是可行的,因为我正在向它提供完整的
$token
数组(或者是因为我预先提供了setAccessToken()

    $token = array();
    $token['access_token'] = '<<SCRUBBED_CURRENT_ACCESS_TOKEN>>>';
    $token['expires_in'] = 3599;
    $token['refresh_token'] = '<<SCRUBBED_REFRESH_TOKEN>>';
    $token['created'] = 1587447211;

    // If I leave out ANY of the values above, the token refresh does not work! 

    // omitted some Gmail client configuration and setup. 

    $this->client->setAccessToken($token);

    if ($this->client->isAccessTokenExpired()) {
      $this->accessToken =  $this->client->fetchAccessTokenWithRefreshToken($token);
    }
    else {
      $this->accessToken = $this->client->getAccessToken();
    }
    $this->service = new Google_Service_Gmail($this->client);
这也不起作用(确认
getRefreshToken()
值正常):

无效补助金

表示您正在使用的令牌为invaid或已过期,或者您正在尝试使用一个有效的刷新令牌,该令牌的客户端id和密码未用于创建该令牌。在这种情况下,您正在发送一个对象,并且应该只发送有效的刷新令牌,因为您发送给该方法的值是不正确的

fetchAccessTokenWithRefreshToken
方法接受刷新令牌,而不是对象。只需将刷新令牌传递给它即可

例如:

客户端创建 检查是否过期,必要时刷新。 注 如果您正在获取由另一个脚本保存和创建的刷新令牌,则刷新令牌的系统必须使用相同的客户端id和客户端机密IE(client_secrets.json)才能使用它刷新访问。它不能只是同一项目中的另一个令牌,它必须是相同的机密

将令牌保存到文件夹的完整示例


注意:只有当用户第一次同意您访问他们的数据时,刷新令牌才能保证在第一次调用时返回。google假定您存储了刷新令牌,因此他们不会发送新的刷新令牌。这就是为什么在系统使用存储的刷新令牌自动刷新访问令牌后,才会再次保存访问令牌的原因好的。

谢谢,不幸的是,这返回:``{“error”:“invalid_grant”,“error_description”:“Bad Request”}``确认
$client->getRefreshToken();
正在返回适当的刷新令牌。仍然得到
invalid_grant
error:(好的,实际上我通过删除
setAccessToken()
之前。现在错误是
LogicException:刷新令牌必须传入或设置为setAccessToken
的一部分,我将对此进行研究。再次感谢。您需要发送一个有效的刷新令牌,确定从何处获取刷新令牌,确保其已设置。我认为这就是为什么它会出现这种情况的原因。它正在下降back在现有令牌上。问题是否已用下面的答案解决?如果没有,您能否提供您现在在哪里的信息?请编辑您的问题并添加您正在使用的授权码,以便我们可以看到您从哪里获得刷新令牌。@Kassy不,问题尚未解决。我仍在处理此问题。主要问题是我无法呼叫setAccessToken
的令牌集,就可以使用RefreshToken取消抓取AccessTokenWithRefreshToken,这会导致以下任一问题:
LogicException:刷新令牌必须传入或设置为setAccessToken
的一部分,或者
无效\u grant
@DaimToken我已经用完整的客户端实例化片段编辑了问题并重新编写了添加了一些内容以使其更清楚。我尝试了你的建议,但它不起作用。只有在我已经提供了完整的令牌集的情况下,我才能使用刷新令牌。@emmdee请编辑你的问题并向我们显示你从何处获取刷新令牌。该令牌无效。你从何处获取此令牌?
    $client = new Google_Client();
    $client->setApplicationName('Gmail API PHP Quickstart');
    $client->setScopes(Google_Service_Gmail::GMAIL_MODIFY);
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // This is the REFRESH token
    $token = '1\/\/0dKcfaketokentokentokenfaketoken-L9IriuoNveLzVQ1w4-lPfakeEPn1R1NjcOK2ISE--O1PO1yEtokenr87E';

    // var_dump just for sanity to ensure this returns true
    var_dump($client->isAccessTokenExpired());

    if ($client->isAccessTokenExpired()) {
      var_dump($client->fetchAccessTokenWithRefreshToken($token));
    }
    $token = array();
    $token['access_token'] = '<<SCRUBBED_CURRENT_ACCESS_TOKEN>>>';
    $token['expires_in'] = 3599;
    $token['refresh_token'] = '<<SCRUBBED_REFRESH_TOKEN>>';
    $token['created'] = 1587447211;

    // If I leave out ANY of the values above, the token refresh does not work! 

    // omitted some Gmail client configuration and setup. 

    $this->client->setAccessToken($token);

    if ($this->client->isAccessTokenExpired()) {
      $this->accessToken =  $this->client->fetchAccessTokenWithRefreshToken($token);
    }
    else {
      $this->accessToken = $this->client->getAccessToken();
    }
    $this->service = new Google_Service_Gmail($this->client);
    // Omitted initial Gmail client setup

    if ($this->client->isAccessTokenExpired()) {
      $this->accessToken =  $this->client->fetchAccessTokenWithRefreshToken('<MY_REFRESH_TOKEN');
    }
    else {
      $this->accessToken = $this->client->getAccessToken();
    }
    $this->service = new Google_Service_Gmail($this->client);
$this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
$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());  
if ($client->isAccessTokenExpired()) {
        $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());      
    }
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();
    }
}