首页 文章

Google API oauth2令牌到期了吗?

提问于
浏览
1

我有google api和oauth2令牌的问题 .

有一个应用程序允许通过oauth2令牌与您的谷歌帐户同步联系人/日历 .

当第一次用户想要与他的谷歌帐户连接时,他需要授予访问权限,然后应用程序正在接收已保存的代码/令牌,稍后将用于脱机同步 .

function getClient($app) 
{       
    $client = new Google_Client();
    $client->setAuthConfig("path_to_secret.json");

    switch($app)
    {
        case 'contacts':
        $client->addScope(Google_Service_Script::WWW_GOOGLE_COM_M8_FEEDS);
        $client->addScope(Google_Service_People::USERINFO_EMAIL);
        break;

        case 'calendar':
        $client->addScope(Google_Service_Calendar::CALENDAR);
        break;

        default:
        throw new Exception('API Callback not defined in setup');
    }

    $client->setAccessType('offline'); // offline access
    $client->setIncludeGrantedScopes(true);   // incremental auth
    $client->setRedirectUri(GOOGLE_APP_URL . $app.'/callback.php');
    return $client;
}

(联系人和日历有不同的令牌)

同步脚本:

...
try
{
    $client = getClient('calendar');
    $client->setAccessToken(unserialize($accessToken));
    $http = $client->authorize();

    $service = new Google_Service_Calendar($client);

    ...
}

$ accessToken是一个序列化的字符串,如:

a:5:{s:12:"access_token";s:131:"******token_here********";s:10:"token_type";s:6:"Bearer";s:10:"expires_in";i:3598;s:8:"id_token";s:902:"***id_token****";s:7:"created";i:1505178047;}

This is working for first time and couple more times but after some time(hours) there is an error:

错误:{“error”:{“errors”:[{“domain”:“global”,“reason”:“authError”,“message”:“Invalid Credentials”,“locationType”:“header”,“location” “:”授权“}],”代码“:401,”消息“:”无效的凭据“}}

我做错了什么?

有趣的是,联系人同步始终正常工作(访问令牌具有与日历同步中相同的属性)

1 回答

  • 2

    好的,可以解决 - refresh_token是第一次提供的,所以当我测试它多次时,我没有获得刷新令牌 . 当我撤消https://myaccount.google.com/u/0/permissions中的访问并再次连接时,我也收到了刷新令牌 . 我现在假设它能正常工作

相关问题