Google Access Token Empty - php

I tried in codeigniter.
Below I put this code in a construct
$this->google = new Google_Client();
$this->google->setClientId(GOOGLEID);
$this->google->setClientSecret(GOOGLESECRET);
$this->google->setDeveloperKey(GOOGLEAPIKEY);
$objOAuthService = new Google_Service_Oauth2($this->google);
then in a method1 I put the below
$this->google->setRedirectUri(site_url('auth/google-login?'));
$this->google->addScope("email");
$this->google->addScope("profile");
$data['content_data']['google_login_url'] = $this->google->createAuthUrl();
$this->load->view("test", $data);
then in method2 I put the below
if (isset($_GET['code'])) {
$this->google->authenticate($_GET['code']);
$token = $this->google->getRefreshToken();
echo $token;
}
You can see that I tried to print the $token but it's empty.
My Question is WHY is it empty?
EDIT:
echo $this->google->getAccessToken();
Even the getAccessToken returns empty.

I just fixed it.
My Solution is that in the construct I have
$this->google = new Google_Client();
$this->google->setClientId(GOOGLEID);
$this->google->setClientSecret(GOOGLESECRET);
$this->google->setDeveloperKey(GOOGLEAPIKEY);
$this->google->setRedirectUri(site_url('auth/google-login?'));
$this->google->addScope("email");
$this->google->addScope("profile");
in method1 I only have this
$data['content_data']['google_login_url'] = $this->google->createAuthUrl();
$this->load->view("test", $data);
and in method2 I have this
if (isset($_GET['code'])) {
$this->google->authenticate($_GET['code']);
$token = $this->google->getAccessToken();
var_dump($token);
}
and here the $token already now has value

Here is the working code which I'm using in Laravel and Codeigniter.
// Initial config
$client = new Google_Client();
$client->setApplicationName(APP_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes(array(SCOPE_A));
// To retrieve refresh token forcefully
// This will ask for permission everytime.
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
// Return url data part
if (isset($_GET['code'])) {
// Log the user in
$client->authenticate($_GET['code']);
// Get acess token and refresh token
$getAccesToken = $client->getAccessToken();
$getRefreshToken = $client->getRefreshToken();
}
else
{
// Return to login
$googleAuthUrl = $client->createAuthUrl();
// Redirect user to authentication URI
}
I hope this helps.

Related

How do i refresh google token if expired?

I am Creating YouTube Broadcast and it successfully working.
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
// $client->refreshToken($accessToken);
// // $client->refreshToken($accessToken);
// $newToken = $client->getAccessToken();
// echo "new token : ". $newToken;
$client->setAccessToken($accessToken);
try {
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
// Define the $liveBroadcast object, which will be uploaded as the request body.
$liveBroadcast = new Google_Service_YouTube_LiveBroadcast();
// Add 'contentDetails' object to the $liveBroadcast object.
$liveBroadcastContentDetails = new Google_Service_YouTube_LiveBroadcastContentDetails();
$liveBroadcastContentDetails->setEnableClosedCaptions(true);
$liveBroadcastContentDetails->setEnableContentEncryption(true);
$liveBroadcastContentDetails->setEnableDvr(true);
$liveBroadcastContentDetails->setRecordFromStart(true);
$liveBroadcastContentDetails->setStartWithSlate(true);
$liveBroadcast->setContentDetails($liveBroadcastContentDetails);
// Add 'snippet' object to the $liveBroadcast object.
$liveBroadcastSnippet = new Google_Service_YouTube_LiveBroadcastSnippet();
$liveBroadcastSnippet->setScheduledStartTime($start_date_time);
$liveBroadcastSnippet->setTitle($class_name);
$liveBroadcast->setSnippet($liveBroadcastSnippet);
// Add 'status' object to the $liveBroadcast object.
$liveBroadcastStatus = new Google_Service_YouTube_LiveBroadcastStatus();
$liveBroadcastStatus->setPrivacyStatus('unlisted');
$liveBroadcast->setStatus($liveBroadcastStatus);
$response = $service->liveBroadcasts->insert('snippet,contentDetails,status', $liveBroadcast);
return ($response->id);
} catch (Google_Service_Exception $e) {
print_r($e);
} catch (Google_Exception $e) {
print_r($e);
}
but after some time Authorization failed.
token has been expired and unable to create broadcast.
I tried to refresh token but not working please help.
https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert?apix=true[][1]
First make sure to request offline access this will return a refresh token to you
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
return $client;
}
The first time the user authorizes you should have a refresh token in returned. Store it some place.
$client->getRefreshToken()
Make sure that you load the refresh token inside the $client->setRefreshtoken($stored) so that it has it for the next part.
Then check if the access token has expired and add the refresh token back and force a fetch of a new access token.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
}

Oauth 2 $client->getAccessToken() Returns Null value

