Google API php客户端的授权错误

时间:2014-07-29 12:43:15

标签: php google-api google-drive-api

我尝试使用Google API PHP客户端让我的应用程序以离线方式使用其Google云端硬盘帐户,因为我不希望我的应用程序每次都重定向到谷歌获取授权。

因此,当我第一次连接并使用access_token和refresh_token接收凭据时,我将其备份并尝试每次都使用它。

问题是它在到期之前有效,并且当API客户端尝试刷新访问令牌时,我不断收到此错误:

刷新OAuth2令牌时出错,消息:' {"错误" :" invalid_request"," error_description" :"客户端必须指定client_id或client_assertion,而不是两者都指定" }

我存储的凭据是json格式:

{"的access_token":" XXX"" token_type":"承载"" expires_in":3600 " refresh_token":" XXX,"创建":1406537500}

我的代码(摘自Google教程并进行了一些更改):

function exchangeCode($authorizationCode) {
    try {
        $client = new Google_Client();

        $client->setClientId(self::$clientId);
        $client->setClientSecret(self::$clientSacred);
        $client->setRedirectUri(self::getRedirectURI());
        $_GET['code'] = $authorizationCode;
        return $client->authenticate();
    } catch (Google_AuthException $e) {
        echo 'An Google_AuthException occurred: ' . $e->getMessage();
        throw new CodeExchangeException(null);
    }
}

function getCredentials($authorizationCode, $state='') {
    $emailAddress = '';
    try {
        $credentials = self::exchangeCode($authorizationCode);

        $credentialsArray = json_decode($credentials, true);
         if (isset($credentialsArray['refresh_token'])) {
             self::storeCredentials($credentials);
             return $credentials;
         } else {
            $credentials = self::getStoredCredentials();
             $credentialsArray = json_decode($credentials, true);
             if ($credentials != null &&
                     isset($credentialsArray['refresh_token'])) {
                    return $credentials;
            }
        }
    } catch (CodeExchangeException $e) {
        print 'An CodeExchangeException occurred during code exchange.';
        $e->setAuthorizationUrl(self::getAuthorizationUrl($emailAddress, $state));
        throw $e;
    } catch (NoUserIdException $e) {
        print 'No e-mail address could be retrieved.';
    }

    $authorizationUrl = self::getAuthorizationUrl($emailAddress, $state);
    throw new NoRefreshTokenException($authorizationUrl);
}

function buildService($credentials) {
    $apiClient = new Google_Client();
     $apiClient->setUseObjects(true);
    $apiClient->setAccessToken($credentials);

    return new Google_DriveService($apiClient);
}


function test()
{
    $credentials = self::getStoredCredentials();
    if ( empty($credentials) )
    {
        if (!isset($_GET["code"]))
        {
            header("location:".self::getAuthorizationUrl("xxx@gmail.com", ''));
            die();
        }
        $credentials = self::getCredentials($_GET["code"]);
        echo "NEW: ".$credentials;
    }
    else
    {
        echo "STORED: ".$credentials;
    }

    $service = self::buildService($credentials);




}

当客户端对象尝试根据传递的凭据刷新时,buildService方法中会发生错误。

0 个答案:

没有答案