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.
Related
I have tried the official HelloAnalytics tutorial however it doesn't work.
I am recieveing this error:
"PHP Fatal error: Class 'Google_Auth_AssertionCredentials' not found"
My Code:
// Creates and returns the Analytics service object.
// Load the Google API PHP Client Library.
require_once 'vendor/autoload.php';
// Use the developers console and replace the values with your
// service account email, and relative location of your key file.
$service_account_email = 'xxxxxxxxxxx#gmail.com';
$key_file_location = 'key_anyl.p12';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("HelloAnalytics");
$analytics = new Google_Service_Analytics($client);
// Read the generated client_secrets.p12 key.
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_email,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
Update:
after adding the suggested V1-master branch I am now getting the following error
Uncaught exception 'Google_Service_Exception' with message 'Error
calling GET googleapis.com/analytics/v3/management/accounts: (403)
User does not have any Google Analytics account.'
Problem nr 1:
if your not using composer make sure you downloaded the v1-master branch – Link
Problem nr 2:
(403) User does not have any Google Analytics account.
You are using a service account by default a service account does not have access to any google analytics accounts. You need to take the service account email address from Google Developers console and add it as a user at the ACCOUNT level it must be the ACCOUNT level in the Google Analytics website under the admin section.
For your problem you need to add the base directory of the library in the php 'include_path'.
Try putting this line of code before the require_once
set_include_path( get_include_path() . PATH_SEPARATOR . 'vendor/google/src' );
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
I am trying to create Google calendar events using Google Api OAuth service Account from PHP GAE.
I need the correct Session ID or the user EMail ID in the Calendar events field ‘created by’.
This is possible well in Google Apps Script(GAS), it creates the events with the correct session ID.
But, I want the same to be done in PHP GAE(Google App Engine). So, I tried to impersonate the user ID as follows:Perform Google Apps Domain-Wide Delegation of Authority
My aim is to insert the correct user ID of any end user automatically as like in GAS(Google Apps Script). I don't want any default credentials to be set in the field ‘created by’..
Using the PHP client library i tried to impersonate a user in Calendar API.I didn't get any complete sample for Calendar API.So, I tried the Drive API documentation sample, this sample seems to be working fine, Using other domain user also
Using Calendar API I wrote the below example.
<?php
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/autoload.php');
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/Service/Calendar.php');
require_once realpath(dirname(__FILE__).'/google-api-php-client-master/src/Google/Service/Oauth2.php');
use google\appengine\api\users\User;
use google\appengine\api\users\UserService;
$user = UserService::getCurrentUser();
$userEmail=$user->getEmail();
$client_email = '34234242424-qssjf8kg1kk42dnjdvd2ndrk7rou44#developer.gserviceaccount.com';
$private_key = file_get_contents('key.p12');
$scopes = array('https://www.googleapis.com/auth/calendar');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$credentials->sub = $userEmail;
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service =new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event();
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime('2015-09-26T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime('2015-09-26T10:00:00.000-07:00');
$event->setEnd($end);
$createdEvent = $service->events->insert('abc#group.calendar.google.com', $event);
It’s working well when i check this email, i got the correct service account credentials.
But when i used different email ID, i got this below error
PHP Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }'' in /base/data/home/apps/s~production/1.3874/google-api-php-client-master/src/Google/Auth/OAuth2.php:363 Stack trace: #0 /base/data/home/apps/s~production/1.387/google-api-php-client-master/src/Google/Auth/OAuth2.php(314): Google_Auth_OAuth2->refreshTokenRequest(Array) #1 /base/data/home/apps/s~ei-html-production/1.3874/final.php(34): Google_Auth_OAuth2->refreshTokenWithAssertion() #2 {main} thrown in /base/data/home/apps/s~production/1.38742/google-api-php-client-master/src/Google/Auth/OAuth2.php on line 363
Plz help me what i did wrong.Why the issue happens, when I used diff email ID, my end user who'll create cal events, could be any GMAIL or Google based domain ID.
So, plz help with at least a sample part...
Reference links:
How do I Insert Google Calendar Event using Google Api 3 for any user in the domain?
How to create a Google Calendar event without a reminder / How to get Service Accounts to impersonate users
You can only impersonate users on a google apps domain where you have the necessary permission for (search for 'domain wide delegation'). You've got that covered.
Once you're authorized for impersonation you have to recreate a fresh Google Client for each user you impersonate. You'll only receive an access_token you can use for this very user. If you just change the email address once you're authorized it will not work.
I am getting the following Error when trying to connect with the AdSense Management API Example:
Missing required parameter: redirect_uri
I am using a service Account, because my Server handles all the interaction between the adSense api. The user is not involved. Here is my PHP Code:
$client = new Google_Client();
$client->setApplicationName("PeopleHelpingPeople"); // name of your app
// set assertion credentials
$client->setAssertionCredentials(
new Google_Auth_AssertionCredentials(
"...",
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents('client_data.json') // keyfile you downloaded
));
$client->setScopes(array(
'https://www.googleapis.com/auth/analytics.readonly'
));
$client->setClientId("..."); // from API console
$client->setAccessType('offline_access'); // this may be unnecessary?
// Create service.
$service = new Google_Service_AdSense($client);
Why am I getting this Error?
If you are trying to use a ServiceAccount from the developers console, the kind of account that gives you a p12 file, those will not work with Adsense.
Take a look at the note on this page https://developers.google.com/adsense/management/getting_started
$client->setRedirectUri() may get you past this error but it wont solve your ultimate issue
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!