Google analytics apis v3 error 401 Login Required - google-maps-api-3

I'm working with google analytics apis v3 to receive traffic data, the language in use is php, the problem is that until a few days ago I obtained the data, now I have this error:
(401) Login Required
I logged on:
gmail.com
analytics.google.it
on the console of google is all enabled properly, because a few days ago it worked ..
here:
http://ga-dev-tools.appspot.com/explorer/
working properly ..
The authentication code is this:
require_once '/analytics/src/Google_Client.php';
require_once '/analytics/src/contrib/Google_AnalyticsService.php';
$client = new Google_Client();
$client->setAccessType('offline'); // default: offline
$client->setApplicationName('#########ca1');
$client->setClientId('#########99.apps.googleusercontent.com');
$client->setClientSecret('#########hs33t');
$client->setRedirectUri("#########/analytics/oauth2callback.php");
$client->setDeveloperKey('#########y86ePKOcHs'); // API key
# $service implements the client interface, has to be set before auth call
$service = new Google_AnalyticsService($client);
if (isset($_GET['logout'])) { // logout: destroy token
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
The parameter $ _GET ['code'] is empty, and then the session token is not created.
Maybe it worked for a few days Just Because in the various tests of code That I did was logged.

you should pass the $_GET['code'] as a parameter to the $client->authenticate() method, like that
$client->authenticate($_GET['code']);

Related

Symfony2 + FosOauth: token get, but requests are anonymous

I have installed and configurated FosOauthBundle but I have this problem: I can get Token And Refresh token with this line of code:
$ http POST http://localhost:8888/app_dev.php/oauth/v2/token grant_type=password client_id=1_3bcbxd9e24g0gk4swg0kwgcwg4o8k8g4g888kwc44gcc0gwwk4 client_secret=4ok2x70rlfokc8g0wws8c8kwcokw80k44sg48goc0ok4w0so0k username=MYEMAIL password=MYPASS
If I pass a wrong MYEMAIL or a wrong MYPASS symfony reply me with an error (and this is correct). Users are manged via FosUserBundle.
Now, How can I use token to say symfony that I'm a registered user ?
I have created this "api" in my controller:
public function getDemosAction()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
$view = $this->view($user);
return $this->handleView($view);
}
and I call it via this code:
$curl -H "Authorization: Bearer NGEwMGIxMzJkZmU5Yjc3YmM2ZjViNmE0YWFhYTEwOTg1MjI5NzIyNDkwNmFhYTUzMTRkZTk3MzEyNjA4OWY0Ng" http://localhost:8888/app_dev.php/api/demos
but it return me ALWAYS "anon.".
Where is my error ?
The problem was the order of firewall directives in security.yml. I have found the solution via this other question: Symfony2 OAuth keeps giving me a login page when a token is provided

google analytics custom plugin getting error invalid grant

$client = new Google_Client();
$client->setAuthConfigFile(plugin_dir_url( __FILE__ ) . '/client_secrets.json');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->setIncludeGrantedScopes(true);
$client->setAccessType('offline');
$client->revokeToken();
$auth_url = $client->createAuthUrl();
using a popup authentication with javascript and then
if (!isset($_SESSION['access_token'])) {
//$client->authenticate($_GET['code']);
if($client->isAccessTokenExpired()){
$client->authenticate($this->options['authenication_code']);
$refreshToken = $client->getRefreshToken();
$client->refreshToken( $refreshToken );
$accessToken = $client->getAccessToken();
}
$_SESSION['access_token'] = $accessToken ? $accessToken : $refreshToken;
}
After authenticating It is giving the result ,but while using another session to get the data it is showing errors different error in different circumstances no clear idea
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant: Invalid code.'
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant' if checked after some time
Google_Auth_Exception' with message 'Error fetching OAuth2 access
token, message: 'invalid_grant: Code was already redeemed.' authenticated closed the browser and try with another browser
This is my 4th week on this but still unable to get things correctly.
I have gone through certain posts but no luck
1.Unable to refresh OAuth2 token in PHP, invalid grant
2.authenticate() accepts invalid tokens
3.Getting "invalid_grant" error on token refresh
4.Problem in refreshing access token
5.Why do I keep catching a Google_Auth_Exception for invalid_grant?
6.How to refresh token with Google API client?
7.Google OAuth2 - access token & refresh token -> invalid_grant/Code was already redeemed
8.Use OAuth Refresh Token to Obtain New Access Token - Google API
9.Using refresh_token for Google OAuth 2.0 returns http 400 bad request
and some more if I need to post more codes or anything else please let me know.
full code

Service account authentication

