Google Analytics API: Report dimensions and metrics are null - google-analytics

I am using the sample code from https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-php, and printResults is failing because $dimensionHeaders and $dimensions are null
Also, it seems to only work if "ga:" is prepended to the view ID provided by google analytics admin\view\view settings\view ID. Is that correct, or am I using the wrong view ID?

Yes, the correct View ID is what the Google Analytics admin interface is in:
Admin --> View --> View settings --> View ID
Like this:

Google's sample code is missing this key bit in getReport() underneath the line: $request = new Google_Service_AnalyticsReporting_ReportRequest();
//Create the Dimensions object.
$browser = new Google_Service_AnalyticsReporting_Dimension();
$browser->setName("ga:browser");
$request->setDimensions(array($browser));

Related

Set email body content in google appmaker

I want to send an email with a content related to my data such as in following piece of code I found on Datasource script of Google AppMaker Project Tracker template. But I don't understand how it works. How that data.modifiedBy reflect to the record in my datasource?
Any help from the floors? Thanks ..
Look at the Notifications server side script in the template.
It has method notifyAboutItemChanges_ which is passing the data to this record.
function notifyAboutItemChanges_(changes) {
var settings = getAppSettingsRecord_()[0];
if (!settings.EnableEmailNotifications) {
return;
}
var data = {
appUrl: settings.AppUrl,
itemType: changes[0].Type,
itemKey: changes[0]._key,
itemName: changes[0].Name,
modifiedBy: changes[0].ModifiedBy,
changes: changes
};
// Email subject.
var subjectTemplate =
HtmlService.createTemplate(settings.NotificationEmailSubject);
}
This function is passing this data to your settings record.
So no magic here :) You need to pass the data to your record which will be replaced at run time with the values.
For more details on Email refer this sample app.

Firebase Analytics: combine paramaters/values in console-view

I'm new to Firebase (and stackoverflow) and have a question:
Is it possible in the console view for firebase to combine the data? What I want to achieve is that when in "parameter_name" I select for example the "scene_interaction" and automatically the "scene_name" displays only the values for the "scene_interaction"-parameter (and ignoring "button_pressed" and "main"). See screenshot for this:
The event is logged as follow:
parameterEntry = new Firebase.Analytics.Parameter[]
{
new Firebase.Analytics.Parameter("parameter_name", parameterList[i].parameterName),
new Firebase.Analytics.Parameter("action_value", parameterList[i].value),
new Firebase.Analytics.Parameter("action_type", parameterList[i].type),
new Firebase.Analytics.Parameter("scene_name", parameterList[i].scene),
new Firebase.Analytics.Parameter("scene_type", parameterList[i].scene_type)
};
}
Firebase.Analytics.FirebaseAnalytics.LogEvent(eventName, parameterEntry);
I hope someone can help me. Preferably without the use of BigQuery.

Can Google Analytics email me if (crashes and) exceptions occur?

