Google contact api mobile view issue with get contacts - javascript

I am fetching google contacts using https://www.googleapis.com/auth/contacts.readonly in javascript working fine on website desktop view but when I am changing view to mobile for website this is not working for me please help me to find out this problem with mobile view
sample code
<script src="https://apis.google.com/js/client.js"></script>
function auth() { $('.loader').css('display','block')
var client_id = "<?php echo config::get('app.client_id') ?>";
var scope = 'https://www.googleapis.com/auth/contacts.readonly';
gapi.load('auth', function(){
gapi.auth.authorize(
{ client_id: client_id, scope: scope, immediate: false }, authResult);
})
return false;
}
function authResult(_Result){ if (_Result && !_Result.error)
{ loadPeopleApi(); }}
function loadPeopleApi(){
gapi.client.load('https://people.googleapis.com/$discovery/rest',
'v2', showContacts);
}
function showContacts()
{
var request = gapi.client.people.people.connections.list({
'resourceName': 'people/me',
'pageSize': 1999,
'requestMask.includeField':'person.email_addresses,person.names,person.photos',
'sortOrder':'FIRST_NAME_ASCENDING',
});
request.execute(function(resp) {
})
}

Related

Handle multiple gmail accounts

I am using Google Calendar JavaScript API.It works fine for single account.Problem is when user is logged-in into two of my gmail accounts, It asks user every time to select which account user want to use.
I want API to remember my last selection at least for the session or most preferably till user disconnect himself.
Here is my JS file.
var clientId = $("#CalendarClientId").val();
var scopes = 'https://www.googleapis.com/auth/calendar';
var objEventList = [];
var calendarIdAtt;
function InitilizeCalendarAPI() {
// Step 2: Reference the API key
window.setTimeout(checkAuth, 5);
}
function CheckGoogleCalAuth() {
gapi.auth.authorize({ client_id: clientId, scope: scopes }, HandleAuthCallBack);
}
function checkAuth() {
gapi.auth.authorize({ client_id: clientId, scope: scopes }, HandelCalAuthResult);
}
function CheckAuthentication() {
gapi.auth.checkSessionState({ client_id: clientId }, CheckAuthCallback);
}
function CheckAuthCallback(loginDataCallback) {
if (loginDataCallback == false) {
checkAuth();
$("#googleAuthorize-Button").hide();
}
}
function HandelCalAuthResult(authResult) {
if (authResult && !authResult.error) {
/*authorizeButton.style.visibility = 'hidden';*/
$("#googleAuthorize-Button").hide();
if ($("#googleConnected").length > 0) {
$("#googleConnected").show();
}
/*bind listing of google calendar name in addevent page*/
if ($("#divGoogleCalendarNameList").length > 0) {
GetListOfCalendarNameFromGoogle();
}
} else {
$("#googleAuthorize-Button").show();
/*authorizeButton.style.visibility = '';*/
if ($("#googleConnected").length > 0) {
$("#googleConnected").hide();
}
}
if ($('#googleAuthorized-Button').length > 0) {
$("#googleAuthorize-Button").hide();
$('#googleAuthorized-Button').show();
$('#calenderSettingIcon').attr('data-original-title', 'Connected To Google');
}
}
function CheckAutheForEventList() {
gapi.auth.checkSessionState({ client_id: clientId }, CheckAuthCallbackListEvent);
}
function CheckAuthCallbackListEvent(loginDataCallback)
{
gapi.auth.authorize({ client_id: clientId, scope: scopes }, LoadEventListinAPI);
}
function checkAuthEventList() {
ConfirmConnectionToGoogleCalendar(function (isConnect) {
if (isConnect) {
gapi.auth.authorize({ client_id: clientId, scope: scopes }, LoadEventListinAPI);
}
});
}
function LoadEventListinAPI() {
gapi.client.load('calendar', 'v3', GetAllCalendar);
}
function GetAllCalendar() {
gapi.client.load('calendar', 'v3', GetCalendarAndTheirEvents);
}
function GetCalendarAndTheirEvents() {
objEventList = [];
try {
var objDate = GetMinAndMaxDate();
var finalMinDate = (objDate.MinDate).toISOString();;
var finalMaxDate = (objDate.MaxDate).toISOString();;
var request = gapi.client.calendar.calendarList.list();
var tempCount = 0;
request.execute(function (resp) {
var calLength = resp.items.length;
$.each(resp.items, function (index, item) {
if (item.accessRole == "owner") {
try {
calendarIdAtt = item.id;
var request = gapi.client.calendar.events.list({
'calendarId': item.id,
'showDeleted': false,
'singleEvents': true,
'orderBy': 'startTime',
'maxResults': 100,
'timeMin': finalMinDate,
'timeMax': finalMaxDate
});
request.execute(function (resp) {
tempCount = tempCount + 1;
var events = resp.items;
if (events.length > 0) {
objEventList.push(events);
}
if (tempCount == calLength) {
//Binding Kendo Scheduler with Google Calenda Events
var eventsList = BindEventToCalendar();
LoadEventsScheduler(eventsList);
}
});
}
catch (error) {
tempCount = tempCount + 1;
if (tempCount == calLength) {
BindEventToCalendar();
}
}
}
else {
tempCount = tempCount + 1;
if (tempCount == calLength) {
BindEventToCalendar();
}
}
});
});
return objEventList;
}
catch (exception) {
BindEventToCalendar();
return null;
}
}
//Function will display google calendar events in the Kendo Scheduler
function LoadEventsScheduler(eventsList) {
//This will retrun all the google calendar events to the server side for the scheduler
var request = {
EventsList: eventsList, CalendarAccount: calendarIdAtt
};
$.ajax({
type: "POST",
data: JSON.stringify(request),
url: $_SetEventScheduler,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data;
if (msg.hasOwnProperty("d")) {
data = msg.d;
}
else
data = msg;
if (data.success) {
$("#scheduler").data("kendoScheduler").dataSource.read();
}
else {
}
}
});
}
I noticed that API show me logged in but calendar is not stored in case of multiple accounts,so it asks me again to select the account.
Summary: I want to save the complete scenario (may be calendar_id or any unique identifier) which can tell API which account and which calendar should be picked up.
If you need more details, please let me know.
I simply used the auth2 implementation and it is working perfect.
Basically current session state function do not work properly in old API. That's why it was asking every time for selecting the account and calendar.

