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.