Get a count of currently active users from Google RealTime API (GA4) - google-analytics

The bounty expires in 2 days. Answers to this question are eligible for a +100 reputation bounty.
thumbtackthief wants to draw more attention to this question.
I'm trying to get a count of the number of people currently viewing my site. With Google Analytics about to switch over to GA4 from UA, I figure it's best to use GA4 but the documentation--especially for the API--is pretty weak. I believe I need to query the Realtime API but I'm having trouble putting together the request to do it. Right now I'm stuck on the authorization step, but I'm not really sure any of it makes sense in the first place. I've created a service account in Google Analytics.
Here's what I have at the moment, cobbled together from a variety of sources, currently giving me a 401 error:
<div id="active-users"></div>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="{SERVICE_CLIENT_ID}.apps.googleusercontent.com">
<script>
// Load the Google Analytics API client library
gapi.load('client', function () {
gapi.client.init({
client_id: '{SERVICE_CLIENT_ID}',
apiKey: '{API_KEY}'
}).then(function () {
gapi.client.request({
path: '/v1/data/realtime:get',
params: {
ids: 'GA4:{PROPERTY_ID}',
metrics: 'rt:activeUsers'
}
}).then(function (response) {
var activeUsers = response.result.totalsForAllResults['rt:activeUsers'];
document.getElementById('active-users').innerHTML = 'Active users: ' + activeUsers;
});
});
});
</script>
EDIT:
I am trying to follow this documentation, which seems relevant, but I can't find any information on how to translate this to the Client Library

Related

LinkedIn API V1 - Receiving “Unauthorized request” when posting to Companies/{companyId}/shares

We are receiving 403 responses when posting to the company shares endpoint.
This happens when using the example company 2414183 and our chosen company.
The call to is-company-share-enabled endpoint is successful.
We are checking that the user is authenticated before making the request.
The LinkedIn profile we are using is set up as an company admin.
The domains we are calling from have been added to the Valid SDK Domains list.
It looks like the app usage & limits is counting these failed requests.
We can successfully post from Postman to both companies shares with varying payloads (using Postmans in built OAuth 2.0).
Would anyone be able to help us with this?
Here are some of the failed request ids
58LETKI9LD
RBG4DRL5VT
XYCOX9XID1
JPY6AORIKW
The code being used is mostly from the developer guides.
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [removed]
authorize: false
</script>
$scope.postToLinkedInCompanyPage = function () {
if (!IN.User.isAuthorized()) {
IN.User.authorize(shareLinkedInCompanyPageContent);
}
else {
shareLinkedInCompanyPageContent();
}
};
function shareLinkedInCompanyPageContent() {
if (!IN.User.isAuthorized()) {
console.error("User not authorized");
return;
}
var payload = {
"comment": "Check out developer.linkedin.com! http://linkd.in/1FC2PyG",
"visibility": {
"code": "anyone"
}
};
var cpnyID = [removed];
IN.API.Raw("/companies/" + cpnyID + "/shares?format=json")
.method("POST")
.body(JSON.stringify(payload))
.result(onSuccess)
.error(onError);
}
function onSuccess(data) {
console.log(data);
}
function onError(error) {
console.log(error);
}
06/12/2018 - Update
I tried the code out into a simple web app.
Converting the angular into plain JavaScript.
When posting to the test company 2414183, I still receive 403
POST https://api.linkedin.com/v1/companies/2414183/shares?format=json 403
{errorCode: 0, message: "Unauthorized request", requestId: "259UFIKLIR", status: 403, timestamp: 1544085898666}
Version 1 of the API is no longer supported.
Here is an extract from the LinkedIn dev blog
Update: As of May 1, 2019, Version 1.0 of our API is no longer
supported. Applications requesting Version 1.0 APIs may experience
issues as we begin to remove services. To find the latest updates, go
to the new LinkedIn Developers site at
https://www.linkedin.com/developers/. You can learn more about our
Version 2.0 APIs, our developer program, and how to migrate your apps.
I'll update the tags and header so this isn't picked up in future searches