I am using codeigniter MVC framework for signing in to my site using google client library. Everything is working fine except $client->getAccessToken() when google redirects with code and I do the following code. $client->getAccessToken() return null value. Here is my code for controller function one. In this function I set my credentials to create authUrl.
public function login()
{
// Include two files from google-php-client library in controller
include_once APPPATH . 'third_party/google-api-php-client/vendor/autoload.php';
// Store values in variables from project created in Google Developer Console
$client_id = 'XXXXXX';
$client_secret = 'XXXXX';
$redirect_uri = 'path/to/mysite/login/loginGoogle';
$simple_api_key = 'XXXXXXX';
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("mysite");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$authUrl = $client->createAuthUrl();
$data['authUrl'] = $authUrl;
$this->load->view('login',$data);
}
And after that when google authenticate and redirects to my redirect uri which is an other controller function which is given below. and problem is in this function.
public function loginGoogle()
{
// Include two files from google-php-client library in controller
include_once APPPATH . 'third_party/google-api-php-client/vendor /autoload.php';
$client_id = 'XXXXXX';
$client_secret = 'XXXXX';
$redirect_uri = 'path/to/mysite/login/loginGoogle';
$simple_api_key = 'XXXXXXX';
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("mysite");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if(!isset($_SESSION['access_token'])){
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$token = $client->getAccessToken();
$_SESSION['access_token'] = $token;
print_r($this -> session -> userdata());exit;
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
// Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$data['userData'] = $userData;
$_SESSION['access_token'] = $client->getAccessToken();
}}
here in second function getAccessToken return nothing and google throws expection.
It looks like you never get the refresh token. There are two different tokens, the access token expires every few hours or so, but the refresh token is only sent the one time when the redirect asks the user for permission. It needs to be stored somewhere secure and is used in the future to refresh the access token.
Here's what my codeigniter code looks like to access the Google API (this would replace your if statements in the loginGoogle function:
if($refresh_token_accessed_from_my_database) {
//If session contains no valid Access token, get a new one
if ($client->isAccessTokenExpired()) {
$client->refreshToken($refresh_token_accessed_from_my_database);
}
//We have access token now, launch the service
$this->service = new Google_Service_Calendar($client);
}
else {
//User has never been authorized, so let's ask for the ok
if (isset($_GET['code'])) {
//Creates refresh and access tokens
$credentials = $client->authenticate($_GET['code']);
//Store refresh token for further use
//I store mine in the DB, I've seen others store it in a file in a secure place on the server
$refresh_token = $credentials['refresh_token'];
//refresh_token->persist_somewhere()
//Store the access token in the session so we can get it after
//the callback redirect
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!isset($_SESSION['access_token'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$this->service = new Google_Service_Calendar($client);
}
If you are running on PLESK you might want to change the permission on /var/lib/php/session to 1777.
chmod 1777 /var/lib/php/sessions

How to use the Google book api with a web application

I'm using google book api for my web app. After setting up environment I ran the following code :
<?php
session_start();
require_once dirname(__FILE__).'/GoogleClientApi/Google_Client.php';
require_once dirname(__FILE__).'/GoogleClientApi/contrib/Google_AnalyticsService.php';
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key
// $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
echo 'Hello, world.';
I have followed this link: http://enarion.net/programming/php/google-client-api/google-client-api-php/
But I'm getting SSL connection error. I have saved the project folder in htDocs of xxamp.

GMail API Oauth Zend framework token refresh php

i am in the situation that i have to use the zend framework along with oauth 2 for gmail.
all works fine and i get the messages and login just fine, my problem is that the token expire too fast.
am i able to set it so it will never expire or how should i implement a refresh token to the framework ? i use standard code when it comes to login.
what i basically need is an access-token that does not expire or a guide for how to implement a refresh token and how to use it in a program.
any help is appreciated.
thank you.
this is the login page.
include("../classes/Google/Client.php");
$client_id = "hidden";
$client_secret = "hidden";
$redirect_uri = "hidden";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
$client->addScope("https://www.googleapis.com/auth/userinfo.profile");
$client->addScope("https://mail.google.com/");
$client->setRedirectUri($redirect_uri);
$authUrl = $client->createAuthUrl();
echo "Login";
this is the callback
$client_id = "hidden";
$client_secret = "hidden";
$redirect_uri = "hidden";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
session_start();
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$oauth2 = new Google_Service_Oauth2($client);
$user = $oauth2->userinfo->get();
$_SESSION['email'] = $user;
$redirect = 'hidden';
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
i know the code is not great, but i wonder if i should get a refresh token along with the access token ?
if someone are interested i have done like this to fix it... now it works like it should.
this method is called every time i need to do something with the mails (if the access token is not valid then you will not have access, so this is to make sure access is always there.)
public function checktokenexpiry()
{
global $google_client; // this is global as we use it in our webservice.
session_start();
$time_created = json_decode($_SESSION['access_token']);
$t=time();
$timediff=$t-$time_created->created;
if($timediff>3500) // 3500 as i want to have a little time to connect if it is just about to need refreshing.
{
$user = json_decode($_COOKIE['user']);
$usermail = $user->email;
$refreshtoken = $this->model->getRefreshToken($usermail);
$refreshtoken = $refreshtoken[0]['google_refresh_token'];
$google_client->refreshToken($refreshtoken);
$_SESSION['access_token'] = $google_client->getAccessToken();
}
}

google analytics (401) Login Required error

i am using google analytics php api to retrieve my data. on index.php i have authorization process done which works fine and i get successful login on this page i have link to another php page where i want to display all my properties so how i can post my login credentials to properties.php and create an analytics object to retrieve all the webproperties
code index.php look like this
session_start();
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('XXXX');
$client->setClientId('XXXXXX');
$client->setClientSecret('XXXXX');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('XXXXXX'); // API key
$client->setScopes('https://www.googleapis.com/auth/analytics');
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
TRY{
}
?>

Categories