Error getting Google Plus Profile when authenticating with Google ID Token - php

When I try getting The Google plus profile information using the following code,
$client = new Google_Client();
$client->setClientId(Config::get('services.google.clientId'));
$client->setClientSecret(Config::get('services.google.clientSecret'));
$client->setRedirectUri(Config::get('services.google.redirectUri'));
$client->setScopes(['profile', 'login' ]);
$id_token = $this->request->input('idToken');
$token_data = $client->verifyIdToken($id_token)->getAttributes();
$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');
I get the error saying
exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/plus/v1/people/me: (403) Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.' in /home/bepolite/websites/goodies/vendor/google/apiclient/src/Google/Http/REST.php:110
This code used to work before and I changed nothing on my end.
Also I am using the official google php api which I downloaded using composer
"google/apiclient": "^1.1"
Thanks In advance

Related

Google Analytics Webmaster API getting insufficientPermissions error code :403

I have created service account and below is my code:
$client = new Google_Client();
$client->setApplicationName("Console_Client");
$client->setAuthConfigFile('xxaax.json');
$scopes = [
//"https://www.googleapis.com/auth/webmasters",
//"https://www.googleapis.com/auth/webmasters.readonly"
Google_Service_Webmasters::WEBMASTERS_READONLY,
Google_Service_Webmasters::WEBMASTERS,
];
$client->setScopes($scopes);
$client->setAccessType('offline');
$service = new Google_Service_Webmasters($client);
$request = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$optParams = array('siteUrl' => 'https://www.test.co/');
$request->startDate = "2018-01-01";
$request->endDate = "2018-01-02";
$results = $service->searchanalytics->query($optParams, $request);
I'm receiving this error message in response:
PHP Fatal error: Uncaught Google_Service_Exception
"reason": "insufficientPermissions"
I have enabled this api in my account and am also able to hit it when trying google API explorer.
Why is this occurring?
For this we need to create service account. This is preferable in the case when you are hitting API from console and you don't have any web UI for OAuth2.0.
For this particular case, there is service account Id (looks like long string email). Copy this and add it to your google account.
Doing above solved my problem.
This step was not clear in google API docs.
Hope this helps someone in future.

"Access denied" exception is thrown, though the account has access

I'm using a service account to delegate domain wide security in order to pull a user listing from our Google Apps for Education instance via the Directory API and the PHP client library.
I'm fairly certain my service account has all the correct security because it's able to pull a listing using the API reference's "try it" feature.
So, at this point, everything is pointing toward an issue with my code but I can't seem to figure out where:
<?php
require 'vendor/autoload.php';
$clientEmail = '<>#developer.gserviceaccount.com';
$privateKey = file_get_contents(__DIR__ . '/access.p12');
$scopes = array(
'https://www.googleapis.com/auth/admin.directory.user.readonly',
);
$credentials = new Google_Auth_AssertionCredentials($clientEmail, $scopes, $privateKey);
$credentials->sub = 'service.account#my.domain';
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}
$directory = new Google_Service_Directory($client);
$result = $directory->users->listUsers(array('domain' => 'my.domain'));
var_dump($result);
The code above throws the following error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: ' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358
Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{
"error" : "access_denied",
"error_description" : "Requested client not authorized."
}' in C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php on line 358
Call Stack:
0.0010 132792 1. {main}() C:\wamp\www\quick\index.php:0
0.0260 1060248 2. Google_Auth_OAuth2->refreshTokenWithAssertion() C:\wamp\www\quick\index.php:18
0.9230 1163560 3. Google_Auth_OAuth2->refreshTokenRequest() C:\wamp\www\quick\vendor\google\apiclient\src\Google\Auth\OAuth2.php:309
The call stack should identify the specific line where this error occurred. Note that the second line in the stack seems to point to line 18 of your script, where the code indeed relates to OAuth verification:
$client->getAuth()->refreshTokenWithAssertion();
In other words, when you try to refreshTokenWithAssertion, Google says "access_denied because Requested client not authorized". If you're trying to identify where in your script you hit the error, I think that should answer your question.
If you want to figure out why it got an error, I'd do some google searches for refreshTokenWithAssertion plus that error message and see if you find any other developers working through a similar problem. For example by doing that google search I found this other page on SO that may help you.
Good luck!

Problems implementing Google Service Account Example in PHP - Getting OAUTH2 Error

