Google OAuth 访问令牌未刷新令牌 NULL

Google OAuth access token not refresh token NULL

我试图在我的服务器上获取我的访问令牌以使用 PHP 客户端库中的 GMail API,在我 var_drump 变量之后我得到的只是 NULL我已经通过 getAccessToken(); 方法存储了访问令牌。

知道我做错了什么以便我可以访问令牌吗?

我在 URL 中有一个带有代码参数的有效授权代码,但我不知道为什么在尝试获取访问令牌时我得到的是空值。有什么想法吗?

这是我的代码:

require_once 'vendor/autoload.php';
$redirect_uri = 'https://website.com/m/?mail=tokened';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
var_dump($access_token);

我进一步 google 搜索发现:

我根据该代码尝试了以下操作,因为这是 运行 没有错误的结果,而不是答案中的确切内容,我仍然得到 NULL

这次我尝试在服务器端执行授权代码并从中获取访问令牌,唯一的区别是这次它确实请求访问 gmail 数据的权限。

require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setScopes('https://mail.google.com');
if($_GET['mail']=='approved'){
    $client->setRedirectUri('https://website.com/m/php/googleTokens.php?mail=tokened');
    return header('Location: ' . $client->createAuthUrl());
}
else{
    $client->authenticate($_GET['code']);
    $tokens = $client->getAccessToken();
    var_dump($tokens);
}

让我们确保正确遵循身份验证流程。首先,客户端向 Google 的 OAuth 系统发送身份验证请求,然后 Google returns 一个访问代码,稍后您可以用该代码交换访问令牌。流程逻辑应该是这样的:

require_once 'vendor/autoload.php'; //Include PHP Client Library

//Create client object and set its configuration
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->addScope(array("email", "profile"));

//Check if the access token is already set and if it is, var dump access token
if(isset($_SESSION["access_token"]) && $_SESSION["access_token"] ) {

    $client->setAccessToken($_SESSION['access_token']);

    var_dump($_SESSION['access_token']);

} else { // if access token is not set, authenticate client

  if( !isset($_GET["code"]) ) { // if there is no access code

    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));

  } else { //if there is an access code

    $client->authenticate($_GET['code']); //authenticate client
    $_SESSION['access_token'] = $client->getAccessToken(); //save access token to session
    $redirect_uri = "http://".$_SERVER['HTTP_HOST']."/index.php";
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

  }
}

在运行之前的逻辑,请到myaccount.google.com/permissions and delete the application, then run the above code. Finally, please lets not forget to review the official documentation更详细的解释。在 Whosebug 上也有几个这样的例子,所以我建议也检查一下。希望对您有所帮助!