Google Analytics is correctly reporting exceptions thrown by my Android app. And I can use Scheduled Emails to send this report to me. However, receiving a daily email when there isn't anything to report (i.e., the report tells me that zero exceptions occurred) is tedious. Thus, I'd like to receive emails only when there is something to report (i.e., the report tells me that one or more exceptions occurred). It seems that Custom Alerts can be used for this purpose. However, Custom Alerts do not appear to be compatible with Exceptions. This leads me to my question.
Can Custom Alerts be configured to provide email notification on exceptions?
Or, more generally,
Can Google Analytics be configured to provide email notification on exceptions?
Also, does this work for crashes too?
UPDATE (22 Nov 2015, 1 Dec 2015)
(Partial) answer. I provide an answer that enables a server (not Google Analytics) to be configured to provide email notification on exceptions, which is probably a sufficient solution for many.
(Almost an) answer. jakub-kriz has provided a detailed answer, but it does not work as-is. Building upon the answer, I was able to configure Google Analytics to email when no exceptions occur. This is the exact opposite of what is required. Unfortunately, I have been unable to get emails when one or more exceptions occur.
Alternate direction. jakub-kriz has proposed an alternative solution, whereby normal events are used, rather than exception events. I haven't tried this direction.
A complete solution has not yet been proposed.
It is possible, but not in a direct way, you have to hookup you analytics quite dirty.
1) Configuration in Analytics Admin
Create two filters in Admin -> View -> Filters -> Custom -> Advanced
Create filter that listens on hitType exception and set Event Category - Exception
Create filter that replicates Exception description into Event Action
2) Create custom Goal
Create two filters in Admin -> View -> Goals -> Custom -> Event
Event Category equals Exception
3) Create Custom Alert
Custom alert by Goal containg exception
Do not forget your email
Try this and let me know!
To get report on Mail Id there is no way to send directly from google analytics. We can send this error report handling it and send it to programmatically to mail id from our app.
A server (not Google Analytics) can be configured to provide email notification on exceptions, which is probably a sufficient solution for many.
First, you need a service account, which can be created https://console.developers.google.com/project/_/apiui/credential. You'll create a key file (MyAnalytics.p12).
Secondly, we configure our analytics client (MyAnalytics.php):
<?php
//You'll need to install google-api-php-client
//(https://github.com/google/google-api-php-client)
require_once 'Google/autoload.php';
class MyAnalytics
{
//When logged into Google Analytics you'll have a URL that looks
//something like https://www.google.com/analytics/web/?authuser=0#home/a00w11p22/
//Your profile id is everything after the p
const PROFILE_ID = '22';
//This is the service account email that you constructed in step 1
const SERVICE_ACCOUNT_EMAIL = 'blah#developer.gserviceaccount.com';
//This is the file that you constructed in step 1.
const KEY_FILE_LOCATION = 'MyAnalytics.p12';
private $client;
private $analytics;
private $cred;
public function __construct() {
$this->client = new Google_Client();
$this->analytics = new Google_Service_Analytics($this->client);
$key = file_get_contents(self::KEY_FILE_LOCATION);
$this->cred = new Google_Auth_AssertionCredentials(
self::SERVICE_ACCOUNT_EMAIL,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$key
);
}
public function getAnalytics() {
$this->client->setAssertionCredentials($this->cred);
if($this->client->getAuth()->isAccessTokenExpired()) {
$this->client->getAuth()->refreshTokenWithAssertion($this->cred);
}
return $this->analytics;
}
}
?>
Thirdly, we query and report on exceptions (exceptions.php):
<?php
require_once 'MyAnalytics.php';
$myAnalytics = new MyAnalytics();
$analytics = $myAnalytics->getAnalytics();
$results = $analytics->data_ga->get(
'ga:' . MyAnalytics::PROFILE_ID,
'yesterday',
'today',
'ga:exceptions'
);
$a = $results->getTotalsForAllResults();
$count = $a['ga:exceptions'];
echo $count;
if (is_numeric($count) && $count > 0) {
//handle the exception, e.g., send an email
//(cf. https://stackoverflow.com/a/5335311/3664487)
}
?>
Fourth, configure cron to run exceptions.php (cf. https://stackoverflow.com/a/22358929/3664487).

How to get statistics of where visitors come from via URL params

There are many QR codes that contains URL of website such as:(it just demos link)
http://www.popupstore.com/index.php?qrcode_type=magazine&location=Singapore
http://www.popupstore.com/index.php?qrcode_type=banner&location=Vietnam
I need a way can summary to know that where customer come from (nearly same as source/channel in Google Analytics):
Type: Mazazine, banner, etc.
Location: Vietnam, Singapore, etc.
Can anyone help me please :)
You could create two Custom Dimensions, each for Type and another for Country
As per your need define the appropriate Scope of the dimension, a Hit level or Session level scope would be appropriate.
You need to push custom dimensions into Google Analytics i.e. additonal JS code in your site.
ga('send', 'pageview', {
'dimension1': 'Magzine',
'dimension2': 'Singapore'
});
How this works
User scans the code and visits the store
Site has a JS code snippet that would get the query parameters from the URL and sets a custom dimension for each parameter
Setting the custom dimension would let Google Analytics know the value of the Type and Country
It is your JS code that tells Google Analytics what value to take for custom dimension. Google Analytics would not know that the value came from the URL.
To get a query parameter value via javascript you can refer to this answer, If you take the function provided there by Jan Turon (head over and give him an upvote of this helps you):
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
You can use this to dynamically set the dimensions based on the url. You first call the function to return an JSON object that has the key/value pairs from the query parameters, then you insert the needed values to set the dimensions:
result = getJsonFromUrl();
ga('send', 'pageview', {
'dimension1': result.qrcode_type,
'dimension2': result.location
});

Unable to Push Custom Variables w/ Google Tag Manager to GA

