How to create new property in google analytics using javascript code - javascript

This is my first time using analytics api to create new property
I got the below code from here
developers.google.com/analytics/devguides/config/mgmt/v3/mgmtReference/management/webproperties/insert
window.onload = function insertProperty() {
var request = gapi.client.analytics.management.webproperties.insert(
{
'accountId': '123456789',
'resource': {
'websiteUrl': 'http://www.examplepetstore.com',
'name': 'Example Store'
}
});
request.execute(function (response) { console.log(response);});
}
<script src="https://apis.google.com/js/api.js"></script>
when i run the code with valid account id ex:'123456789'
I am getting this error
Uncaught TypeError: Cannot read properties of undefined (reading 'analytics') at insertProperty
what should i do to create new property using this code
The below code is the setup of authorization and rest code
// Replace with your client ID from the developer console.
var CLIENT_ID = '';
// Set authorized scope.
var SCOPES = ['https://www.googleapis.com/auth/analytics.readonly'];
function authorize(event) {
// Handles the authorization flow.
// `immediate` should be false when invoked from the button click.
var useImmdiate = event ? false : true;
var authData = {
client_id: CLIENT_ID,
scope: SCOPES,
immediate: useImmdiate
};
gapi.auth.authorize(authData, function(response) {
var authButton = document.getElementById('auth-button');
if (response.error) {
authButton.hidden = false;
}
else {
authButton.hidden = true;
queryAccounts();
}
});
}
function queryAccounts() {
// Load the Google Analytics client library.
gapi.client.load('analytics', 'v3').then(function() {
// Get a list of all Google Analytics accounts for this user
gapi.client.analytics.management.accounts.list().then(handleAccounts);
});
}
function handleAccounts(response) {
// Handles the response from the accounts list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account.
var firstAccountId = response.result.items[0].id;
// Query for properties.
queryProperties(firstAccountId);
} else {
console.log('No accounts found for this user.');
}
}
function queryProperties(accountId) {
// Get a list of all the properties for the account.
gapi.client.analytics.management.webproperties.list(
{'accountId': accountId})
.then(handleProperties)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProperties(response) {
// Handles the response from the webproperties list method.
if (response.result.items && response.result.items.length) {
// Get the first Google Analytics account
var firstAccountId = response.result.items[0].accountId;
// Get the first property ID
var firstPropertyId = response.result.items[0].id;
// Query for Views (Profiles).
queryProfiles(firstAccountId, firstPropertyId);
} else {
console.log('No properties found for this user.');
}
}
function queryProfiles(accountId, propertyId) {
// Get a list of all Views (Profiles) for the first property
// of the first Account.
gapi.client.analytics.management.profiles.list({
'accountId': accountId,
'webPropertyId': propertyId
})
.then(handleProfiles)
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
function handleProfiles(response) {
// Handles the response from the profiles list method.
if (response.result.items && response.result.items.length) {
// Get the first View (Profile) ID.
var firstProfileId = response.result.items[0].id;
// Query the Core Reporting API.
queryCoreReportingApi(firstProfileId);
} else {
console.log('No views (profiles) found for this user.');
}
}
function queryCoreReportingApi(profileId) {
// Query the Core Reporting API for the number sessions for
// the past seven days.
gapi.client.analytics.data.ga.get({
'ids': 'ga:' + profileId,
'start-date': '7daysAgo',
'end-date': 'today',
'metrics': 'ga:sessions'
})
.then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
document.getElementById('query-output').value = formattedJson;
})
.then(null, function(err) {
// Log any errors.
console.log(err);
});
}
// Add an event listener to the 'auth-button'.
document.getElementById('auth-button').addEventListener('click', authorize);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello Analytics - A quickstart guide for JavaScript</title>
</head>
<body>
<button id="auth-button" hidden>Authorize</button>
<h1>Hello Analytics</h1>
<textarea cols="80" rows="20" id="query-output"></textarea>
<script src="https://apis.google.com/js/client.js?onload=authorize"></script>
</body>
</html>
yes i did , when i click on Authorize i got this Error {error: {code: 403, message: "Request had insufficient authentication scopes.",…}}
not sure why..?

The developer hasn’t given you access to this app. It’s currently being tested and it hasn’t been verified by Google
The issue is that your project is still in testing, you need to add users who you want to grant permission to test your app.
Go to google cloud console Under consent screen look for the button that says "add Users" add the email of the user you are trying to run the app with.

Understanding Property, Account, and View in Google Analytics
Your Analytics profile consists of 3 different components. They are account, property, and view (if you’re using Universal Analytics).
Here’s a closer look at each of them:
Account: You should have at least one account to access the analytics report.
Property: A property can be a website or a mobile app that you’d like to track in Google Analytics and has a unique tracking ID.
View: A view is the access point for your reports if you’re using Universal Analytics. For example, within a property you can have different views for viewing all the data for your website, viewing only a specific subdomain, like blog.example.com, or viewing only Google Ads traffic. Views do not exist in Google Analytics 4.

Related

(Reddit API) How to get a list of subreddits user is subscribed to, using snoowrap?