I'm trying to create calendar event via PHP for one particular user - say developement#example.com.
I've created Service Account in Google Developers Console, got ClientID, E-mail address and private key. The authentication is done with code:
$client = new Google_Client();
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$cred = new Google_Auth_AssertionCredentials(
'somelongstring#developer.gserviceaccount.com.',
array('https://www.googleapis.com/auth/calendar','https://www.googleapis.com/auth/calendar.readonly'),
file_get_contents('p12 file'));
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
This type of authentication seems pretty OK. But all events are created as user with E-mail address somelongstring#developer.gserviceaccount.com instead of developement#example.com.
I've tried setting sub parameter:
$cred = new Google_Auth_AssertionCredentials(
....
$cred->sub = 'developement#example.com';
$client->setAssertionCredentials($cred);
But this piece of code throws exception:
Google_Auth_Exception: Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }'
And now I'm lost. Any advice?
OK, resolved ;-)
Problem was with developement on own domain.
As mentioned in other question and in Google SDK Guide I have to grant access for service account to all scopes I request access. I forgot to add read-only scope.

Google Analytics API Automated Login

I have this panel that i'm developing at my company where i will show the user's information from Google Analytics but i don't want the user to authorize or log in with his account every time he comes to the panel.
What i would like to do is: on the first time using my panel he would connect his Google account and i would save some info and on the next time he connects at my panel i would use this saved info to log on his account so i can list the Analytics info without ask for his permission or list that info even if he's not connected on is Google account right now.
Basically i would log in his account automatically and permit the 'app' to show the information.
I already have some code that connects on the API if he is connected on is Google account, but when he's not i get the login screen where he has to provide his email e password.
What i have so far is this:
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google Analytics PHP Starter Application");
$client->setClientId('KEY');
$client->setClientSecret('SECRET');
$client->setRedirectUri('RETURN URI');
$client->setScopes('https://www.googleapis.com/auth/analytics.readonly');
$client->setAccessType('offline');
$service = new Google_Service_Analytics($client);
if(isset($_GET['logout']))
{
unset($_SESSION['token']);
}
if(isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_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())
{
$props = $service->management_webproperties->listManagementWebproperties("12008145");//~all
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
//print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
//print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
//print "<h1>Goals</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
header("Location: " . $authUrl);
}
?>
Is there any way to do that ? I have looked for it around everywhere and couldn't find something near it.
In google Api's, when user authenticate the first time, you receive a CODE (which you are already getting i suppose). Use this code to get refresh token (lifetime is (always), until and unless, user revokes the permissions). Save this refresh token in Database for further use. Refresh token is used to get access token(lifetime is a short time, returned in the expires in argument). Access token is to give you access to your user's data for some time. You can keep using refresh token to get access token whenever you need to access your user's data.
Whenever you want to access user's data, use refresh token to get access token and then use that access token to get user's data.
In your case, you are using google api php client, you can use Methods in Client.php like:
getAccessToken()---to get refresh token the first time. When you call this method, you get back a json in a form: let this json name be $accessToken
$accessToken = {"access_token":"TOKEN", "refresh_token":"TOKEN", "token_type":"Bearer",
"expires_in":3600,"id_token":"TOKEN", "created":1320790426}
parse json to take refresh_token($refreshToken = $accessToken.refresh_token) and save it for later use.
setAccessToken($accessToken)---call this to set the OAuth access token.
refreshToken($refreshToken)---Fetches a fresh OAuth access token with the given refresh token.
For further clearity, look at Client.php and also read:
https://developers.google.com/accounts/docs/OAuth2WebServer

Cannot Authenticate Salesforce in a Wordpress Plugin

I'm getting an error (INVALID_SESSION_ID) when trying to send an authenticated GET request to Salesforce.com.
Here is the plug-in in its entirety, which basically just outputs the body of the REST response to whatever page has the [MembershipTables] shortcode:
if (!class_exists('WP_Http')) {
include_once(ABSPATH . WPINC . '/class-http.php');
}
// This is obviously the real username
$username = 'xxxx#xxxx.xxx';
// And this is obviously the real password concatonated with the security token
$password = 'xxxxxxxxxxxxxx';
function getMembershipTables() {
$api_url = 'https://na15.salesforce.com/services/apexrest/directory';
$headers = array('Authorization' => 'Basic ' . base64_encode("$username:$password"));
$args = array('headers' => $headers);
$request = new WP_Http;
$result = $request->request($api_url, $args);
$body = $result['body'];
echo "$body";
}
add_shortcode( 'MembershipTables', 'getMembershipTables' );
I should note that I can successfully hit this endpoint with Curl, though I use a session token I get from Salesforce using the old SOAP API to keep it equivalent (i.e., no client id/secret).
Am I doing something wrong with WP_Http? Or cannot I not authenticate a salesforce.com request using basic auth?
Thanks.
The salesforce API does not support Basic authentication, you need to call it with a sessionId. You can obtain a sessionId by various methods include interactive & programatic OAuth2 flows, and via a Soap login call.
Basis Interactive had a similar problem to solve. When I worked on the project I opted to to call the SalesForce CRM via the preset form plugin and a custom JS Cookie PHP Wordpress Plugin. We had this problem easily resolved by developing custom calls to SalesForce CRM via a getRequest in PHP passing data to the SalesForce CRM.
Test Site in Use:
http://newtest.medullan.com/wp/?page_id=3089
Here is the code and recycle the logical queries
Download Link:
http://basisinteractive.net/webdesign.html#wordpress

Resources