Google PHP API未返回刷新令牌

时间:2017-04-04 18:36:53

标签: php google-api-php-client

我正在开发一个Web应用程序,其中包括读取已登录用户的gmail。我正在使用Google PHP库来处理身份验证,我可以毫无问题地获取电子邮件。问题是访问令牌在1小时后到期。文档表明您应该获得具有初始授权的刷新令牌,但是当我调用$client->getRefreshToken()时,它将返回null。

我知道刷新令牌仅在用户第一次登录时返回。在测试时,我撤销了帐户上的授权,然后再次尝试,但它仍然没有给我刷新令牌。我做错了什么?

编辑:我有一位朋友使用他的个人Google帐户登录,该帐户从未在网站上使用,但仍未提供刷新令牌。

源代码:

Login.php:第一页

<?php
session_start();
require_once 'vendor/autoload.php';
$force=(isset($_GET['force'])&&$_GET['force']='true');
if(!isset($_SESSION['google_token'])||force)
{
    $client=new Google_Client();
    $client->setAuthConfig('/path/to/client_secret.json');
    $client->addScope('https://www.googleapis.com/auth/gmail.readonly');
    $client->addScope('https://www.googleapis.com/auth/userinfo.email');
    $client->addScope('https://www.googleapis.com/auth/userinfo.profile');
    $client->setState('offline'); //I realized that the mistake is here, see my answer below.
    $client->setApprovalPrompt('force');
    if($force)
            $client->setPrompt('consent');
    $client->setRedirectUri('https://example.com/doLogin.php');

    $auth_url=$client->createAuthUrl();
    header("Location: " . filter_var($auth_url, FILTER_SANITIZE_URL));
    die();
}
header('location: /index.php');
die();

doLogin.php:Google Oauth页面重定向到这里。

<?php
session_start();
require_once 'vendor/autoload.php';
if(isset($_GET['error']))
{
    session_unset();
    header('location: /error.php?error='.urlencode('You must be signed into Google to use this program.'));
    die();
}
$client=new Google_Client();
$client->setAuthConfig('/path/to/client_secret.json');
$client->setRedirectUri('https://example.com/doLogin.php');
$client->setAccessType('offline');
$client->authenticate($_GET['code']);
$access_token=$client->getAccessToken();
$refresh_token=$client->getRefreshToken();

$service=new Google_Service_Oauth2($client);
$email=$service->userinfo->get()['email'];
$_SESSION['email']=strtolower($email);

$_SESSION['access_token']=$access_token;
$_SESSION['refresh_token']=$refresh_token;
header('Location: /index.php');
die();
?>

1 个答案:

答案 0 :(得分:1)

好的,所以在环顾四周,并查看原始的http之后,我发现了自己的错误。我正在调用$client->setState('offline');而不是$client->setAccessType('offline');我修复了它,现在我正在接收刷新令牌。

相关问题