GAPI访问令牌null?

时间:2018-04-02 23:44:05

标签: php google-api google-oauth gmail-api google-api-php-client

我正在尝试使用Google API对用户进行身份验证。我使用以下代码开始authstart.php

<?php

require_once "gapi/vendor/autoload.php";

$client = new Google_Client();
$client->setAuthConfig("secret.json");
$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->addScope("https://mail.google.com/");
$client->setRedirectUri("http://" . $_SERVER["HTTP_HOST"] . "/auth.php");
$auth_url = $client->createAuthUrl();
header("Location: " . filter_var($auth_url, FILTER_SANITIZE_URL));

?>

让用户登录后,会重定向到auth.php:

<?php

require_once "gapi/vendor/autoload.php";

$client = new Google_Client();
$client->setAccessType("offline");
$client->authenticate($_GET['code']);
$client->setApprovalPrompt("force");
$access_token = $client->getAccessToken();
var_dump($access_token);
$client->setAccessToken($access_token);
$oauth2 = new Google_Service_Oauth2($client);
$userInfo = $oauth2->userinfo->get();

?>

这个应该工作(我认为:/),但事实并非如此。我收到以下错误: enter image description here
有人可以帮帮我吗?访问令牌的var_dump为C:\wamp64\www\auth.php:10:null。我做了很多研究,但似乎一切都与刷新令牌有关。

编辑:您现在可以查看我的电脑上托管的网站(自动回复程序)here

1 个答案:

答案 0 :(得分:2)

我认为你错过了交流。

$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();    

代码摘自Oauth2Callback.php