I am trying to implement an example of using a google services account. What I want to do is very basic - create a connection, set the service provider, pull back some data. For some reason however, when I follow the example provided (https://github.com/google/google-api-php-client/blob/master/examples/service-account.php) it fails with the following error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'
I have scoured google trying to figure this out, and have found a few things here on StackOverflow, but none of them have solved my issue. Im hoping someone out there can help me. Here is the code I am working with:
//initialize a new Google client
$client = new Google_Client();
$client->setApplicationName("books-provider-example");
$this->service = new Google_Service_Books($client);
//do we already have a service token?
if (isset($this->service_token)) {
$client->setAccessToken($this->service_token);
}
//setup the credentials
$credentials = new Google_Auth_AssertionCredentials(
$GLOBALS['GSERVICES']['clientemail'],
$GLOBALS['GSERVICES']['scopes'],
file_get_contents($GLOBALS['GSERVICES']['keypath']),
'notasecret'
);
$client->setAssertionCredentials($credentials);
//refresh the auth token if its expired
if ($client->getAuth()->isAccessTokenExpired())
$client->getAuth()->refreshTokenWithAssertion();
//set the service token
$this->service_token = $client->getAccessToken();
Any help in getting this to work is greatly appreciated!

fecing 'Google_Auth_Exception' wror fetching OAuth2 access token, message: 'invalid_client'' error

I am trying to fetch mail from Google through gmail api
while authenticate the Google_Client after receiving the token i am getting this error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_client'' in
my code is simple using google-api-php-client-master and my code is as follow
require_once('config.php');
require_once 'autoload.php';
$client = new Google_Client();
$client->setScopes(array(
'https://www.googleapis.com/auth/plus.login',
'profile',
'email',
'openid',
'https://www.googleapis.com/auth/gmail.readonly',
'https://mail.google.com/',
));
$client->setApplicationName($config->social['google']->app_name);
$client->setClientId($config->social['google']->client_id);
$client->setClientSecret($config->social['google']->client_secret);
$client->setRedirectUri($config->social['google']->Redirect_URI);
$client->setDeveloperKey($config->social['google']->api_key); // API key
$gclient='';
print_r($_GET);
$token=new stdclass;
if(!isset( $_SESSION['google_token']))
{
$gclient=$client->authenticate($_GET['code']);//error occurs hare
$_SESSION['gclient']=$gclient;
if($gclient)
{
$_SESSION['google_token'] = $client->getAccessToken();
}
print_r($gclient);
}
I have checked my credentials several times and they were all correct
would some one please help me on it
I had the same problem but my solution was extreamly easy and frustrating.
When you copy the "Client secret" in API Credentials on your Google Developers Console they add a space after the "Client secret". Be sure to delete it!
$client_secret = "hf83nd93hd93j39dj9 ";<--
As Mario M. explained, there's an additional space when you copy the Client Secret. You have to make sure you got it right.
I got the same error - Error fetching OAuth2 access token, message: 'invalid_client', but in my case it was due to not verified domain. Therefore if you are creating credentials for a Web application or something similar and received the same error;
Check there's no additional space at the end of Client secret
Make sure your domain is verified
In my case I had to set the Client Secret file
$client->setAuthConfigFile(WWW_ROOT . 'files\json\client_secret_google_api.json');
and that solved my problem. Hope it helps someone.

Google Analytics API login required error

I've got a strange problem that I've tried to solve but I've tried a whole day and it just doesn't work, so I hope maybe someone else can help me with this.
I've build a CMS and after you login you see the dashboard.
On this dashboard you can click on a button to connect your account with Google - because I want my customers to be able to connect their Google Analytics account.
Everything works fine, I've got tokens and the refresh token and everything seems to work. Even when I request my user profile data I get it printed on my screen as an array. But when I try to get the accounts that are available to view for the connected user i get this error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties
key=xxxxxxxxxxxxxxxxxxxxxxxxxx: (401) Login Required'
I just don't understand why I get the message 'Login required'.
Below you can see my script.
require_once('/Google/Client.php');
require_once('/Google/Service/Analytics.php');
// call object
$client = new Google_Client();
$client->setApplicationName("Google Analytics - CMS title");
$client->setClientId('xxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxx');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array(
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/analytics'
));
// decode
$token = $token; // this comes from my database and it's json encoded
// connect
$client->setAccessToken($token);
// call service
$service = new Google_Service_Analytics($client);
// get accounts from analytics
$accounts = $service->management_accounts->listManagementAccounts();
When I try to var_dump $accounts I don't see anything because the error already occurred (Login required)
I think you are going to ask me now if my token is correct but it is because I tested it with other api calls.. it's just not working for this specific analytics request.
I hope someone can help me with this.
Thanks,
Pim vd Molen
UPDATE:
Something really strange just happened. I don't know how this is possible but the error just changed into another error:
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management
/accounts?key=xxxxxxxxxxxxxxxxxx: (403) Access Not Configured.
Please use Google Developers Console to activate the API for your project.
I've enabled the Google Analytics service ofcourse, but don't know which one i also need to enable.
The 401 error clearly states that the credentials are wrong. The Token might be valid for retrieving Data, but for retrieving user management information, you need a particular grant when asking for that token, please look here in the table you see the additional value for the scope parameter to set in your OAuth request.
not sure if you have solved this yet, but I've documented the process, with photos here:
https://circlical.squarespace.com/blog/2014/7/18/getting-zend-framework-2-and-googles-api-to-play-nice

Categories