Google PHP API 未返回刷新令牌

Google PHP API not returning refresh token

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

我了解到刷新令牌仅在用户首次登录时返回。在测试时,我撤销了对该帐户的授权,然后再次尝试,但仍然没有给我刷新令牌.我做错了什么?

编辑:我有一个朋友用他的个人 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();
?>

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