搜索
首页后端开发php教程使用 Google Analytics API 刷新令牌时如何解决'invalid_grant”错误?

How to Resolve

使用 Google API 客户端刷新令牌

在使用 Google Analytics API (V3) 时,用户可能会遇到错误,特别是在尝试检索时来自测试帐户以外的帐户的数据。此问题通常表现为 403 错误。另外,即使撤销并重新验证令牌后,问题也可能会在令牌过期时重新出现。

为了解决这个问题,解决方案是利用refreshToken方法来获取新的验证令牌。但是,执行 $client->refreshToken(refresh_token_key) 可能会产生无效授予错误消息(“error”:“invalid_grant”)。

在研究refreshToken方法背后的代码后,很明显以下内容参数已发送正确:

  • client_id
  • client_secret
  • refresh_token
  • grant_type(硬编码为refresh_token)

令牌刷新的过程如下如下:

$client = new apiClient();
$client->setClientId($config['oauth2_client_id']);
$client->setClientSecret($config['oauth2_client_secret']);
$client->setRedirectUri($config['oauth2_redirect_uri']);
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setState('offline');

$client->setAccessToken($config['token']); // The access JSON object.

$client->refreshToken($config['refreshToken']); // Will return error here

解决问题的关键是理解身份验证时获得的初始令牌拥有刷新令牌。虽然初始令牌会在一小时内过期,但可以利用刷新令牌来获取新令牌。但是,请务必注意,此临时令牌也会在一小时后过期,并且没有关联的刷新令牌。因此,要检索新的临时令牌,必须使用初始令牌的刷新令牌。

为了清楚起见,以下代码提供了详细说明:

// Retrieve original token from database
$tokenquery = "SELECT * FROM token WHERE type='original'";
$tokenresult = mysqli_query($cxn, $tokenquery);
if ($tokenresult != 0) {
    $tokenrow = mysqli_fetch_array($tokenresult);
    extract($tokenrow);
}
$time_created = json_decode($token)->created;
$t = time();
$timediff = $t - $time_created;

$refreshToken = json_decode($token)->refresh_token;

// Initialize Google client
$client = new Google_Client();
$client->setApplicationName('');
$client->setScopes(array());
$client->setClientId('');
$client->setClientSecret('');
$client->setRedirectUri('');
$client->setAccessType('offline');
$client->setDeveloperKey('');

// Refresh token if expired
if (($timediff > 3600) && ($token != '')) {
    $refreshquery = "SELECT * FROM token WHERE type='refresh'";
    $refreshresult = mysqli_query($cxn, $refreshquery);

    // If refresh token exists
    if ($refreshresult != 0) {
        $refreshrow = mysqli_fetch_array($refreshresult);
        extract($refreshrow);
        $refresh_created = json_decode($token)->created;
        $refreshtimediff = $t - $refresh_created;

        // If refresh token is also expired
        if ($refreshtimediff > 3600) {
            $client->refreshToken($refreshToken);
            $newtoken = $client->getAccessToken();
            $tokenupdate = "UPDATE token SET token='$newtoken' WHERE type='refresh'";
            mysqli_query($cxn, $tokenupdate);
            $token = $newtoken;
            echo "refreshed again";
        } else {
            $client->setAccessToken($token);
            echo "use refreshed token but not time yet";
        }
    } else {
        $client->refreshToken($refreshToken);
        $newtoken = $client->getAccessToken();
        $tokenupdate = "INSERT INTO token (type, token) VALUES ('refresh', '$newtoken')";
        mysqli_query($cxn, $tokenupdate);
        $token = $newtoken;
        echo "refreshed for first time";
    }
}

// If token is still valid
if (($timediff setAccessToken($token);
}

$service = new Google_DfareportingService($client);

以上是使用 Google Analytics API 刷新令牌时如何解决'invalid_grant”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
高流量网站的PHP性能调整高流量网站的PHP性能调整May 14, 2025 am 12:13 AM

TheSecretTokeEpingAphp-PowerEdwebSiterUnningSmoothlyShyunderHeavyLoadInVolvOLVOLVOLDEVERSALKEYSTRATICES:1)emplactopCodeCachingWithOpcachingWithOpCacheToreCescriptexecution Time,2)使用atabasequercachingCachingCachingWithRedataBasEndataBaseLeSendataBaseLoad,3)

PHP中的依赖注入:初学者的代码示例PHP中的依赖注入:初学者的代码示例May 14, 2025 am 12:08 AM

你应该关心DependencyInjection(DI),因为它能让你的代码更清晰、更易维护。1)DI通过解耦类,使其更模块化,2)提高了测试的便捷性和代码的灵活性,3)使用DI容器可以管理复杂的依赖关系,但要注意性能影响和循环依赖问题,4)最佳实践是依赖于抽象接口,实现松散耦合。

PHP性能:是否可以优化应用程序?PHP性能:是否可以优化应用程序?May 14, 2025 am 12:04 AM

是的,优化papplicationispossibleandessential.1)empartcachingingcachingusedapcutorediucedsatabaseload.2)优化的atabaseswithexing,高效Quereteries,and ConconnectionPooling.3)EnhanceCodeWithBuilt-unctions,避免使用,避免使用ingglobalalairaiables,并避免使用

PHP性能优化:最终指南PHP性能优化:最终指南May 14, 2025 am 12:02 AM

theKeyStrategiestosiminificallyBoostphpapplicationPermenCeare:1)useOpCodeCachingLikeLikeLikeLikeLikeCacheToreDuceExecutiontime,2)优化AtabaseInteractionswithPreparedStateTemtStatementStatementSandProperIndexing,3)配置

PHP依赖注入容器:快速启动PHP依赖注入容器:快速启动May 13, 2025 am 12:11 AM

aphpdepentioncontiveContainerIsatoolThatManagesClassDeptions,增强codemodocultion,可验证性和Maintainability.itactsasaceCentralHubForeatingingIndections,因此reducingTightCightTightCoupOulplingIndeSingantInting。

PHP中的依赖注入与服务定位器PHP中的依赖注入与服务定位器May 13, 2025 am 12:10 AM

选择DependencyInjection(DI)用于大型应用,ServiceLocator适合小型项目或原型。1)DI通过构造函数注入依赖,提高代码的测试性和模块化。2)ServiceLocator通过中心注册获取服务,方便但可能导致代码耦合度增加。

PHP性能优化策略。PHP性能优化策略。May 13, 2025 am 12:06 AM

phpapplicationscanbeoptimizedForsPeedAndeffificeby:1)启用cacheInphp.ini,2)使用preparedStatatementSwithPdoforDatabasequesies,3)3)替换loopswitharray_filtaray_filteraray_maparray_mapfordataprocrocessing,4)conformentnginxasaseproxy,5)

PHP电子邮件验证:确保正确发送电子邮件PHP电子邮件验证:确保正确发送电子邮件May 13, 2025 am 12:06 AM

phpemailvalidation invoLvesthreesteps:1)格式化进行regulareXpressecthemailFormat; 2)dnsvalidationtoshethedomainhasavalidmxrecord; 3)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用