I am trying to authenticate a user with the Google API. I start on authstart.php
with this code:
<?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));
?>
After having the user sign in, it redirects to 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();
?>
This should work (I think :/), but it doesn't. I get the following error:
Could someone please help me? The var_dump of the access token is C:\wamp64\www\auth.php:10:null
. I have done a lot of research, but it seems everything is about the refresh token.
EDIT: You can actually view the website (an autoresponder program) hosted on my PC right now here.
I think you are missing the exchange.
$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();
Code ripped from Oauth2Callback.php