Google OAuth: can't get access token - php

I'm just starting with google OAuth using the PHP Client Library. I'm having trouble getting the example from the Google APIs site working. Google's Example
When i try to exchange the authorization code for a token, it just returns NULL. No errors or exceptions.
I thought maybe it was a problem with my client_secret.json, but I don't know what to look for.
Here's my full code:
$client = new \Google_Client();
$client->setAuthConfig('client_secret.json');
$client->setRedirectUri('http://localhost/test.php');
$client->setAccessType('offline');
$client->addScope(\Google_Service_Gmail::MAIL_GOOGLE_COM);
if (! isset($request->code)) {
return redirect($client->createAuthUrl());
} else {
$client->authenticate($request->code);
$token = $client->getAccessToken(); // <- returns NULL, but no execeptions or errors
dd($token);
return redirect('https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=' . $token);
}

Related

Too few arguments to function Google\Client::authenticate(), 0 passed in google.php on line 41 and exactly 1 expected

Hello I am trying to get access token using Google api client PHP in CodeIgniter
when I load this localhost:8080/google/callback i am getting following error
Too few arguments to function Google\Client::authenticate(), 0 passed in E:\wamp\www\myproject\app\Controllers\Google.php on line 41 and exactly 1 expected
here is code
public function callback(){
define('GOOGLE_CLIENT_ID', 'XXXX']);
define('GOOGLE_CLIENT_SECRET', 'XXXX');
// Create Client Request to access Google API
$client = new Client();
$client->setApplicationName('Mysite.dom.ain');
$client->setClientId(GOOGLE_CLIENT_ID);
$client->setClientSecret(GOOGLE_CLIENT_SECRET);
$client->setRedirectUri('http://localhost:8080/google/callback');
$client->addScope('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtube.upload');
$client->setAccessType('offline'); // offline access
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setHttpClient(new GC(['verify' => false]));
$client->authenticate();
return $client->getAccessToken();
}
it will be a great if anybody can help me sorting this.
You need to redirect user to createAuthUrl() to get $_GET['code']
You can simply do it by following way
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
return $client->getAccessToken();
} else {
$redirect = $client->createAuthUrl();
header('Location: ' . $redirect);
exit();
}
where you can initially check $_GET['code'] is exist if not request for it.
Hope this might help you.

Get Google Analytics API token / Google_Client getAccessToken returns null / empty