I am trying to build remarketing audience lists within Google Analytics using GTM. I need some help figuring out how to pass custom variables via GTM thru the datalayer and into GA.
So far, I have been able to successfully do this by hard coding some custom code and passing custom variables directly into GA (bypassing GTM). However, when I use this code it skews the GA numbers b/c 2 instances of the same GA that are present via custom code, and existing GTM instance. Which is great since it inflates the numbers favorably ;) Unfortunately, we are currently very dependent GTM, and therefore cannot abandon it.
What we are now trying to do is modify the working code to use with GTM so that we are not inflating our numbers as mentioned. Thus far, we can see this data in the datalayer by inspecting the console in chrome. However, we haven’t been able to push this data to GA.
Here is an example of the code that we used previously which does not rely on GTM and is successfully pushing the custom variables to GA.
<script>var _gaq = _gaq || [];_gaq.push(["_setAccount", "UA-XXXXXX-X"]);_gaq.push(['_setCustomVar', 1, "Category", "testing", 3]);_gaq.push(['_setCustomVar', 2, "content-type", "Brief", 3]);_gaq.push(['_setCustomVar', 3, "publish-date", "Wednesday, July 16, 2014 - 17:42", 3]);_gaq.push(['_setCustomVar', 4, "author", "Greg Bates", 3]);_gaq.push(["_trackPageview"]);(function() {var ga = document.createElement("script");ga.type = "text/javascript";ga.async = true;ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";var s = document.getElementsByTagName("script")[0];s.parentNode.insertBefore(ga, s);})();</script>
For the current GTM implementation, there is a bit of a hybridization using GTM and hard coding a newer script which I will detail below.
In my standard GA tag for GTM it is setup as follows:
Tag Name: GA Universal
Tag Type: universal analytics
Tracking ID: UA-XXXXXX-X
Enable Display Advertising Features √
Track Type: Page View
Firing Rules: All pages
More Settings>>Custom Dimensions:
Index = 4 Dimension = {{Author}}
Index = 3 Dimension = {{Publish Date}}
Index = 2 Dimension = {{Content Type}}
Index = 1 Dimension = {{Page Category}}
The custom code that is hardcoded into the page manually is as follows:
<script>
if (Drupal.settings.common !== undefined && Drupal.settings.common.pageCategory !== undefined) {
dataLayer = [{
'pageCategory': Drupal.settings.common.pageCategory
}];
var google_tag_params = {
section: Drupal.settings.common.pageCategory,
pagetype: ' ',
membertype: ' '
};
if (Drupal.settings.common.contentType !== undefined) {
dataLayer.push({'contentType': Drupal.settings.common.contentType});
google_tag_params.contenttype = Drupal.settings.common.contentType;
}
if (Drupal.settings.common.publishDate !== undefined) {
dataLayer.push({'publishDate': Drupal.settings.common.publishDate});
google_tag_params.publishdate = Drupal.settings.common.publishDate;
}
if (Drupal.settings.common.author !== undefined) {
dataLayer.push({'author': Drupal.settings.common.author});
google_tag_params.author = Drupal.settings.common.author;
}
}
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-XXXXXX');</script> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXX" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
I‘ll also add that Drupal.settings.common.author, Drupal.settings.common.contentType, Drupal.settings.common.pageCategory and Drupal.settings.common.publishDate are defined before executing the GTM script.
Can anybody provide some helpful insight as to what we are doing incorrect and what can be done to pass these custom variables into Google Analytics?
If it would be helpful to see a live implementation, please follow this link http://api.pw/Uem8ba .
Thanks in advance of your time and help!
Brett
ok, first of all, since it's Drupal - drop your custom implementation in favor of these two modules:
https://www.drupal.org/project/google_tag
https://www.drupal.org/project/datalayer
Configure GTM container ID, and pass all the data you need via dataLayer - if after enabling all checkboxes in data_layer module you don't have everything you need in data layer, you have to use alter hook from this module, to push your variables there - since your code is ready it should be very easy.
Next, you have to configure GTM to collect your data in GTM and pass it to GA, so:
add a macro choosing "dataLayer variable" as a type
put variable name in the input and name it (it'd be best to name it in the same way for debuging purposes)
repeat 1 and 2 for remaining 3 dimensions
edit your standard GTM GA tag by expanding "more options->custom dimensions" and add there your dimension numbers and varaibles you've configured in steps 1-3.
save updated tag and click "preview button" to launch your site with GTM debug bar at the bottom
check in the debug bar if your data has been passed to dataLayer and then if variables were matched and passed on to GA
nobody said using GTM is simple ;)

Resources