Google Calendar API getting 'Cannot read property 'signIn' of null' - javascript

I'm trying to use Google's Calendar API to get info on specific calendar. I keep getting this error Cannot read property 'signIn' of null. I'm using the example online here https://developers.google.com/google-apps/calendar/quickstart/js.
Any idea why this is happening? And can someone give me a more simple way to get calendar data? Basically I want to know which rooms in my calendar feed are free to book. Can I do this using the calendar API?
const CLIENT_ID = '418414126140-u5u3r2ampke8egh7d2tk50ferkl8ri26.apps.googleusercontent.com';
const SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];
app.factory('getCalendar', ['$q', function($q){
return function checkAuth() {
var deferred = $q.defer();
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
handleClientLoad();
function initClient() {
gapi.client.init({
"client_id": CLIENT_ID,
"scope": SCOPES
}).then(function () {
gapi.auth2.getAuthInstance().signIn();
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
console.log("You are authorized");
listUpcomingEvents();
} else {
console.log("You are not authorized");
}
}
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
console.log(response);
deferred.resolve(response);
});
}
return deferred.promise;
} //return ends here
}]);

Try using gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); instead of gapi.auth2.getAuthInstance().signIn();. You may refer with this sample code on how to use the Google JavaScript Client API Library to authenticate and interact with the API.
Also check this related SO thread and see if it helps.
UPDATE:
Any idea on how to check which rooms on your calendar are available or not?
You may check on this link: Google Calendar Api, Is meeting Room available?
You will need to be authenticated as a user that has read-access to the room. Then you can take the resourceEmail field of the Calendar Resource API and use it as a calendarId in the events.list() Calendar API call.

Related

How to create new property in google analytics using javascript code

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.

calling a Google Cloud Functions with parameters from browser using Javascript

I am trying to stream some events in batches from a mobile web site to BigQuery, and I am trying to trigger a Google Cloud Function to do this via parameters.
I've reached the point to initilise de script, but how do I call a Google Cloud Function with param?
<script src="https://apis.google.com/js/api.js"></script>
<script>
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// Your API key will be automatically added to the Discovery Document URLs.
'discoveryDocs': ['https://people.googleapis.com/$discovery/rest'],
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
});
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
</script>
I hope you found a solution for it... but I usually do:
var getPeople = gapi.client.people.people.get({
'resourceName': 'people/me',
'requestMask.includeField': 'person.names'
});
getPeople.execute(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});

API key not valid error when trying to get profile data

I'm trying to test Google login API. I want to retrieve some basic data after the client logs.
I created a Google API Console project and client ID (https://developers.google.com/identity/sign-in/web/devconsole-project)
Here is google official code (https://developers.google.com/api-client-library/javascript/samples/samples#LoadinganAPIandMakingaRequest):
<html>
<head>
</head>
<body>
<script type="text/javascript">
function handleClientLoad() {
// Loads the client library and the auth2 library together for efficiency.
// Loading the auth2 library is optional here since `gapi.client.init` function will load
// it if not already loaded. Loading it upfront can save one network request.
gapi.load('client:auth2', initClient);
}
function initClient() {
// Initialize the client with API key and People API, and initialize OAuth with an
// OAuth 2.0 client ID and scopes (space delimited string) to request access.
gapi.client.init({
apiKey: '5v2RzP7-xyQGNjxrD5suoPL9',
discoveryDocs: ["https://people.googleapis.com/$discovery/rest?version=v1"],
clientId: '298062822261-e5c09q8191mkho0o7n3n3obiq2eq2p3f.apps.googleusercontent.com',
scope: 'profile'
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
});
}
function updateSigninStatus(isSignedIn) {
// When signin status changes, this function is called.
// If the signin status is changed to signedIn, we make an API call.
if (isSignedIn) {
makeApiCall();
}
}
function handleSignInClick(event) {
// Ideally the button should only show up after gapi.client.init finishes, so that this
// handler won't be called before OAuth is initialized.
gapi.auth2.getAuthInstance().signIn();
}
function handleSignOutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function makeApiCall() {
// Make an API call to the People API, and print the user's given name.
gapi.client.people.people.get({
resourceName: 'people/me'
}).then(function(response) {
console.log('Hello, ' + response.result.names[0].givenName);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
<button id="signin-button" onclick="handleSignInClick()">Sign In</button>
<button id="signout-button" onclick="handleSignOutClick()">Sign Out</button>
</body>
</html>
ClientId and apikey are from my google api.
I receive error 400
{
"error": {
"code": 400,
"message": "API key not valid. Please pass a valid API key.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.Help",
"links": [
{
"description": "Google developers console",
"url": "https://console.developers.google.com"
}
]
}
]
}
}
I don't understand what's wrong whit my api key. I followed all the steps from google documentation.
It seems you are using the client secret as API key. Isn't it?
To obtain an API key you must create it.
Under credentials (dev console) click on create credential, and then 'API Key'

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

Persistent Firebase OAuth Authentication

I'm trying to persist the Firebase user authentication state across multiple pages.
$scope.loginGoogle = function() {
console.log("Got into google login");
ref.authWithOAuthPopup("google", function(error, authData) {
$scope.loggedIn = true;
$scope.uniqueid = authData.google.displayName;
}, {
remember: "sessionOnly",
scope: "email"
});
};
function checkLogin() {
ref.onAuth(function(authData) {
if (authData) {
// user authenticated with Firebase
console.log("User ID: " + authData.uid + ", Provider: " + authData.provider);
} else {
console.log("Nope, user is not logged in.");
}
});
};
However, when the checkLogin function is called in another page, authData is not defined, even though the user has logged in on the login page. What seems to be the matter?
There are two things to know here.
First, you're using the JS Client auth methods in conjunction with AngularFire. While this is not a bad thing, you need to be aware of a few gotchas.
Second, you can use the $firebaseAuth module in AngularFire 0.9 to not deal with all of the crazy stuff below.
When using Firebase JS client level functions, Angular will not always pick up on them due to its digest loop. This is true for any external JS library. The way to get around this is to use the $timeout service.
CodePen
// inject the $timeout service
app.controller("fluttrCtrl", function($scope, $firebase, $timeout) {
var url = "https://crowdfluttr.firebaseio.com/";
var ref = new Firebase(url);
$scope.loginGoogle = function() {
console.log("Got into google login");
ref.authWithOAuthPopup("google", function(error, authData) {
// wrap this in a timeout to allow angular to display it on the next digest loop
$timeout(function() {
$scope.loggedIn = true;
$scope.uniqueid = authData.google.displayName;
});
}, {
remember: "sessionOnly",
scope: "email"
});
});
});
By wrapping the $scope properties in the $timeout another cycle will be run and it will display on the page.
Ideally, you don't want to deal with this yourself. Use $firebaseAuth module built into AngularFire. You need to upgrade to the 0.9 version to use the module.

Categories

Resources