I'm trying to get a Google access token for a service account so I can access the Analytics API from the client side.
On the server side I have the following code:
$keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxxxx.json';
$client = new Google_Client();
$client->setApplicationName('Analytics Demo');
$client->setAuthConfig($keyFile);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$token = $client->getAccessToken(); // Returns null
At some point it returned a token, but after a couple of calls it started returning null.
Trying to get the $client->getRefreshToken() also returns null.
When I put $client in a Google_Service_Analytics object everything seems to work just fine, so I know the key file is correct and properly read:
$analytics = new Google_Service_Analytics($client);
$accounts = $analytics->management_accounts->listManagementAccounts(); // Returns proper data
Any ideas on what might be going wrong?
UPDATE:
Calling $client->isAccessTokenExpired() results in true so I guess I have to refresh the token, but I have no clue how.
After a lot of trial and error I found that I had to use $client->fetchAccessTokenWithAssertion() instead of $client->getAccessToken().
public static function getGoogleServiceToken():?string {
$keyFile = base_path() . '/keys/xxxxxxxx-xxxxxxx.json';
$client = new Google_Client();
$client->setAuthConfig($keyFile);
$client->setApplicationName('Analytics Demo');
$client->setAccessType('access_type');
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
if ($client->isAccessTokenExpired()) {
$token = $client->fetchAccessTokenWithAssertion();
}
else {
$token = $client->getAccessToken();
}
return $token['access_token'];
}
Client side:
...
private _handleGetResponse(response) {
...
gapi.analytics.auth.authorize({
serverAuth: {
access_token: response.token,
}
});
...
Not sure why there is no decent documentation on this at all. Even knowing that I have to use this method I can't find documentation on what this method is actually doing. Any explanation or links to some documentation are still welcome!

Refresh token on Google OAuth2 PHP library

I implemented Google OAuth2 for user login on my website.
It works but after 1 hour token expires and login fails.
I read on the web that I need to get the Refresh Token (for Facebook Login I used a Long Lived Token), but code I tried doesn't work.
Here the code:
//LOGIN CALLBACK FROM GOOGLE
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setRedirectUri(SITE_URL."/login/google/google-callback.php");
if(isset($_GET['code'])) {
$gClient->setAccessType('offline');
$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
$gClient->setAccessToken($token['access_token']);
$_SESSION['google_access_token'] = $token['access_token'];
}
if($gClient->getAccessToken()) {
// Get user profile data from google
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
}
...
This first snippet works fine.
In this second snipped, when user change page, I verify if login is still active:
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setAccessType('offline');
$gClient->setAccessToken($_SESSION['google_access_token']);
if($gClient->getAccessToken()) {
if ($gClient->isAccessTokenExpired()) {
$gClient->fetchAccessTokenWithRefreshToken($gClient->getRefreshToken());
}
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
...
}
This second snipped doesn't work, because method fetchAccessTokenWithRefreshToken($gClient->getRefreshToken()) fails because $gClient->getRefreshToken() is NULL.
I debugged the callback and I saw that $token = $gClient->fetchAccessTokenWithAuthCode returns an array without "refresh_token" field.
Can anyone help me?
Thanks
Bye

Google oauth getAccessToken() null

I want to add google oauth to my web app, i already follow the google documentation about google oauth with php client library, but i got problem
Here my code
public function googleOauth() {
$client = new Google_Client();
$client->setAuthConfig(base_path('google_client.json'));
//$client->setAccessType("offline");
$client->setIncludeGrantedScopes(true);
$client->addScope(Google_Service_Blogger::BLOGGER);
$client->setRedirectUri(route('googleOauthCallback'));
return redirect($client->createAuthUrl());
}
public function googleOauthCallback(Request $params) {
if ($params->code) {
$client = new Google_Client();
$client->authenticate($params->code);
dd($client->getAccessToken());
}
But the $client->getAccessToken() return null
How to fix it ?

How to fetch auth token for service account using google API?

I have a Wordpress site (running PHP) that needs to display its own analytics data to visitors using the google-api. I want to create the charts in Javascript, so I need to fetch an auth token from the PHP code and then pass that to the Javascript code. I can't figure out how to get the auth token.
So far, I have code similar to this working using my service account:
https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
My code:
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$analytics = new Google_Service_Analytics($client);
$ga = $analytics->data_ga;
$start = date('Y-m-d', strtotime('-7 days'));
$end = date('Y-m-d');
$views = $ga->get('ga:'.$myAnalyticsId,
$start,
$end,
'ga:pageviews,ga:sessions,ga:newUsers',
array(
'dimensions' => 'ga:date',
'sort' => 'ga:date'
));
This all works, and I'm able to connect to Google_Service_Analytics and fetch analytics data. However, I can't figure out how to fetch a service access token using my credentials, that I can hand off to the Javascript code so I can use the Google Analytics API from Javascript.
This doesn't work:
$token = $client->getAccessToken();
Token just ends up being null. What do I need to do to fetch a token?
Here is the working code for me.
The service account has a different type of process for generating access token.
It is not following oauth client api.
//include_once 'vendor/autoload.php';
$credentialsFilePath = 'test.json';
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
print_r($token);
$accessToken = $token['access_token'];
Figured this out:
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
First answer still works in 2021 (Thanks!), but a used function is deprecated (still available though)
This worked for me
public function getToken() {
$client = new Client(); // use Google\Client;
$client->setAuthConfig('securejsonfile.json');
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$client->setApplicationName('appname');
$client->fetchAccessTokenWithAssertion();
return $client->getAccessToken(); //array
}

Categories