Mathew Smith
Mathew Smith

Reputation: 143

Google Analytics Embed API: How to Auto-Authenticate?

I'm using the Google Analytics Embed API to embed some GA data on a custom dashboard. I'm using the method from the demo site:

https://ga-dev-tools.appspot.com/embed-api/

gapi.analytics.auth.authorize({
   container: 'embed-api-auth-container',
   clientid: 'MY CLIENT ID',
});

This works fine. But it requires the user to authenticate before they can see the data. How do I get around this or auto-authenicate using this method (so anyone that can access the page doesn't have to login)?

Upvotes: 1

Views: 6299

Answers (3)

Aykarnz
Aykarnz

Reputation: 67

I want to use Google Analytics Embed in my admin dashboard. After hours, searching similar posts on stackoverflow, and any other sites found by google search, i have solved my auth problem. Then i want to share.

Firstly, you know, you need some credentials. get your client_id and client_secret keys from https://console.developers.google.com. Add your site(example.com) to authenticated js source... and follow directions...

Secondly, go to https://developers.google.com/oauthplayground/ and select api (Google Analytics Reporting API v4) check https://www.googleapis.com/auth/analytics and https://www.googleapis.com/auth/analytics.readonly And this is important: Before pressing Authorize Apis button, you should press settings button on top rigth side of page. then check "Use your own OAuth credentials" on settings popup and write your own client_id client_secret Now you can press Authorize Apis button. Then press "Exchange authorization code for tokens" button and copy refresh token code. Seems like 1/gwPrtXcdqpC_pDXXXXXXXXXXXXXXXXXzvVA.

So you have client_id, client_secret and refresh_token(taken by your own auth via settings popup)

Let see javascript code:

of course, add

<script>
        (function (w, d, s, g, js, fs) {
            g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
            js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
            js.src = 'https://apis.google.com/js/platform.js';
            fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
        }(window, document, 'script'));
</script>

Then you can use this script as example:

<script>

    //CX Google Auth Process   
    var client_id = "111XXXXXXXXXXXXXXXXson.apps.googleusercontent.com";
    var client_secret = "edXXXXXXXXXXXXXXXXabW";    

    function CXAuth(parameters) {
        var credits= { client_secret: client_secret, grant_type: 'refresh_token', refresh_token: '1/AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXi7', client_id: client_id };
        $.ajax({
            type: "POST",
            url: "https://www.googleapis.com/oauth2/v4/token",
            contentType: "application/x-www-form-urlencoded",
            data: credits,
            dataType: "json",
            success: function (credits) {
                //console.log("CX Auth success");

                gapi.analytics.auth.authorize({
                    serverAuth: {
                        "access_token": credits.access_token,
                        "expires_in": credits.expires_in,
                        "token_type": credits.token_type
                    },
                    container: 'embed-api-auth-container', //Your auth div id in html
                    clientid: client_id,
                    clientsecret: client_secret
                });

            }, error: function (xhr, textStatus, errorThrown) {
                    console.log("cx ajax post error:" + xhr.statusText);                   
                }
        });
    }    

    gapi.analytics.ready(function () {

        CXAuth();

        //CX Get your ids no from https://ga-dev-tools.appspot.com/query-explorer/

        var report = new gapi.analytics.report.Data({
            query: {
                ids: 'ga:18XXXXX',  //Your ids no                  
                //CX ga:visits,ga:sessions,ga:users for Tekil kullanıcı Sayısı-Unique user count
                metrics: 'ga:pageviews',  // Not unique user count  
                dimensions: 'ga:date',
                'start-date': '2018-01-01',
                'end-date': 'today'
            }
        });

        var total = 0;
        report.on('success', function handleCoreAPIResponse(resultsAsObject) {
            if (resultsAsObject.rows.length > 0) {
                resultsAsObject.rows.forEach(function pushNumericColumn(row) {
                    total = Number(total) + Number(row[1]);
                });                    
                document.getElementById("totalCounter").textContent = total;
            }
        });
        report.execute();


        var dataChart = new gapi.analytics.googleCharts.DataChart({
            query: {
                'ids': 'ga:18XXXXX', // <-- Replace with the ids value for your view.
                'start-date': '30daysAgo',
                'end-date': 'today',
                'metrics': 'ga:sessions,ga:users',
                'dimensions': 'ga:date'
            },
            chart: {
                'container': 'site_statistics', //Your div id
                'type': 'LINE',
                'options': {
                    'width': '100%'
                }
            }
        });


        //CX Responsive Google Charts
        window.addEventListener('resize', function () {
            dataChart.execute();                               
        });
        $(document).ready(function () {
            dataChart.execute();             
        });


    });


</script>

and finally in your html like this:

<div id="embed-api-auth-container"></div>
<div id="site_statistics" class="chart"> </div>
<div id="totalCounter">0</div >

if all steps correct, you can get auto refresh token via js on your Admin Dashboard without pressing sign in button manually everytime.

Upvotes: 3

Philip Walton
Philip Walton

Reputation: 30431

Essentially, you're asking about authorizing server side on behalf of your visitors.

Various forms of this question have been asked before, so rather than re-answer I'll just send you some links:

And here's the documentation for the auth method, which discusses the serverAuth option:
https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#auth

Upvotes: 2

user2940137
user2940137

Reputation: 15

I would suggest you follow this:

  1. Go to this website: Google Analytics
  2. SignUp for a Google Analytics Account
  3. Go to the Admin Tab
  4. Create a new Property (put your website URL)
  5. Under new Property go to Tracking Info > Tracking Code, and there is a piece of code
  6. Copy it and put in every JS file of each page you want to track in your site
  7. Go to Reporting Tab on Google Analytics and on the left side click on Real-Time
  8. Start seeing real-time data of visitors of your page

Upvotes: -3

Related Questions