So I'm using snoowrap to write a Chrome extension that gets a list of subreddits the user is subscribed, and subscribes to them on a different account.
I'm trying to get the list of subreddits currently but can't figure out how to do it. I've tried simply getting the JSON from https://www.reddit.com/subreddits/mine.json, which returns an empty object (persumably because no auth) and I have no idea how to do it via snoowrap. I looked through the documentation and can't find an option for it.
My code:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('login');
login.addEventListener('click', function() {
const r = new snoowrap({
userAgent: '???',
clientId: '<id>',
clientSecret: '<clientsecret>',
username: '<username-here>',
password: '<password-here>'
});
r.getHot().map(post => post.title).then(console.log);
});
var getSubs = document.getElementById('get-subs');
getSubs.addEventListener('click', function() {
fetch('https://www.reddit.com/subreddits/mine.json')
.then(function(data) {
console.log(JSON.stringify(data));
})
.catch(function(error) {
console.log('error');
});
});
});
Not sure how else to try. Anyone have suggestions? I'd like to use snoowrap for this ideally.
When using snoowrap as API wrapper, after connecting to the api with:
const r = new snoowrap({...});
They provide a function for getting your own subscribed subreddits:
r.getSubscriptions();
This will return a Listing Object, which you can use like an Array.

Parse-server social login

I am developing application based on Parse-server and I want to offer social login. I found this guide in the documentation http://docs.parseplatform.org/js/guide/#linking-users.
I started to implement the social login by google. I did following steps:
1) I added following lines to the ParseServer settings
var api = new ParseServer({
...
auth:{
google: {}
},
...
});
2) I did the authentication by hello.js on the client side (call user._linkWith function on login)
hello.init({
google: 'My Google id'
});
hello.on('auth.login', function(auth) {
// Call user information, for the given network
hello(auth.network).api('me').then(function(r) {
const user = new Parse.User();
user._linkWith(auth.network, auth.authResponse).then(function(user){
console.log('You are logged in successfully.');
});
});
});
When I debugged it, I found that it fails in _linkWith() function, when provider object is preparing. Object AuthProviders, which should store all providers, is empty. Because of it the statement provider = authProviders['google']; leads to undefined. Invoking provider.authenticate(...); leads to error "Cannot read property 'authenticate' of undefined"
What am I missing or what am I doing wrong?
Thanks for all your answers.
Honza
Did you register the authenticationProvider? You can find examples in our unit tests on how to do so:
https://github.com/parse-community/parse-server/blob/5813fd0bf8350a97d529e5e608e7620b2b65fd0c/spec/AuthenticationAdapters.spec.js#L139
I also got this error and looked at the _linkWith(provider, options) source code. It checks if options has an authData field (which in turn should contain id and credentials). If so, it uses options.authData. Otherwise it falls back on looking up a previously registered authentication provider mentioned in the previous answer.
This is a fragment of the code I'm using:
const authData = {
"id": profile.getId(),
"id_token": id_token
}
const options = {
"authData": authData
}
const user = new Parse.User();
user._linkWith('google', options).then(function(user) {
console.log('Successful user._linkWith(). returned user=' + JSON.stringify(user))
}, function(error) {
console.log('Error linking/creating user: ' + error)
alert('Error linking/creating user: ' + error)
// TODO handle error
})

Twitter authentication in Codebird JS

