标签: google-api-php-client

使用OAuth刷新令牌获取新的访问令牌 - Google API

我的应用很简单,它连接到Google+ API以对用户进行身份验证,如果成功,它会检索用户的电子邮件,然后根据检索到的电子邮件对给定数据库执行一系列操作.

我的主要问题是每小时,我的访问令牌都会过期,而我似乎不知道如何"刷新"它.我得到以下错误,我想是预期的:

The OAuth 2.0 access token has expired, and a refresh token is not available.
Run Code Online (Sandbox Code Playgroud)

我目前正在将访问令牌存储在数据库中,因此我可以根据需要进行检索.我唯一的问题是如何使用该令牌获得新的令牌?

php oauth-2.0 google-oauth google-api-php-client

11
推荐指数
1
解决办法
5929
查看次数

Google Cloud API - 应用程序默认凭据

我从Google的文档中修改了以下代码:

        $GOOGLE_APPLICATION_CREDENTIALS = "./[path].json";
        $_ENV["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";
        $_SERVER["GOOGLE_APPLICATION_CREDENTIALS"] = "./[path].json";

        $projectId = "[my project's ID']";
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->setScopes(['https://www.googleapis.com/auth/books']);
        $service = new Google_Service_Books($client);
        $results = $service->volumes->listVolumes('Henry David Thoreau');
Run Code Online (Sandbox Code Playgroud)

然而,当我运行它时,它返回错误:

PHP Fatal error:  Uncaught exception 'DomainException' with message 'Could not load the default credentials. Browse to https://developers.google.com/accounts/docs/application-default-credentials for more information'
Run Code Online (Sandbox Code Playgroud)

我尝试了各种配置,例如更改文件的路径.如你所见,我还完成了我可以立即想到的三种不同形式的变量(两种环境,一种不是).

我不太确定下一步该去哪儿.我应该研究设置环境变量的不同方法,还是应该以不同的方式定义路径?这样做的正确方法是什么?该错误还有其他原因吗?

php google-api google-api-php-client google-cloud-platform

11
推荐指数
2
解决办法
1万
查看次数

Google AnalyticsAPI - 无法在经过身份验证后添加服务

在谷歌控制台中,我为API密钥 - 类型服务器创建了凭据,为类型为其他的Oauth创建了凭据.

对于开发人员密钥,我使用的是API密钥凭证,对于客户端ID /秘密,我使用的是Oauth凭证

我正在使用php sdk进行google analytics api:

$client = new Google_Client();
$client->setApplicationName('Schedule GA');
$client->setAccessType('offline');
$client->setUseObjects(true);

$ganalytics_settings = wp_get_custom_field_for_current_user('ganalytics_settings', 'ga_settings');

$ganalytics_settings['google_api_key'] = 'c0f3d189e82938128ndoea1a426ee4e264e4b0b0';
$ganalytics_settings['google_client_id'] = '17381202384367-gejnedh2aijuq1660f0lvl5uvj6roloo4.apps.googleusercontent.com';
$ganalytics_settings['google_client_secret'] = '**Secret key**';

$client->setClientId("17381202384367-gejnel2aijuq1060f0lvl5uvj6roloo4.apps.googleusercontent.com");
$client->setClientSecret("QclsDKOSLcsrbpJD_KLbIUtQ");
$client->setDeveloperKey("c0f3d189e82938128ndoea1a426ee4e264e4b0b0");
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$analytics = new Google_AnalyticsService($client); //the error occurs here!!!

// Setting Access Token

$access_token = $ganalytics_settings['google_access_token'];
if ($access_token) {
    $client->setAccessToken($access_token);
}
else {
    if ($ganalytics_settings['google_auth_code']) {
        $client->authenticate($ganalytics_settings['google_auth_code']);
        $ganalytics_settings['google_access_token'] = $client->getAccessToken();

        // update_option('ganalytics_settings', $ganalytics_settings);
        ga_settings_exists_else_update();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息:

Cant add services after having authenticated
Run Code Online (Sandbox Code Playgroud)

有什么建议我做错了吗?

感谢您的回复!

php google-analytics google-api google-analytics-api google-api-php-client

11
推荐指数
1
解决办法
279
查看次数

Google登录网站,导致JWT PHP库"签名验证失败"

Google网站登录让我感到非常疯狂......

我正在构建一个简单的Web应用程序,我正在尝试将Google的登录功能集成到网站中(https://developers.google.com/identity/sign-in/web/).

JavaScript看起来相当不错,下一步是验证id_token我使用后端服务器收到的信息(再次,根据Google的建议:https://developers.google.com/identity/sign-in/web/backend- auth).

这是一个基于PHP的Web应用程序,我已经使用composer:成功安装了Google Client API库composer require google/apiclient,但是当我将我的id_token值发布到我的PHP后端系统时,我一直收到以下错误:

Firebase\JWT\SignatureInvalidException
File: .\vendor\firebase\php-jwt\src\JWT.php:112 
Message: Signature verification failed

Stack trace:
#0 .\vendor\google\apiclient\src\Google\AccessToken\Verify.php(103): Firebase\JWT\JWT::decode('eyJhbGciOiJSUzI...', '-----BEGIN PUBL...', Array)
#1 .\vendor\google\apiclient\src\Google\Client.php(712): Google_AccessToken_Verify->verifyIdToken('eyJhbGciOiJSUzI...', '10...')
Run Code Online (Sandbox Code Playgroud)

我还使用了id_tokenGoogle的"tokeninfo"端点(https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=ABC123)上的值,并且id_token验证完美,所以我确定它的id_token值不是错误.它也通过POST变量完美地传递给PHP脚本,所以我有点亏.

这是我的代码:

使用Javascript:

<script src="https://apis.google.com/js/platform.js?onload=googleAppStart" async defer></script>
<script>
    var googleAppStart  = function(){gapi.load('auth2', initGoogleSignIn);};
    var auth            = false;
    function initGoogleSignIn(){
        auth = gapi.auth2.init({
            client_id   : 'client-id-is-here',
            scope       : 'profile'
        });

        auth.attachClickHandler(document.getElementById('my-button'));
        auth.isSignedIn.listen(googleSignInChanged);
        auth.currentUser.listen(googleCurrentUserChanged); …
Run Code Online (Sandbox Code Playgroud)

javascript php google-api-php-client google-signin

11
推荐指数
2
解决办法
1469
查看次数

使用PHP客户端库将大文件上传到Google云端硬盘

我正在尝试通过其PHP客户端库使用Google Drive API来上传大文件.目前它失败了,因为看似可用的唯一方法是"简单"上传方法.不幸的是,这要求您将整个文件作为数据加载,并且它会达到我的php内存限制.我想知道是否有可能,并看看它是如何完成的一个例子.我知道有一种可恢复和chuncked上传的方法,但没有关于如何使用它的文档.

<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';

$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));

$service = new Google_DriveService($client);

$authUrl = $client->createAuthUrl();

//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));

// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);

//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = file_get_contents('document.txt');

$createdFile = $service->files->insert($file, array(
      'data' => $data,
      'mimeType' …
Run Code Online (Sandbox Code Playgroud)

google-drive-api google-api-php-client

10
推荐指数
1
解决办法
4079
查看次数

在两个日期之间获取日历活动

如何获取两个特定日期之间的所有事件.例如,我只想在1st of March 2013&之间获取事件28th of March 2013.

我使用的是Google Calendar API v3.在Google Calendar API v1中,可以使用start-min和start-max在2个日期之间进行搜索.我想知道Google Calendar API v3中这两个参数的替换是什么?

google-calendar-api google-api google-api-php-client

10
推荐指数
1
解决办法
1万
查看次数

使用Google API时,身份验证范围错误不足

我将Google SDK设置为使用Google API和Application Default Credentials.对于我的本地计算机,创建了凭证json文件并将其路径设置GOOGLE_APPLICATION_CREDENTIALS为环境变量.这是按预期工作没有问题.

但是,当应用程序部署到Google Cloud VM时,会引发以下错误:

[Google_Service_Exception]                                             
{                                                                      
    "error": {                                                           
      "code": 403,                                                       
      "message": "Request had insufficient authentication scopes.",      
      "errors": [                                                        
        {                                                                
          "message": "Request had insufficient authentication scopes.",  
          "domain": "global",                                            
          "reason": "forbidden"                                          
        }                                                                
      ],                                                                 
      "status": "PERMISSION_DENIED"                                      
    }                                                                    
}
Run Code Online (Sandbox Code Playgroud)

根据文档,内置服务帐户应与虚拟机实例关联.为了使它工作,我尝试使用凭据json文件,就像我在本地机器上做的那样(工作正常)但它也没有用.

要注意,错误消息是关于范围但不是auth问题.如何使其在Compute Engine VM实例上运行?

给客户端初始化代码:

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Pubsub::PUBSUB);
Run Code Online (Sandbox Code Playgroud)

google-api google-api-client google-compute-engine google-api-php-client

10
推荐指数
1
解决办法
1万
查看次数

刷新oauth2令牌google api和HWIOAuthBundle

我怎么刷新令牌?我使用带有此令牌的Google api - 它可以工作但无法找到如何刷新它,在这个例子中我们不保存过期时间.我需要

`access_type:     offline `
Run Code Online (Sandbox Code Playgroud)

然后

$client = new Google_Client();
        //$client->setClientId($GoogleClientId);
        $client->setApplicationName($GoogleAppName);
        $client->setClientId($this->user->getGoogleId());
        $client->setAccessType('offline');
Run Code Online (Sandbox Code Playgroud)

如果令牌有效,我可以工作但是什么时候过期我试试

$token = [
            'access_token' => $this->user->getGoogleAccessToken(),
            'expires_in'   => (new \DateTime())->modify('-1 year')->getTimestamp(),
        ];
Run Code Online (Sandbox Code Playgroud)

我把它放在任何日期,因为在这个例子中我们不保存过期时间

https://gist.github.com/danvbe/4476697

    $client->setAccessToken($token);

    if($client->isAccessTokenExpired()){

        $refreshedToken = $client->refreshToken($client->getAccessToken());
Run Code Online (Sandbox Code Playgroud)

我有错误

array:2 [?
  "error" => "invalid_request"
  "error_description" => "Could not determine client ID from request."
]
Run Code Online (Sandbox Code Playgroud)

有HwiAuthBundle方法来刷新令牌吗?为什么这不适用于Google_Client刷新?

php google-api symfony google-api-php-client hwioauthbundle

10
推荐指数
1
解决办法
1137
查看次数

如何从Google PHP API有效负载中获取其他范围信息?

我正在努力从Google PHP API获取额外的范围信息.我正在使用它与JavaScript一起获取访问令牌(不确定这是否正确,但它适用于我)

我的页面上有一个Google注册按钮,它连接到以下功能.基本上,它获得一个响应令牌,通过AJAX发送到我的PHP服务器.

gapi.load('auth2', function() {
    // Retrieve the singleton for the GoogleAuth library and set up the client.
    auth2 = gapi.auth2.init({
        client_id: 'XXXX',
        cookie_policy: 'single_host_origin',
        // Requesting additional scopes
        scope: 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/plus.login'
    });

    auth2.attachClickHandler(document.getElementById('google-login-signup'), {},
        function(googleUser) {

            if ( auth2.isSignedIn.get() ) {

                var data = {
                    'action': 'social_google_login',
                    '_nonce': $('#google-login-signup').attr('data-nonce'),
                    'redirect_to': $('#google-login-signup').attr('data-redirect-to'),
                    'token': googleUser.getAuthResponse().id_token
                }

                $.ajax({
                    url: ajax_url,
                    type: 'POST',
                    data: data,
                    success: function(response) {
                        console.log(response);

                        if ( response.success === true ) {
                            window.location.href = response.data.redirect;                  
                        } …
Run Code Online (Sandbox Code Playgroud)

php google-api google-api-php-client

10
推荐指数
1
解决办法
961
查看次数

如何使用存储的刷新令牌获取更新的访问令牌

我正在构建一个应用程序,允许管理员验证对其分析帐户的访问权限以供脱机使用,并将刷新令牌存储在数据库中.

现在,当我尝试在前端使用API​​时,它返回以下错误:

"Access Token Expired. There wan a general error : The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved."
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止生成此错误的代码:

require_once "lib/google/Google_Client.php";
require_once "lib/google/contrib/Google_AnalyticsService.php";

$_analytics = new analytics();
$_googleClient = new Google_Client();
$_googleClient->setClientId($_analytics->gaClientId);
$_googleClient->setClientSecret($_analytics->gaClientSecret);
$_googleClient->setRedirectUri($_analytics->gaRedirectUri);
$_googleClient->setScopes($_analytics->gaScope);
$_googleClient->setAccessType($_analytics->gaAccessType);

// Returns last access token from the database (this works)
$_tokenArray['access_token'] = $_analytics->dbAccessToken($_agencyId);
$_googleClient->setAccessToken(json_encode($_tokenArray));

if($_googleClient->isAccessTokenExpired()) {
    // Don't think this is required for Analytics API V3
    //$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId)); …
Run Code Online (Sandbox Code Playgroud)

php google-analytics-api oauth-2.0 google-api-php-client

9
推荐指数
1
解决办法
1万
查看次数