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

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!

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.

Get user login access token to use youtube API

I am using youtube API for scheduling live events for user in my application.
Once the user logged in my application i need to logged in the same user to our business google account(One google account for all user) without giving login credentials. and to get access token for scheduling the live events.
Is it possible to login the user into google account without giving login credentials(User will not feel he is login to another account).
Is it feasible with PHP?.Please give one example to get access token for youtube API access.
I used the following code for getting access token but service account can't access the youtube service.
My code for getting access token using service account:
<?php
require_once 'Google/autoload.php';
session_start();
$client_id = '395540674667-p64tdfqdsfsdfdsf#dsfd.com';
$Email_address = '54564-drgfdg1#developer.gserviceaccount.com';
$key_file_location = 'Youtube API-5czxczxc86.p12';
$client = new Google_Client();
$client->setApplicationName("Youtube API");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes = array('https://www.googleapis.com/auth/sqlservice.admin','https://www.googleapis.com/auth/plus.login','https://www.googleapis.com/auth/youtube');
$cred = new Google_Auth_AssertionCredentials($Email_address,
$scopes,
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
//print_r($client);
echo $client->getAccessToken();
?>
I am expecting the answer is something like this.Any one please help
you example about Youtube api, first:
select credentials to your api project from here:
https://console.cloud.google.com/home/dashboard?project= with your project
also you need to have the api enable because google told us "Some APIs are enabled automatically."
when you select:
https://console.cloud.google.com/apis/api/youtube/ with Go to Credentials you have some option into modal window this will help
also.
the php code seem to be ok but also I think you will change after you learn more about Credentials settings.

AdSense Management API - Missing required parameter: redirect_uri With Service Account

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

How to resolve oAuth 2.0 Google Spreadsheets authentication issue?

I'm building a server-side application that would need to authenticate with Google Spreadsheets API and read data from it. Using this PHP client with Google APIs client.
What I need to do is to authenticate with Google without user interaction.
Installed everything with composer and loaded with autoloader.php.
The problem I'm having is, in this section of the documentation, an $accessToken variable is used which I can't generate. I created a project in Google Developers Console and oAuth 2.0 credentials with service account client ID. As a result, I got two files - JSON and p12, alongside with the CLIENT ID, EMAIL ADDRESS and PUBLIC KEY FINGERPRINTS credentials, which I don't know how to use to obtain the authorization token.
Also, I'm facing a redirect_uri_mismatch error and I can't set it up in Google Developers Console.
The authenticate method in OAuth2.php is requiring a $code variable which I don't have and don't know how to obtain.
If I could obtain that $accessToken variable, I could try to debug further.
Any help is highly appreciated.
This is what worked for me:
$client = new Google_Client();
$client->setApplicationName(GOOGLE_APPLICATION_NAME);
$client->setClientId(GOOGLE_CLIENT_ID);
$key = file_get_contents(GOOGLE_KEY_FILE);
$cred = new Google_Auth_AssertionCredentials(
GOOGLE_CLIENT_EMAIL,
array(GOOGLE_SPREADSHEETS_URL),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service_token = json_decode($client->getAccessToken());
$accessToken = $service_token->access_token;
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
GOOGLE_SPREADSHEETS_URL is https://spreadsheets.google.com/feeds and GOOGLE_KEY_FILE is the location of your XXX.p12 file.
I do hope this will help somebody in a similar situation.

Fetch Google Calendar Events on PHP server after authenticating on iOS app

Okay so here's what I want to do...
user authorized the app on iPhone with read/write access to Google calendar
I get an auth token of some kind from Google
Pass on the token to my PHP server and save it in database
Use the token to regularly check on Google events and store them in server's database
Send the Google events data as json to the app
I want to implement the fetching of Google events on server, so that I can build additional functionality around them like sending remote push notifications.
I am stuck at the part of getting auth token and saving it on server and using it to fetch events from Google's calendar api, having not able to find the resources for same. Can somebody throw some light on this.
UPDATE
I have been able to successfully implement the scenario till step 3.
I get the auth token and refresh token from Google and save it in database. Now using the Google API php client, I am trying to connect to Google's calendar API using the access token that I got earlier. I am using the following code...
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
$client = new Google_Client();
$client->setAccessToken($google_access_token);
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);
But now I get this error...
PHP Fatal error: Uncaught exception 'Google_AuthException' with
message 'Could not json decode the token' in
/myserver/application/libraries/Google/auth/Google_OAuth2.php:162
Stack trace:
/myserver/application/libraries/Google/Google_Client.php(170): Google_OAuth2->setAccessToken('a_token...')
I understand that I am directly trying to set the access token in Google client api without specifying any redirect url or other params normally used when the user authorizes the access to Google calendars on server itself. Is this supposed to work like I am trying to?
UPDATE 2
Upon some further digging, I found out that directly setting the access token using setAccessToken does not work as Google client for API expects a JSON encoded string in the setAccessToken method. After some tweaks I changed my code to following....
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
$client = new Google_Client();
$client->setAccessType('offline');
$client->refreshToken($google_refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);
Now the error that I am getting is that of an invalid_request.
Error refreshing the OAuth2 token, message: '{"error" : "invalid_request"}'
Finally I am able to answer my own question. Hope this helps someone else.
Step 1 & 2. I got the Google OAuth protocol working in my iOS App following the instructions in this excellent tutorial on mobiletuts.
Step 3. I saved the access token and refresh token in database on my web server.
Step 4. Using the refresh token I got from iOS App I connected to the Google calendar API with this code...
require_once(APPPATH . "libraries/Google/Google_Client.php");
require_once(APPPATH . "libraries/Google/contrib/Google_CalendarService.php");
/* setup google client object */
$client = new Google_Client();
$client->setClientId(GOOGLE_CLIENT_ID);
/* refresh access token */
$client->refreshToken($google_refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);
/* get google calendars list */
$calendar = new Google_CalendarService($client);
$calendarList = $calendar->calendarList->listCalendarList();
echo print_r($calendarList, true);

Categories