login with google plus using javascript

I want to login with google plus using javascript,below is my code
index.html
Here i placed all scripts,html code
<html>
<title>Login With google plus</title>
<meta name="google-signin-client_id"
content="aaaaaaaaaaa.apps.googleusercontent.com ">
<script src="jquery.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?
onload=renderButton" async defer></script>
<script>
function onSuccess(googleUser) {
var profile = googleUser.getBasicProfile();
gapi.client.load('plus', 'v1', function () {
var request = gapi.client.plus.people.get({
'userId': 'me'
});
request.execute(function (resp) {
var profileHTML = '<div class="profile"><div class="head">Welcome
'+resp.name.givenName+'! <a href="javascript:void(0);"
onclick="signOut();">Sign out</a></div>';
profileHTML += '<img src="'+resp.image.url+'"/><div
class="proDetails"><p>'+resp.displayName+'</p>
<p>'+resp.emails[0].value+'</p><p>'+resp.gender+'</p>
<p>'+resp.id+'</p><p>View Google+ Profile
</p></div></div>';
$('.userContent').html(profileHTML);
$('#gSignIn').slideUp('slow');
});
});
}
function onFailure(error) {
alert(error);
}
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
$('.userContent').html('');
$('#gSignIn').slideDown('slow');
});
}
</script>
<div id="gSignIn"></div>
<div class="userContent"></div>
</html>
but when i want to login this error will show.
That’s an error.
Error: invalid_client
The OAuth client was not found.
I can't get this error, please help me to solve this error.
You have to register your application with google console to be able to use the OAuth, You will have to specify the return url after OAuth is granted by the client

Error: Object doesn't support property or method in angular js code for fb login

