How to get referral flow using google analytics api? - google-analytics

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/

Related

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

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

How can I extract ads form an ad site and view them in a flutter app? , the ad site has been made by the classified listing plugin in wordpress

I have been trying to extract the data of all ads in an ad site and view them in a flutter app.
The ad site has been made by wordpress and its structure is maintained by the classified listing plugin (by RadiusTheme).
I use Postman app to test the api and make the get requests.
Here is the function I used in flutter to get the data:
Future getDataFromServer(String url) async {
var responseBody;
var request = http.Request('GET', Uri.parse(url));
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
responseBody = jsonDecode(await response.stream.bytesToString());
print(responseBody);
} else {
return response.reasonPhrase;
}
return responseBody;
}
Then I pass the url and get the data and present them in a list of widgets.
The url is like this : https://(siteurl)/wp-json/wp/v2/rtcl_listing?per_page=10
but the extension (rtcl_listing) doesn't present the ads with all the details in postman.
The details I mean are the title, the category, the image, the price and the location.
I was able to get the title and the image, but not the rest of the details.
what type of extension should I write after wp-json/wp/v2/ to get the ads with the desired details to present them in the flutter app.

Firebase Cloud Messaging. Set analytics label with nodeJS

I configured FCM with my Node server. and I need to add firebase cloud messaging. and I can send messages successfully. I receive
projects/<project-name>/messages/<some random number as message id>
as the output.
but all the data messages I sent are not visible firebase console cloud-messaging section. I need those for analytics. to check how many people receive my message etc.
const message = {
data: {
...args.data
},
topic
// token
}
const messageResponse = await userFirebase.messaging().send(message);
I checked their documentation and unable to find how to set an analytics label with messaging.
I am using firebase-admin V8.12.1
Java does have a message builder to set this analytics label. How can I do the same thing with nodeJs?
found that we can set the analytics label under fcmOptions.
const message = {
data: {
...args.data
},
topic,
fcmOptions: {
analyticsLabel: "my_analytics_label"
},
};

Integrate Firebase with 3rd party API

I'd like to integrate my firebase project with some 3rd party API's, like the twitter API.
3rd party API
The following code will listen to new tweets containing the certain text 'little rocket man':
var Twitter = require('twitter');
// setup new twitter client
var client = new Twitter({
consumer_key: '',
consumer_secret: '',
access_token_key: '',
access_token_secret: ''
});
// open new twitter stream
let stream = this.client.stream('statuses/filter', { track: 'little rocket man' });
stream.on('data', (event: any) => {
let tweetText = event && event.text; // this should be written to the firebase db
});
Firebase Cloud Functions
The following firebase cloud functions listens to incoming HTTP GET requests on a specific route and saves data back to the firebase db:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'; // Firebase Admin SDK
admin.initializeApp(functions.config().firebase);
// this example uses a HTTP trigger, but how can I trigger it whenever new tweets containint 'little rocket man' are detected??
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
admin.database().ref('/messages').push({original: original}).then(snapshot => {
res.redirect(303, snapshot.ref);
});
});
Question
How can I write the tweets I'm recieving from the twitter client back to the firebase db? If possible, I'd like to run all the code on firebase cloud functions.
Disclaimer:
I'm new to firebase and although googling around for a few hours I wasn't able to find the solution to my problem on the net. I'd like to apologize in advance, should I have overseen it.
You can't use streaming APIs like this in Cloud Functions. A function may only respond to some distinct event, such as an HTTP request, or some change in your database. Functions can't run indefinitely.
If you want to collect tweets that match some query into your database, you can use IFTTT to periodically send them to a function as they become available. I recently finished a small project that does exactly that.

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