Google Analytics API 401 Invalid Credentials - php

I'm wracking my brain trying to figure out how to use the Google API PHP Client to access Google Analytics. Specifically, I want to upload cost data from other campaigns. My code does work to get information from GA, I can view traffic data for profiles, but I cannot figure out how to upload.
Here's the code that I'm using for auth:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("GA-Tester");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://www.site.com/indext.php');
$client->setDeveloperKey('xxx');
$analyticsService = new Google_AnalyticsService($client);
$dailyUploads = $analyticsService->management_dailyUploads;
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
header ('Location:http://www.site.com/indext.php');
} else {...
This code does work for requesting data. I can get a list of accounts, profiles, download traffic data for a specific profile, etc. No errors or issues.
When I try to upload my CSV file containing cost data I get a '401 Invalid Credentials' error. Here's the code that sends the file:
$send = $dailyUploads->upload(
$accountId,
$webPropertyId,
$customDataSourceId,
$start_date,
1,
'cost',
array(
"reset" => true,
"data" => $cont,
"mimeType" => "application/octet-stream",
"uploadType" => "media"));
I've double checked all of my variables that I'm passing, they're sending the correct information.
So here's my question. If all of my GET requests work without issue, why would my POST request throw an error? I can't tell if this is an error with my code, or with settings in the API console. Can anyone steer me in the right direction?
EDIT:
Here's the error code generated (minus identifiable bits).
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling POST https://www.googleapis.com/upload/analytics/v3/man
agement/accounts/1234567/webproperties/UA-1234567-1/customDataSources/
xXxXxX/dailyUploads/2013-01-17/uploads?appendNumber=1&type=cost&reset=
true&uploadType=media&key=xXxXxX: (401) Invalid Credentials' in /../pub
lic_html/proj/google-api-php-client/src/io/Google_REST.php:66 Stack tra
ce: #0 /../public_html/proj/google-api-php-client/src/io/Google_REST.ph
p(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1 /
../public_html/proj/google-api-php-client/src/service/Google_ServiceRes
ource.php(186): Google_REST::execute(Object(Google_HttpRequest)) #2 /..
/public_html/proj/google-api-php-client/src/contrib/Google_AnalyticsSer
vice.php(82): Google_ServiceResource->__call('upload', Array) #3 /../pu
blic_html/proj/dailyUpload_send.php(60): Google_ManagementDailyUploadsS
erviceResource->upload('1234567', 'UA-1234567-1', 'xXxXxXxXxXxXxXx...',
' in /../public_html/proj/google-api-php-client/src/io/Google_REST.php
on line 66

I just successfully uploaded cost data for the first time. In trading comments with Nicholas Pickering I came across the documentation for Management API Authorization which states that:
You will get a 401 status code if your access_token has expired or if you are using the wrong scope for the API.
The default for scope is read only, which is why all of my GET requests were working without difficulty, but I couldn't complete any POST requests through the API. I can't remember how I found it, but the way to accomplish this within the PHP client library is to append the following line to the client declaration:
$client->setScopes('https://www.googleapis.com/auth/analytics');
As soon as I added that line to my project, I was able to successfully upload cost data. I'm really glad to have cleared this hurdle. I still have a long way to go to complete my project, but at least I know that it's going to work.

I kept geting this error until I went to Google Console -> APIs & auth ->
APIs and turned on this API usage.

Related

Fat Free Use Google OAuth + Google API

I'm trying the following thing for quite a while now and am heavily struggling...
On a website, I first want to authenticate a user with his Google Account using OAuth. Therefore, I'm using this library. In order to get it working, I used $f3->set('AUTOLOAD','vendor/ikkez/f3-opauth/lib/opauth/'); to load the PHP files and then used the following code to create the routes and make the authentication possible:
$f3 = \Base::instance();
// load opauth config (allow token resolve)
$f3->config('vendor/ikkez/f3-opauth/lib/opauth/opauth.ini', TRUE);
// init with config
$opauth = OpauthBridge::instance($f3->opauth);
// define login handler
$opauth->onSuccess(function($data){
header('Content-Type: text');
//$data['credentials']['token'];
});
// define error handler
$opauth->onAbort(function($data){
header('Content-Type: text');
echo 'Auth request was canceled.'."\n";
print_r($data);
});
So far so good, thats all working fine, once permission is granted from Google I get the correct callback, also including the login token.
Now the next step is, that after user gave permission for that (by authenticating), I want to check, if the user subscribed to a specific channel on Youtube (and afterwards saving that information to my DB, printing it at the first step would be enough though).
Now I did my homework for multiple hours in trying to figuring out how it works...
What I (in general found) is that the following curl request should give me the desired result:
curl \
'https://youtube.googleapis.com/youtube/v3/subscriptions?part=snippet%2CcontentDetails&forChannelId=UC_x5XG1OV2P6uZZ5FSM9Ttw&mine=true&key=[YOUR_API_KEY]' \
--header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \
--header 'Accept: application/json' \
--compressed
I then tried to sent this curl request with PHP, substituting the API KEY with my Google API Key and "YOUR_ACCESS_TOKEN" with the token I got from OAUTH.... However, it's throwing an error, saying "request had insufficient authentication scopes"... That seems to be because when checking the PHP example from Google, I have to provide the Scopes I'm using - in my case https://www.googleapis.com/auth/youtube.readonly.
The PHP code provided by Google is the following:
<?php
/**
* Sample PHP code for youtube.subscriptions.list
* See instructions for running these code samples locally:
* https://developers.google.com/explorer-help/guides/code_samples#php
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new Exception(sprintf('Please run "composer require google/apiclient:~2.0" in "%s"', __DIR__));
}
require_once __DIR__ . '/vendor/autoload.php';
$client = new Google_Client();
$client->setApplicationName('API code samples');
$client->setScopes([
'https://www.googleapis.com/auth/youtube.readonly',
]);
// TODO: For this request to work, you must replace
// "YOUR_CLIENT_SECRET_FILE.json" with a pointer to your
// client_secret.json file. For more information, see
// https://cloud.google.com/iam/docs/creating-managing-service-account-keys
$client->setAuthConfig('YOUR_CLIENT_SECRET_FILE.json');
$client->setAccessType('offline');
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open this link in your browser:\n%s\n", $authUrl);
print('Enter verification code: ');
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Define service object for making API requests.
$service = new Google_Service_YouTube($client);
$queryParams = [
'forChannelId' => 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
'mine' => true
];
$response = $service->subscriptions->listSubscriptions('snippet,contentDetails', $queryParams);
print_r($response);
This let's me run into a new issue... Trying to use this code, I'm getting the error, that Google_Client is not known as class... I then went ahead and installed Google Client with Composer and tried to use vendor/autoload.php in order to use the class.... However, when including the autoload.php, I get the error Fatal error: Cannot declare class Prefab, because the name is already in use... This seems to be the case, because the f3-opauth declares this Prefab class already and then the google apiclient tries to declare it again... However, I didn't manage to to include google apiclient without the autoload...
You see, I really tried a lot and I've been working on this for about 5-6 hours today, only getting that one API request to work and I don't know what else to try...
Any hint on how to get it working would be appreciated - if there's any hint on doing it a completely other way, I'd be willing to change it as well, as the project itself just started.
Summarizing, what I'm trying to do is the following:
-> User can log in on Website with his Youtube/Google Account
-> When authenticating, its checked, if the User is a Subscriber of a specific channel. Next step would be to also check, if he is a channel member of this speicific channel. Both information would need to be saved to database
-> after that, user can always log in into his account with Google again and in the database, you can find the information if the user is subscriber and/or channel member of this channel..
Thanks in advance!
I'm not sure if this will help with your exact use case, but I've worked with Google APIs in the past with Fat-Free. I couldn't get it to work right off the bat, so I installed and got it working with the Google Client/API/SDK. Once I got that working, then I worked backwards to see if I could make it work with Fat-Free. One of the things that I noticed I was running into was missing fields in the Oauth request. access_type was one that got me as well as approval_prompt. I know that you said you've gotten your access token thus far, so it may not apply, but it could for future requests. Here's some example code I've got working to generate an oauth URL for Google Sign in, and then to process the request and make the call to the userinfo portion.
<?php
class App_Auth {
public static function generateOauthUrl() {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('scope', 'profile email');
$Oauth->set('response_type', 'code');
$Oauth->set('access_type', 'online');
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->uri('https://accounts.google.com/o/oauth2/auth', true);
}
public static function processAuthCodeAndGetToken($auth_code) {
$fw = Base::instance();
$Oauth = new \Web\OAuth2();
$Oauth->set('client_id', $fw->get('google.client_id'));
$Oauth->set('client_secret', $fw->get('google.client_secret'));
$Oauth->set('scope', 'profile email');
$Oauth->set('access_type', 'online');
$Oauth->set('grant_type', 'authorization_code');
$Oauth->set('code', $auth_code);
$Oauth->set('approval_prompt', 'auto');
$Oauth->set('redirect_uri', $fw->SCHEME.'://' . $_SERVER['HTTP_HOST'] . $fw->BASE.'/oauthRedirect');
return $Oauth->request('https://oauth2.googleapis.com/token', 'POST');
}
public static function getOauthUserInfo($access_token) {
$Oauth_User_Info = new \Web\OAuth2();
return $Oauth_User_Info->request('https://www.googleapis.com/oauth2/v2/userinfo', 'GET', $access_token);
}
One other error that has bitten me in the backside was we would get our access token from Google and then store it in the database for subsequent requests. We would get that scopes error you mentioned request had insufficient authentication scopes. We eventually figured out that the access_token was longer than our database field (VARCHAR(32) if I remember right) so we needed to make our database field longer so it would store the whole thing.
Hopefully one of those triggers something for you to figure out your issue.

Google Calendar API error redirect_uri_mismatch

I am trying to use the google API to manage the user´s calendar, and I am finding a problem. I created and configured a google project on the Google Developers Console. One of the settings was the allowed redirecting uris... and I think it is ok, because after some test where google threw the same error (redirect_uri_mismatch), I got that google ask me for permissions... the problem I think is this line: $this->client->authenticate($_GET['code']);
I am going to show the code and explain what it does
function __construct()
{
parent::__construct();
require __DIR__ . '/vendor/autoload.php';
define('APPLICATION_NAME', 'Google Calendar API PHP Quickstart');
define('CLIENT_SECRET_PATH', __DIR__ . '/credentials/client_secret.json');
define('CREDENTIALS_PATH', __DIR__ .'/credentials/');
define('SCOPES', implode(' ', array(Google_Service_Calendar::CALENDAR_READONLY)));
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-php-quickstart.json
$this->client = new Google_Client();
$this->client->setApplicationName(APPLICATION_NAME);
$this->client->setScopes(SCOPES);
$this->client->setAuthConfigFile(CLIENT_SECRET_PATH);
if (!file_exists(CLIENT_SECRET_PATH.$this->session->userdata("identity").".json") && !$this->input->get("code"))
$this->getCredentials();
}
public function responseCredentials()
{
$authCode = $this->input->get("code");
$this->client->authenticate($_GET['code']);
$accessToken = $this->client->client->getAccessToken();
$credentialsPath = CLIENT_SECRET_PATH.$this->session->userdata("identity").".json";
mkdir(dirname($credentialsPath), 0700, true);
file_put_contents($credentialsPath, $accessToken);
redirect(base_url("dashboard"));
}
private function getCredentials()
{
$this->client->setRedirectUri(base_url('calendar/responseCredentials'));
$authUrl = $this->client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
Ok... the first... the constructor it load the google api autoloader, and the constants, creates a new Google_Client object, and inspect if exists a permissions file for the user and there is no "code" index on the get.
If not it invokes the getCredentials function that redirect to google.
After give permissions, the user is redirect to http://domain.com/calendar/responseCredentials (that it is configured on the console.developers.google)
The error thrown is this:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message
'Error fetching OAuth2 access token, message: 'redirect_uri_mismatch'' in
/var/www/html/prototipo/application/controllers/vendor/google/apiclient/src/Google/Auth/OAuth2.php:126
Stack trace:
#0 /var/www/html/prototipo/application/controllers/vendor/google/apiclient/src/Google/Client.php(128): Google_Auth_OAuth2->authenticate('4/rkAKNAmiVgs1Z...', false)
#1 /var/www/html/prototipo/application/controllers/calendar.php(52): Google_Client->authenticate('4/rkAKNAmiVgs1Z...')
#2 [internal function]: Calendar->responseCredentials()
#3 /var/www/html/prototipo/system/core/CodeIgniter.php(360): call_user_func_array(Array, Array)
#4 /var/www/html/prototipo/index.php(202): require_once('/var/www/html/p...')
#5 {main} thrown in/var/www/html/prototipo/application/controllers/vendor/google/apiclient/src/Google/Auth/OAuth2.php on line 126
What am I doing wrong??
Thank you.
EDIT
I just realized that at the end of the code variable on the return uri there always is a pad... something like this:
http://pedro.eatec.es/prototipo/calendar_test_stack/responseCredentials?code=4/PL7nK1s9m5vpBow7HScaPmkpWpoW3J4uzUxlD7NE49g#
The example here: https://developers.google.com/identity/protocols/OAuth2WebServer#handlingresponse doesn´t show this pad... I tried to do this:
$this->client->authenticate($_GET['code']."#");
But... of course, doesn´t work.
PS: I tried to do it because with echo $_GET['code']; didn´t show the pad.
Hello and Thanks #thepieterdc finally you were reason...
I was setting up correctly the project on console.developers... but my mistake was that I need make some trying to get a correct configuration and when I got to make disappear the error 400 (with the broken robot) and it ask me for permission, on the redirecting function when I make $this->g_client->authenticate($_GET['code']); the code try to make other request (on OAuth2.php) to https://accounts.google.com/o/oauth2/token and it use the client_id.json that you need to refresh... and I didn´t. I WAS USING THE FIRST EDITION OF THE CLIENT_ID.JSON I need to re-download (or re-write) if you change something on the console.
Thanks.

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.

Unable to get Google OAuth Token

I'm trying to add calendar events to my Google calendar from a php script. Note that I can do this successfully directly from a Google test page so I think that my calendar is set up correctly. However, when I attempt do this from a php script, I'm not able to get the OAuth2 token.
The following script, mostly taken from a Google example, runs without error, but it always winds up with a "Connect Me!" link. When I click on this link, it takes me to a validation screen that warns me that this app would like to manage my calendars. I click 'Accept' and a then see my calendar. A little inconvenient, but if this gets the OAuth token, fine.
I then go back and run the script again, hoping that the access token will now be available, but I get exactly the same result. No matter how many times I run this script, I never get the token, which I need in order to expand the script to add events to the calendar.
I've been at this for days, and I'm just not getting anywhere. Can anyone help? Thanks.
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_CalendarService.php';
require_once '../../src/auth/Google_OAuth2.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Add Google Calendar Entries");
// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('843319906820-1s1d737e77o71a3vaskf434k3ape1fk5.apps.googleusercontent.com');
$client->setClientSecret('AP5imn3e0TEWNyLTCNm8YJj6');
$client->setRedirectUri('https://www.google.com/calendar/');
$client->setDeveloperKey('AIzaSyDIw3ks7AmrIrRxjO9y2gWBhQDYHFWd-uc');
$client->setUseObjects(true);
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
EDIT: Attempting to implement the suggestion from Vinicius Pinto. I've changed my redirect to point directly back to this script. Now I get this error:
Fatal error: Uncaught exception 'Google_ServiceException' with message
'Error calling GET
https://www.googleapis.com/calendar/v3/users/me/calendarList?key=AIzaSyDIw3ks7AmrIrRxjO9y2gWBhQDYHFWd-uc:
(403) Access Not Configured. Please use Google Developers Console to
activate the API for your project.' in
D:\Hosting\11347607\html\scripts\google-api-php-client\src\io\Google_REST.php:66
Stack trace: #0
D:\Hosting\11347607\html\scripts\google-api-php-client\src\io\Google_REST.php(36):
Google_REST::decodeHttpResponse(Object(Google_HttpRequest)) #1
D:\Hosting\11347607\html\scripts\google-api-php-client\src\service\Google_ServiceResource.php(186):
Google_REST::execute(Object(Google_HttpRequest)) #2
D:\Hosting\11347607\html\scripts\google-api-php-client\src\contrib\Google_CalendarService.php(205):
Google_ServiceResource->__call('list', Array) #3
D:\Hosting\11347607\html\scripts\google-api-php-client\examples\calendar\simple.php(43):
Google_CalendarListServiceResource->listCalen in
D:\Hosting\11347607\html\scripts\google-api-php-client\src\io\Google_REST.php
on line 66
It would appear that I don't have the correct APIs activated in the developer console. I have the Calendar API and the Google Cloud Storage JSON API activated and nothing else. I don't see any other APIs that would be relevant, and I don't think that this message is telling me which APIs it wants.
EDIT 2: Looks like I was using the wrong developer key. I've changed it to the key for server applications. Now my error is this:
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error refreshing the OAuth2 token, message: '{ "error" :
"invalid_client" }'' in
D:\Hosting\11347607\html\scripts\google-api-php-client\src\auth\Google_OAuth2.php:288
Stack trace: #0
D:\Hosting\11347607\html\scripts\google-api-php-client\src\auth\Google_OAuth2.php(248):
Google_OAuth2->refreshTokenRequest(Array) #1
D:\Hosting\11347607\html\scripts\google-api-php-client\src\auth\Google_OAuth2.php(225):
Google_OAuth2->refreshToken('1/6ZdJyZALqcbwW...') #2
D:\Hosting\11347607\html\scripts\google-api-php-client\src\service\Google_ServiceResource.php(167):
Google_OAuth2->sign(Object(Google_HttpRequest)) #3
D:\Hosting\11347607\html\scripts\google-api-php-client\src\contrib\Google_CalendarService.php(205):
Google_ServiceResource->__call('list', Array) #4
D:\Hosting\11347607\html\scripts\google-api-php-client\examples\calendar\simple.php(47):
Google_CalendarListServiceResource->listCalendarList() in
D:\Hosting\11347607\html\scripts\google-api-php-client\src\auth\Google_OAuth2.php
on line 288
The $client->setRedirectUri() should receive a URL pointing to your application, because this is the URL that you'll be redirected to after you authorize the application in the Google page. That's why you are being redirect to the calendar, because you are using the calendar URL.
It seems like your script is already expecting a $_GET['code'], so try setting the redirect URL to the url of this script. You'll also need to set the same URL in the Developers Console, under API -> Credentials.
You only get a token when you call $client->authenticate($_GET['code']); with a value code.
Take a look at this lib I just commited to Github, it's an early version, but it's working fine (I'm using to access YouTube). It's using the new official library.
Update: as said in the comments, the developer key isn't actually required for this to work, even though all Google sample code sets it.

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