【问题标题】:Google PHP API not returning refresh token谷歌 PHP API 不返回刷新令牌
【发布时间】:2017-04-04 18:36:53
【问题描述】:

我正在开发一个 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();
?>

【问题讨论】:

  • 你是在localhost中使用的吗?
  • 您可能会觉得这很有用:stackoverflow.com/questions/9241213/… 并阅读 cmets 以获得最受好评的答案,因为这也有一个很好的提示。
  • 这是在我的开发服务器上。
  • @Zeke 我查看了 cmets,没有看到任何我认为可以解决问题的方法,尽管很高兴知道。
  • 我的意思是,不仅仅是 cmets,还要阅读更重要的答案。它确实解释了如何正确刷新令牌!

标签: php google-api-php-client


【解决方案1】:

好的,所以在环顾四周并浏览原始http之后,我发现了我的错误。我打电话给$client-&gt;setState('offline'); 而不是$client-&gt;setAccessType('offline'); 我解决了这个问题,现在我应该收到刷新令牌。

【讨论】:

    猜你喜欢
    • 2014-03-31
    • 1970-01-01
    • 2021-05-06
    • 2017-04-19
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-11
    相关资源
    最近更新 更多