I am very new to integrating social sites into a website. I somewhat managed to integrate Facebook, but I have no idea how to integrate Twitter.
I want to login through a Twitter account, then get the username and some other data from Twitter. I have a consumer key and consumer secret. I'm not sure how to proceed from here, and my Google searches haven't helped so far.
I am trying with codebird js:
$(function() {
$('#twitter').click(function(e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("redacted", "redacted");
cb.__call(
"oauth_requestToken",
{ oauth_callback: "http://127.0.0.1:49479/" },
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize",
{},
function (auth_url) {
window.codebird_auth = window.open(auth_url);
}
);
}
}
);
cb.__call(
"account_verifyCredentials",
{},
function(reply) {
console.log(reply);
}
);
})
});
But I get
Your credentials do not allow access to this resource
How can I resolve this and get the user data? I am open to using an alternate Twitter implementation.
You cannot call cb._call( "account_verifyCredentials"... there.
The code only has a request token, NOT an access token, which you will only receive after the user authorizes your app (on the Twitter auth popup).
You are using the "callback URL without PIN" method, as documented on the README. So you'll need to implement that example code on your http://127.0.0.1:49479/ page.
Also, this essentially requires that you store the oauth credentials somewhere. In my example below, I've used localStorage.
$(function () {
$('#twitter').click(function (e) {
e.preventDefault();
var cb = new Codebird;
cb.setConsumerKey("CeDhZjVa0d8W02gWuflPWQmmo", "YO4RI2UoinJ95sonHGnxtYt4XFtlAhIEyt89oJ8ZajClOyZhka");
var oauth_token = localStorage.getItem("oauth_token");
var oauth_token_secret = localStorage.getItem("oauth_token_secret");
if (oauth_token && oauth_token_secret) {
cb.setToken(oauth_token, oauth_token_secret);
} else {
cb.__call(
"oauth_requestToken", {
oauth_callback: "http://127.0.0.1:49479/"
},
function (reply, rate, err) {
if (err) {
console.log("error response or timeout exceeded" + err.error);
}
if (reply) {
console.log("reply", reply)
// stores it
cb.setToken(reply.oauth_token, reply.oauth_token_secret);
// save the token for the redirect (after user authorizes)
// we'll want to compare these values
localStorage.setItem("oauth_token", reply.oauth_token);
localStorage.setItem("oauth_token_secret", reply.oauth_token_secret);
// gets the authorize screen URL
cb.__call(
"oauth_authorize", {},
function (auth_url) {
console.log("auth_url", auth_url);
// JSFiddle doesn't open windows:
// window.open(auth_url);
$("#authorize").attr("href", auth_url);
// after user authorizes, user will be redirected to
// http://127.0.0.1:49479/?oauth_token=[some_token]&oauth_verifier=[some_verifier]
// then follow this section for coding that page:
// https://github.com/jublonet/codebird-js#authenticating-using-a-callback-url-without-pin
});
}
});
}
})
});
Also made a JSFiddle

jQuery undefined object error when initialisation code is skipped for some odd reason

I'am trying to run a Skype SDK on my site, which will allow me to log into Skype initially. The code I'am using is from https://msdn.microsoft.com/EN-US/library/dn962162(v=office.16).aspx but when running the javascript through it complains of an undefined object. Here is the javascript code (ignore the $j, this is needed by us to run jQuery),
/**
* This script demonstrates how to sign the user in and how to sign it out.
*/
$j(function () {
'use strict'; // create an instance of the Application object;
// note, that different instances of Application may
// represent different users
var Application
var client;
Skype.initialize({
apiKey: 'SWX-BUILD-SDK',
}, function (api) {
Application = api.application;
client = new Application();
}, function (err) {
alert('some error occurred: ' + err);
});
// whenever state changes, display its value
client.signInManager.state.changed(function (state) {
$j('#application_state').text(state);
});
// when the user clicks on the "Sign In" button
$j('#signin').click(function () {
// start signing in
client.signInManager.signIn({
username: $j('#username').text(),
password: $j('#password').text()
}).then(
//onSuccess callback
function () {
// when the sign in operation succeeds display the user name
alert('Signed in as ' + client.personsAndGroupsManager.mePerson.displayName());
},
//onFailure callback
function (error) {
// if something goes wrong in either of the steps above,
// display the error message
alert(error || 'Cannot sign in');
});
});
// when the user clicks on the "Sign Out" button
$j('#signout').click(function () {
// start signing out
client.signInManager.signOut()
.then(
//onSuccess callback
function () {
// and report the success
alert('Signed out');
},
//onFailure callback
function (error) {
// or a failure
alert(error || 'Cannot sign in');
});
});
});
When I run this through, it doesn't enter into the "Skype.initialize({" code but jumps to "client.signInManager.state.changed(function (state) {", which is when it throws this error "Uncaught TypeError: Cannot read property 'signInManager' of undefined". When running this though the source debugger in chrome it shows that "Application" is undefined and that "client" is also undefined. So my question is why aren't these 2 objects getting initialised in the Skype.initialize code?
You will have to add the listener, after the client is initialized. So in the initialize "success" callback. The way you have it implemented at the moment, the script tries to add the listener before the client is initialized, on an undefined object attribute, hence the error.

Meteor re-render template after user login

Ok so im using Facebook API graph when the user is logging in using facebook
im getting the user friend list + friends pictures like that:
Template.user_loggedout.events({
"click #fb": function (e, tmp) {
Meteor.loginWithFacebook({
requestPermissions: ['user_likes',
'friends_about_me',
'user_birthday',
'email',
'user_location',
'user_work_history',
'read_friendlists',
'friends_groups',
'user_groups']
}, function (err) {
if (err) {
console.log("error when login with facebook " + err);
} else {
FB.api('/' + Meteor.user().services.facebook.id + '/friends', { fields: 'name,picture' }, function (response) {
if (response && response.data) {
friends = response.data
}
})
}
});
}
and as expected i get friends array inside there are objects(represented as friends).
at some point when the user clicks a link i want to show the user his friends list.
so i got this html:
Template.add_friends.helpers({
friends_list: friends
});
template name="add_friends">
<div class="friends_Page">
{{#each friends_list}}
<li>{{name}}</li>
{{/each}}
</div>
</template>
the problem is that the friends object gets updated after the app as started and when the user clicked the login button using facebook.
so how to re-render when i get the callback from facebook graph api?
i dont want to store the friends in database (its already available thanks to facebook )
The most natural way to force a redraw when data is changed is to use a dependency on that data.
var friends = [];
var friends_dep = new Deps.Dependency();
Template.myTemplate.friends_list = function() {
friends_dep.depend(); /* Causes the helper to rerun when data changes */
return friends;
};
...
function callback() {
...
friends = response.data;
friends_dep.changed(); /* Call this after you set the new data */
}

Categories

Resources