LinkedIn JavaScript SDK "You must specify a valid JavaScript API Domain as part of this key's configuration."

I want to show our LinkedIn company recent updates inside our web site. so i follow these steps, to integrate with LinkedIn JavaScript SDK # https://developer.linkedin.com/docs/getting-started-js-sdk . mainly i did the following steps:-
1- I created a new application .
2- then i add the following domains inside the "Valid SDK Domains". since the site i want to show the linkedin data inside it is a sharepoint online site which has the following url https://ourcompanyname.sharepoint.com :-
3- then inside my sharepoint page , i added the following script, to get the information from LinkedIn:-
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 0**********c
</script>
<script>
alert("1");
var liLogin = function() { // Setup an event listener to make an API call once auth is complete
IN.UI.Authorize().params({"scope":["r_basicprofile", "r_emailaddress"]}).place();
IN.Event.on(IN, 'auth', getProfileData);
}
var getProfileData = function() { // Use the API call wrapper to request the member's basic profile data
alert("2");
IN.API.Profile("me").fields("id,firstName,lastName,email-address,picture-urls::(original),public-profile-url,location:(name)").result(function (me) {
var profile = me.values[0];
var id = profile.id;
var firstName = profile.firstName;
var lastName = profile.lastName;
var emailAddress = profile.emailAddress;
var pictureUrl = profile.pictureUrls.values[0];
var profileUrl = profile.publicProfileUrl;
var country = profile.location.name;
alert(id);
});
}
</script>
<p>testing</p>
but on the browser i got the following error:-
Error: You must specify a valid JavaScript API Domain as part of this key's configuration. userspace:22:9
<anonymous>
https://www.linkedin.com/uas/js/userspace:22:9
<anonymous>
https://www.linkedin.com/uas/js/userspace:1:2
EDIT
Now based on #Lars Hendriks advice, i waited for 2 hours and i can see that the You must specify a valid JavaScript API Domain as part of this key's configuration. error is no longer showing inside my browser F12 console. but at the same time i can not see any data returned from the JavaScript call, even the alert("2") & alert(id) inside my above JavaScript did not get popup.. not sure what is going on ?
what you could try is :
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: 0**********c
authorize: true
</script>
if this does not work , you might want to have to wait :
After registering an API key and specifying a valid domain, it may
take up to 30 minutes for the changes to take affect, so if it doesn't
work immediately, go grab a coffee and check back in a few.

How to get referral flow using google analytics api?

I have a node application. Here I'm trying to fetch the referral flow from google analytics using Google API. I have mentioned the dimensions, metrics and other required parameters. Here is my code snippet,
// imported googleapis npm module
import google from "googleapis";
const analytics = google.analytics("v3");
// This is my payload to get the required analytics data
const analyticsData = {
auth: oauth2Creds,
accountId: "accountID",
webPropertyId: "webPropertyID",
profileId: "profileID",
ids: "ga:id",
"start-date": "90daysAgo",
"end-date": "today",
metrics: "ga:pageValue,ga:pageviews,ga:entranceRate,ga:exitRate",
dimensions: "ga:fullReferrer",
"start-index": "1"
};
// Function to get analytical data using the above payload
analytics.data.ga.get(analyticsData, (err, result) => {
// I will get the results here
console.log(result);
});
Here it returns only the data related to the entrance. But I need to get the flow for each referral visits. For ex, if a user enters into the home page from google and moves to page2, page3 and exits the website, then I need to track this flow. How can this be done using google analytics API?
I might not be answering your question directly but I think the following documentation might assist you.
https://developers.google.com/analytics/devguides/reporting/mcf/v3/

Google Cloud Print or other service to auto print using C# or PHP