I am trying to integrate facebook login for my angular JS website. I am getting a pop up and even I am getting some data like my id and username. The issue what I am facing here is when I am trying to redirect the page or sending this data to a handleUser object in my controller, it is not allowing me to call any of the function from that fbLOgin() function block.
It is not allowing me to call any function from dat block... please help me with this.
FBLogin(){
console.log("came into fb ");
FB.init({
appId : 'my_id',
autoLogAppEvents : true,
xfbml : true,
version : 'v2.9'
// js.src = "//connect.facebook.net/en_US/sdk.js";
});
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
// console.log('Good to see you, ' + response.name + '.');
console.log(response.name);
let user = {
"userAccountId":response.name,
"userRole": "CUSTOMER",
"lastOtpRequest": 0,
"fullName": "myname",
"mobileNo": "1234567890",
"emailId": "mymail#gmail.com",
"like": false,
"token": 0,
"loyal": false,
"guest": false,
"enabled": true,
"newCustomer": true
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
}
Actually I am having the same problem with the gmail account also. So what I found here is, we cant call the current object from that promise. So I Created another function from that promise and I m calling that function. The code is as follows..
googleLogin() {
var google = window.gapi;
var currentObject = this;
function authenticateUser(data) {
var user = {};
user.emailId = data.getEmail();
user.fullName = data.getName();
user.socialId = data.getId();
user.username = data.getGivenName();
currentObject.handleUser(user);
}
google.load('auth2', function () {
google.auth2.init({
client_id: ''
}).then(function (auth2) {
if (auth2.isSignedIn.get()) {
var googleUser = auth2.currentUser.get();
authenticateUser(googleUser.getBasicProfile());
} else {
auth2.signIn();
auth2.isSignedIn.listen(onSignIn);
function onSignIn(googleUser) {
console.log(googleUser);
if (googleUser) {
var googleUser = auth2.currentUser.get();
authenticateUser(googleUser.getBasicProfile());
}
}
}
});
});
}

Login Google javascript

I´m using google login javascript.
I want import js after click button. The problem: Only show popup login google the second time I click the button
My Code:
function clickButton(){
$.getScript( "https://apis.google.com/js/client:plusone.js?onload=onLoadGoogleLogin");
}
function onLoadGoogleLogin()
{
var initializedGoogleCallback = false;
gapi.client.setApiKey('AIzaSyBhV6vP_D_I7ldL1YIU7LJUGtSxJ55ievw');
var myParams = {
'callback': function googleLoginCallback(result) {
debugger;
if (!initializedGoogleCallback) {
if (result) {
if (result['error'] == undefined) {
initializedGoogleCallback = true;
gapi.auth.setToken(result);
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get();
request.execute(googleLoginDataUserCallback);
});
}
} else {
alert('Empty authResult');
}
}
},
'clientid': 'xxxxx-4kragpsm6jolann6d9t74crpkthch0iq.apps.googleusercontent.com',
'cookiepolicy': 'single_host_origin',
'requestvisibleactions': 'http://schemas.google.com/AddActivity',
'scope': 'https://www.googleapis.com/auth/plus.login'
}

How to scope correct data in angularfire | firebase | angular | ionic

I'm working on an android game, im using ionic and firebase. I fixed the login: if the user logs in, it checks if the user exists and if not it creates an account.
Now I got a problem scoping the correct data in my controller. I can scope it in html using
{{ user.level }}
I can add data using
users.child($scope.authData.google.cachedUserProfile.id).set({
Username: $scope.authData.google.cachedUserProfile.id
});
i can update data using
user.update({
"level": "Over 9000"
});
But when I try to scope it in my controller it keeps saying undefined or giving me wrong formatted data. (or says user not defined)
var level = user.level;
console.log(level);
my code is
var app = angular.module('starter.controllers', ["firebase"])
//page controller
app.factory("credentials", ["$firebaseAuth",
function($firebaseAuth) {
var FIREB = new Firebase("https://sudokidsapp.firebaseio.com");
return $firebaseAuth(FIREB);
}
]);
app.controller('HomeScreen', function($scope, credentials, $state, $firebaseArray, $firebaseObject) {
credentials.$onAuth(function(authData) {
$scope.authData = authData;
});
$scope.googlelogin = function() {
credentials.$authWithOAuthPopup("google").then(function(authData) {
var users = new Firebase("https://sudokidsapp.firebaseio.com/users");
$scope.users = $firebaseArray(users);
var userId = $scope.authData.google.cachedUserProfile.id;
checkIfUserExists(userId);
function checkIfUserExists(userId) {
var usersRef = new Firebase("https://sudokidsapp.firebaseio.com/users");
usersRef.child(userId).once('value', function(snapshot) {
var exists = (snapshot.val() !== null);
userExistsCallback(userId, exists);
});
}
function userExistsCallback(userId, exists) {
if (exists) {
currentUser = $scope.authData.google.cachedUserProfile.id;
$state.go('app.next');
} else {
$scope.date = JSON.stringify(new Date());
users.child($scope.authData.google.cachedUserProfile.id).set({
Username: $scope.authData.google.cachedUserProfile.id,
Gender: $scope.authData.google.cachedUserProfile.gender || "",
level: 0,
tutorial: true,
world1: true,
world2: false,
world3: false,
world4: false,
world5: false,
stickerset1: true,
stickerset2: false,
stickerset3: false,
stickerset4: false,
stickerset5: false,
character: "none",
date: $scope.date
});
$state.go('app.tutorial');
}
}
}).catch(function(error) {
});
}
});
app.controller("NextControllers", function($scope, $state, credentials, currentUser, $firebaseObject, $firebaseArray) {
var user = currentUser.google.id;
var information = new Firebase("https://sudokidsapp.firebaseio.com/users/" + user);
$scope.information = $firebaseObject(information);
console.log($scope.information);
});
--edit--
Fixed my problem using data snapshot
$scope.UpdateLevel = function(){
information.once("value", function(snapshot) {
var data = snapshot.val();
console.log(data);
console.log(data.level);
console.log(data.world5);
var newdata = data.level + 1 ;
information.update({
"level" : newdata
})
});
}

Categories

Resources