Google Analytics Api Error - google-api

I am trying to make a call to get data from Google Analytics.
<?php
require_once 'lib/apiClient.php';
require_once 'lib/contrib/apiAnalyticsService.php';
session_start();
$client = new apiClient();
$service = new apiAnalyticsService($client);
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()) {
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
try {
$data = $service->data_ga->get('ga:29214712', '2012-01-01', '2012-01-15',
'ga:visits', array('dimensions' => 'ga:source,ga:keyword', 'sort' =>
'-ga:visits,ga:source', 'filters' => 'ga:medium==organic', 'max-results' => '25'));
}
catch (apiServiceException $e) {
echo $e->getCode();
print_r($data);
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
After Wrapping the code in the TRY Catch Block i am getting the following error
403
Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A29214712&start-date=2012-01-01&end-date=2012-01-15&metrics=ga%3Avisits: (403) Forbidden
( ! ) Notice: Undefined variable: data in
C:\wamp\www\gitgrow\index.php on line 43
Note: I have granted the permission and have forced the Profile ID to test it.

The 403 error you're getting means the authorized user doesn't have access to the ga:29214712 reporting profile that is defined in your query.
Take a look at the HelloAnalyticsAPI.php sample in the examples/analytics/demo directory, and make sure you can connect to the API:
http://code.google.com/p/google-api-php-client/source/browse/#svn%2Ftrunk%2Fexamples%2Fanalytics%2Fdemo
Also, take a look at the Google Analytics developer guide. It will describe how you can obtain the correct profile IDs:
https://developers.google.com/analytics/devguides/reporting/core/v3/#user_reports

Related

PHP Google Search Console API "invalid_grant" response

I am using following PHP code to fetch data through Google Search Consonle API.
It was working fine 2 months ago but now it's showing invalid grand message instead of data. Please! need your help.
error: '400 - {"error":"invalid_grant","error_description":"Bad Request"}'
I've right credentials included. Also you can see token is saved in file and is being fetched on demand and getting refresh too. I don't why it's stopped working.
Thanks
At the top I've added
use Google_Client;
use Google_Service_Webmasters_SearchAnalyticsQueryRequest;
use Google_Service_Webmasters;
and here is the code
$siteToFetch = (!empty($site)) ? base64_decode($site) : "https://www.siteiamfulluserof.com/";
$client_id = 'XXXXXXXXXXXX-FULL-TOKEN-REMOVED';
$client_secret = 'xxxxxx-xxxxx_xxxxxxxxxxxxxxx-xxxx';
$redirect_uri = 'http://localhost/redirect_url';
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAuthConfig(public_path("client_secret_latest.json"));
$client->setScopes("https://www.googleapis.com/auth/webmasters", 'https://www.googleapis.com/auth/webmasters.readonly');
if (file_exists($this->tokenFile)) {
$accessToken = json_decode(file_get_contents($this->tokenFile), true);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
if (isset($_REQUEST['code'])) {
$authCode = $_REQUEST['code'];
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
if (!file_exists(dirname($this->tokenFile))) {
mkdir(dirname($this->tokenFile), 0700, true);
}
file_put_contents($this->tokenFile, json_encode($accessToken));
} else {
exit('No code found');
}
}
$client->setAccessToken($accessToken);
// Refresh Token if expired.
if ($client->isAccessTokenExpired()) {
$refreshTokenSaved = $client->getRefreshToken();
$client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
}
if ($client->getAccessToken()) {
$googleQuery = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$googleQuery->setStartDate(date('Y-m-d', strtotime('-180 days')));
$googleQuery->setEndDate(date('Y-m-d', strtotime('-3 days')));
$googleQuery->setDimensions(['page', 'date']);
$googleQuery->setSearchType('web');
try {
$service = new Google_Service_Webmasters($client);
$response = $service->searchanalytics->query($sitesFetched[0]["site"], $googleQuery);
$siteData = [];
foreach ($response as $row) {
$siteData[] = [
"site" => $row->keys[0],
"date" => $row->keys[1],
"clicks" => $row->clicks,
"impressions" => $row->impressions,
"ctr" => $row->ctr,
"position" => $row->position,
];
}
} catch (\Exception $e) {
$error = json_decode($e->getMessage());
if ($error->error = "invalid_grant") {
echo "You don't have proper permissions to access this site or data is being fetched.";
}
}
}

Testing laravel routes identify method type

How can I get about a Laravel route if the request is a get or post?
I try to test my laravel routes with the following
public function testRoutes()
{
$app = app();
$routes = $app->routes->getRoutes();
/**
* Test if mynamespace routes are redirected to login page if is not the login page
*/
echo PHP_EOL;
foreach ($routes as $route) {
if(strpos($route->getName(),'mynamespace::' ) !== false ) {
$url = $route->uri;
//$appURL = env('APP_URL') .'/';
$response = $this->get($url);
if((int)$response->status() !== 200 ){
echo $url . ' (FAILED) did not return 200. The response is ' . $response->status();
$this->assertTrue(false);
} else {
echo $url . ' (success ?)';
$this->assertTrue(true);
}
echo PHP_EOL;
}
}
}
but I would like exclude post requests for the moment
As we can see the Route class has a property $methods.
Your solution would look something like:
if (in_array('POST', $route->methods)) continue;
It may be interesting for you to look into the testing provided by Laravel itself. A simple way of testing response testing and much more!
Laravel testing.

Composer and Php Google Api Client

This is my composer.json:
{
"require": {
"google/apiclient": "1.0.*#beta"
}
}
And this is my code:
<?
$path = get_include_path() . PATH_SEPARATOR . 'C:\wamp\www\gCalendar\vendor\google\apiclient\src';
set_include_path($path);
define("APIKEY","AIxxxxxxxWA");
define("CLIENTID","xxxkqt.apps.googleusercontent.com");
define("CLIENTSECRET","xxxx");
define("DEVELOPERKEY","xxx.apps.googleusercontent.com");
require_once("config.php");
require_once("vendor/autoload.php");
session_start();
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('CalendarTest');
$client->setClientId(CLIENTID);
$client->setClientSecret(CLIENTSECRET);
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(APIKEY); // 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']);
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) { // extract token from session and configure client
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
echo 'Hello, world.';
?>
I have returned this error:
( ! ) Fatal error: Class 'Google_AnalyticsService' not found in C:\wamp\www\gCalendar\index.php on line 21
What I am doing wrong including the library with Composer?
Thank you so much
The class Google_AnalyticsService does not exist in that library. Try Google_Service instead.
$service = new Google_Service($client);
I know this is old, but I see no answer, and there is not enough about this out there... Does setting the scope to 'https://www.googleapis.com/auth/analytics' help?
All scopes found here:
https://developers.google.com/identity/protocols/googlescopes
<?php
session_start();
$_SESSION = [];
require_once 'vendor/autoload.php';//Composer generated autoload.php(not Google/autoload.php)
$google_api_key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
$clientID = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.apps.googleusercontent.com";
$clientSecret = "AAAAAAAAAAAAAAAAAAAAAAAA";
$scriptUri = "https://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAccessType('online');
$client->setApplicationName('MYAPPNAME');
$client->setClientId($clientID );
$client->setClientSecret($clientSecret);
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey($google_api_key);
$client->addScope('https://www.googleapis.com/auth/analytics');
$service = new Google_Service($client);
if (isset($_GET['logout']))
{
unset($_SESSION['token']);
die('Logged out.');
}
if (isset($_GET['code']))
{
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token']))
{
$token = $_SESSION['token'];
$client->setAccessToken($token);
}
if (!$client->getAccessToken())
{
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die;
}
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
echo 'Hello, world.';
?>
The class used to exists and still get copy pasted along.
Use Google_Service_Analytics now.
In version ^2.0 use like this
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
$analytics = new Google_Service_AnalyticsReporting($client);
...

Joomla logout with message

I'm trying to modify the
'Token Interceptor' system plugin
by joomunited.com
The original plugin redirects on encountering an invalid token error using register_shutdown_function.
I'm trying to get it to:
Log the user out if they are logged in
Redirect to the login page with the invalid token message
Code:
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect('/index.php', JText::_('JINVALID_TOKEN'), 'warning');
I can successfully log the user out and redirect to the login page but the error message is not being displayed.
How can I retain the message after logging the user out?
i've also tried:
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
but that didn't work either...
The solution I came up with was a variation of Alonzo Turner's 2nd post here.
The plugin redirects to the login page with a parameter passed in the url. The onAfterInitialise event then looks for this parameter and displays a message if it's found.
class PlgSystemTokeninterceptor extends JPlugin
{
public function __construct(&$subject, $config = array())
{
parent::__construct($subject, $config);
$app = JFactory::getApplication();
if (($app->isSite() && $this->params->get('use_frontend')) || ($app->isAdmin() && $this->params->get('use_backend')))
{
register_shutdown_function(array($this,'redirectToLogin'));
}
}
public function redirectToLogin()
{
$content = ob_get_contents();
if($content == JText::_('JINVALID_TOKEN') || $content == 'Invalid Token')
{
$app = JFactory::getApplication();
if (!JFactory::getUser()->guest)
{
$app->logout();
}
$app->redirect(JURI::base().'index.php?invalid_token=true');
return false;
}
}
function onAfterInitialise()
{
$app = JFactory::getApplication();
$invalid_token = $app->input->get('invalid_token', 'false');
if ($invalid_token == 'true')
{
$app->enqueueMessage(JText::_('JINVALID_TOKEN'), 'warning');
}
return true;
}
}
When you logout you destroy the session so you are not going to have the message any more.
This will get you a message on redirect.
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
//$app->logout();
$app->redirect($this->redirect);
}
This will not because the session is destroyed
$this->redirect = JUri::base() . 'index.php?option=com_users&view=login';
if (!JFactory::getUser()->guest && $app->input->getCmd('option') != 'com_users')
{
$app->enqueueMessage('message', 'warning');
$app->logout();
$app->redirect($this->redirect);
}
Not tested but
$app->logout()
echo '<div class="">'. JText::_('whatever you want') . '</div>';
$module = JModuleHelper::getModule('login');
$output = JModuleHelper::renderModule($module);
Something like that

Session expiring for twitter oAuth

I am using Abraham Williams' oAuth library to update a status. The application does not have a UI (other than the prompt from Twitter for credentials. Instead, the user enters a URL in the browser.
When the URL is called, I get an error: "Could not post Tweet. Error: Reason: 1".
I inserted some test code, and it seems as if the session is getting lost in between transitions: $_SESSION['tweetmsg'] is set on initial call in index.php, but then when the switch to connect.php happens, it seems as if the session is lost. Any ideas?
Following is the source code:
index.php
<?php
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
session_start();
if (empty($_SESSION['access_token'])) {
$_SESSION['tweetmsg'] = create_tweet_text();
print "<script>self.location='./connect.php');</script>";
}
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['access_token']['oauth_token'],
$_SESSION['access_token']['oauth_token_secret']
);
if (!isset($_SESSION['tweetmsg'])) {
exit('No tweet value in session or from form');
}
$tweetmsg = $_SESSION['tweetmsg'];
$result = $connection->post('statuses/update', array('status' => $tweetmsg));
unset($_SESSION['tweetmsg']);
if (200 === $connection->http_code) {
echo 'Tweet Posted: '.$tweetmsg;
}
else {
echo 'Could not post Tweet. Error: '.$httpCode.' Reason: '.
session_destroy();
}
function create_tweet_text () {
return 'this is a test';
}
connect.php
?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
$request_token = $connection->getRequestToken(OAUTH_CALLBACK.'callback.php');
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
$url = $connection->getAuthorizeURL($request_token);
print "<script>self.location='$url';</script>";
callback.php
<?php
session_start();
include_once '../../winsinclude/tw_config.php';
require_once "../../winsinclude/twitteroauth.php";
require_once "../../winsinclude/OAuth.php";
if (
isset($_REQUEST['oauth_token'])
&& $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']
) {
echo 'Session expired';
}
else {
$connection = new TwitterOAuth(
CONSUMER_KEY,
CONSUMER_SECRET,
$_SESSION['oauth_token'],
$_SESSION['oauth_token_secret']
);
$_SESSION['access_token'] = $connection->getAccessToken($_REQUEST['oauth_verifier']);
print "<script>self.location='index.php';</script>";
}
Recently Twitter deactivated a number of http urls for oAuth and replaced them with https equivalents. If you can see the URL string http://twitter.com/oauth/request_token in the includes then it means you need to follow https://dev.twitter.com/discussions/10803 and change all the calls to https...

Resources