Are there ANY code examples of how to use Google Cloud Print (using the new OAuth 2) and how when a document comes into the Google Cloud Print queue to automatically print it?
Pretty much what I am trying to do is not spend thousands of dollars that when an order is submitted to our online store, that the order automatically gets printed to our printer. Any ideas, pointers, code examples.
I have done a bunch of searching, and a lot of examples using C#, use Google's old service, not the OAuth2, documentation.
Pretty much, I need a service that will sent a print command to our printer when we get an order in. I can write the part from the store to the service, it is the service to the printer part I have a ton of trouble with.
Thanks in advance.
There's a brilliant PHP class you can download and use that does exactly that:
https://github.com/yasirsiddiqui/php-google-cloud-print
The problem with what you want to achieve is that Google Cloud Print is meant for authenticated users submitting their own print jobs. If I understand correctly, you want to have the server submit a print job as a callback after receiving an order. Therefore, print jobs need to be submitted by a service account, not a Google user. This can be done (we use it in production at the company I work for) using a little hack, described here:
Share printer with Google API Service Account
I can't help you with C# or PHP code, basically you need to be able to make JWT authenticated calls to Google Cloud Print, here you are a code snippet in NodeJS, hope it helps:
var request = require('google-oauth-jwt').requestWithJWT();
service.submitJob = function(readStream,callback) {
// Build multipart form data
var formData = {
printerid: cloudPrintConfig.googleId,
title: 'My Title',
content: readStream,
contentType: "application/pdf",
tag: 'My tag',
'ticket[version]': '1.0',
'ticket[print]': ''
};
// Submit POST request
request({
uri: cloudPrintConfig.endpoints.submit,
json: true,
method: 'post',
formData: formData,
jwt: cloudPrintConfig.jwt
}, function (err, res, body) {
if (err) {
callback(err,null);
} else {
if (body.success == false) {
callback('unsuccessful submission',null);
} else {
callback(null, body);
}
}
});
}
Details about JWT credentials can be found here

Need good example: Google Calendar API in Javascript

What I'm trying to do:
Add events to a google calendar from my site using javascript.
What I can't do:
Find a good tutorial/walk through/example for the google calendar api. All the documentation I've been able to find links back and forth between v1 and v2 api's, or the v3 api doesn't seem to be client based.
For those that are curious, the site I'm developing this for:
http://infohost.nmt.edu/~bbean/banweb/index.php
Google provides a great JS client library that works with all of Google's discovery-based APIs (such as Calendar API v3). I've written a blog post that covers the basics of setting up the JS client and authorizing a user.
Once you have the basic client enabled in your application, you'll need to get familiar with the specifics of Calendar v3 to write your application. I suggest two things:
The APIs Explorer will show you which calls are available in the API.
The Chrome developer tools' Javascript console will automatically suggest method names when you are manipulating gapi.client. For example, begin typing gapi.client.calendar.events. and you should see a set of possible completions (you'll need the insert method).
Here's an example of what inserting an event into JS would look like:
var resource = {
"summary": "Appointment",
"location": "Somewhere",
"start": {
"dateTime": "2011-12-16T10:00:00.000-07:00"
},
"end": {
"dateTime": "2011-12-16T10:25:00.000-07:00"
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': resource
});
request.execute(function(resp) {
console.log(resp);
});
Hopefully this is enough to get you started.
this should do the trick
//async function to handle data fetching
async function getData () {
//try catch block to handle promises and errors
try {
const calendarId = ''
const myKey = ''
//using await and fetch together as two standard ES6 client side features to extract the data
let apiCall = await fetch('https://www.googleapis.com/calendar/v3/calendars/' + calendarId+ '/events?key=' + myKey)
//response.json() is a method on the Response object that lets you extract a JSON object from the response
//response.json() returns a promise resolved to a JSON object
let apiResponse = await apiCall.json()
console.log(apiResponse)
} catch (error) {
console.log(error)
}
}
getData()

Resources