I am trying to create event via my website.I am not getting any response while post event.
Below is my code
<div id="fb-root"></div>
<span id='fbinfo'><fb:name uid='loggedinuser' useyou='false'></fb:name></span>
<div id="fb-root"></div>
<span id='fbinfo'><fb:name uid='loggedinuser' useyou='false'></fb:name></span>
<!-- USE 'Asynchronous Loading' version, for IE8 to work
http://developers.facebook.com/docs/reference/javascript/FB.init/
<script type="text/javascript" src="<%=path%>/js/socialNetwork.js"></script> -->
<script>
FB.init({appId: appid, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
// alert("fbtoken"+fbtoken);
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
else{
loginFB();
}
// alert("fbtoken 2"+fbtoken);
});
function loginFB() {
FB.login(function(response) {
if (response.status === 'connected') {
// var session = FB.getSession();
fbtoken = response.authResponse.accessToken;
fbuserid = response.authResponse.userID;;
}
}, {scope:’create_event'});
// alert("fbtoken"+fbtoken);
}
function logoutFB() {
FB.logout(function(response) {
// user is now logged out
});
}
function createEvent(name, startTime, endTime, location, description) {
var eventData = {
"access_token": fbtoken,
"start_time" : startTime,
"end_time": endTime,
"location" : location,
"name" : name,
"description": description,
"privacy":"OPEN"
};
FB.api("/me/events","post",eventData,function(response){
alert(response.error);
if (!response || response.error) {
alert("Response "+response.id);
} else {
alert("Post ID: " + response.id);
}
});
}
function createMyEvent(){
var name = "My Amazing Event";
var startTime = "10/29/2015 12:00 PM";
var endTime = "10/29/2015 06:00 PM";
var location = "Dhaka";
var description = "It will be freaking awesome";
createEvent(name, startTime,endTime, location, description);
alert(name);
}
</script>
I am getting the response.id as invalid.
So because of that i think event is not created on my FB wall..
Can someone please help me on this.
You cannot create events via the Graph API.
Source: https://developers.facebook.com/docs/graph-api/reference/v2.3/event#publish
Changelog: https://developers.facebook.com/docs/apps/changelog#v2_0_games
Related
I am using an internal service to Authenticate my Gsuite add-on. The Issue is we cannot find any request made from the Add-on to internal servers on Prod (or Dev environments). These are public facing authentication endpoints.
Currently this Addon only runs in Gmail. Unsure If there are any bandwidth limits we might be reaching but Google support said they couldn't help.
We followed the docs Google provides for 3rd Part Oauth.
auth File:
function accessProtectedResource(url, method_opt, headers_opt, body) {
var service = getOAuthService();
var maybeAuthorized = service.hasAccess();
if (maybeAuthorized) {
// A token is present, but it may be expired or invalid. Make a
// request and check the response code to be sure.
// Make the UrlFetch request and return the result.
var accessToken = service.getAccessToken();
var method = method_opt || 'get';
var headers = headers_opt || {};
headers['Authorization'] = Utilities.formatString('Bearer %s', accessToken);
var resp = UrlFetchApp.fetch(url, {
'headers': headers,
'method' : method,
'contentType': 'application/json',
'muteHttpExceptions': true, // Prevents thrown HTTP exceptions.
'payload': JSON.stringify(body)
});
var code = resp.getResponseCode();
if (code >= 200 && code < 300) {
return resp.getContentText('utf-8'); // Success
} else if (code >= 400 && code <= 403) {
// Not fully authorized for this action.
maybeAuthorized = false;
} else {
// Handle other response codes by logging them and throwing an exception.
Logger.log('Server error (%s): %s', code.toString(),
resp.getContentText('utf-8'));
throw ('Backend server error: ' + code);
}
}
if (!maybeAuthorized) {
// Invoke the authorization flow using the default authorization
// prompt card.
CardService.newAuthorizationException()
.setAuthorizationUrl(service.getAuthorizationUrl())
.setCustomUiCallback('createCompanyeAuthorizationUi')
.setResourceDisplayName('Company')
.throwException();
}
}
function getOAuthService() {
// added Console.log for debug
var service = OAuth2.createService('COMPANY_AUTH')
var servicewithurl = service.setAuthorizationBaseUrl(urlBase + '/oauth2/authenticate/');
var setauthBase = servicewithurl.setAuthorizationBaseUrl(urlBase + '/oauth2/authenticate/');
console.log('setauthBase ', setauthBase);
var setToken = setauthBase.setTokenUrl(urlBase + '/oauth/token/');
console.log('setToken ',setToken);
var setCallback = setToken.setCallbackFunction('authCallback');
console.log('setCallback ', setCallback);
setCallback.setClientId('2222TW9LzuT4AgAMN')
.setClientSecret('WZN5tyDKfMYoDLNnC')
.setPropertyStore(PropertiesService.getUserProperties());
.setCache(CacheService.getUserCache())
console.log('setCallback2 ', setCallback);
return setCallback;
}
function authCallback(callbackRequest) {
var authorized = getOAuthService().handleCallback(callbackRequest);
if (authorized) {
return HtmlService.createHtmlOutput(
'Success! <script>setTimeout(function() { top.window.close() }, 1);</script>');
} else {
return HtmlService.createHtmlOutput('Denied');
}
}
function createCompanyAuthorizationUi() {
var service = getOAuthService();
var authUrl = service.getAuthorizationUrl();
var authAction = CardService.newAuthorizationAction().setAuthorizationUrl(authUrl);
var CompanyLogo = CardService.newImage().setAltText("Company Logo").setImageUrl("image_url_replaced");
var headerText = 'Create actions in Company from your email.';
var mainImage = CardService.newImage().setAltText("Company Mail").setImageUrl("image_url_replaced");
var loginButton = CardService.newImage().setAltText("Login").setImageUrl("image_url_replaced").setAuthorizationAction(authAction);
var signupLink = CardService.newOpenLink()
.setUrl(urlBase + "/join")
.setOpenAs(CardService.OpenAs.FULL_SIZE)
.setOnClose(CardService.OnClose.NOTHING);
var signupButton = CardService.newImage().setAltText("Sign up").setImageUrl("image_url_replaced").setOpenLink(signupLink);
var featureOne = CardService.newKeyValue()
.setIconUrl("image_url_replaced")
.setContent("Company is the best way to plan, execute, and monitor all of your teams's projects in one place.")
.setMultiline(true);
var featureTwo = CardService.newKeyValue()
.setIconUrl("image_url_replaced")
.setContent("Content here")
.setMultiline(true);
var card = CardService.newCardBuilder()
.addSection(CardService.newCardSection()
.addWidget(CardService.newTextParagraph())
.addWidget(CompanyLogo)
.addWidget(CardService.newTextParagraph().setText(headerText))
.addWidget(mainImage)
.addWidget(signupButton)
.addWidget(loginButton)
.addWidget(featureOne)
.addWidget(featureTwo)
).build();
return [card];
}
function resetOAuth() {
getOAuthService().reset();
}
function getCompanyResourceUrls() {
accessProtectedResource(urlBase + '/api/v1/books/');
}
function makeRequest(url, params) {
var oauthService = getOAuthService();
var response = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + oauthService.getAccessToken()
},
body: params
});
return response;
}
function getUserId() {
var cache = CacheService.getUserCache();
var userId = cache.get('userId');
if(userId) {
return userId;
}
var response = accessProtectedResource(urlBase + '/oauth/getIdentity');
var data = JSON.parse(response);
var userId = data.data.id;
cache.put('userId', userId);
return userId;
}
appsscript.json
{
"timeZone": "America/New_York",
"dependencies": {
"libraries": [{
"userSymbol": "OAuth2",
"libraryId": "",
"version": "37",
"developmentMode": true
}]
},
"webapp": {
"access": "ANYONE",
"executeAs": "USER_ACCESSING"
},
"oauthScopes": ["https://www.googleapis.com/auth/gmail.addons.execute", "https://www.googleapis.com/auth/gmail.addons.current.message.readonly", "https://www.googleapis.com/auth/script.external_request"],
"urlFetchWhitelist": ["https://company.com/", "https://company.com/oauth/token/", "https://company.com/api/v1/books/", "https://companycom/oauth/revoke"],
"runtimeVersion": "V8",
"gmail": {
"name": "Name",
"logoUrl": "https://logourl.com",
"contextualTriggers": [{
"unconditional": {
},
"onTriggerFunction": "buildAddOn"
}],
"universalActions": [{
"text": "Logout",
"runFunction": "logout"
}],
"primaryColor": "#ffffff",
"secondaryColor": "#ffffff",
"authorizationCheckFunction": "getCompanyResourceUrls",
"openLinkUrlPrefixes": ["https://company.com/"]
}
}
You made mistake:
.setCustomUiCallback('createCompanyeAuthorizationUi')
but you have
createCompanyAuthorizationUi
I am not sure, but it can help you.
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.
I have limited experience working with JavaScript and am attempting to pass a client token generated on my server into the braintree client create of Braintree's javascript code. I do not know how to pass the ClientToken out of the jQuery post and into the authorization section of braintree.client.create. A portion of my code is below:
<script src="https://js.braintreegateway.com/web/3.34.0/js/client.min.js"></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/hosted-fields.min.js"></script>
<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
<script src="https://js.braintreegateway.com/web/3.34.0/js/paypal-checkout.min.js"></script>
<script>
var form = document.querySelector('#register-form');
var submit = document.querySelector('input[type="submit"]');
var ClientToken;
var authPosting = jQuery.post('/path/to/php_scripts/getClientToken.php');
authPosting.done(function( data ) {
ClientToken = data;
console.log(ClientToken);
});
braintree.client.create({
authorization: 'ClientToken'
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
}
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '15px',
'font-family': 'roboto, verdana, sans-serif',
'font-weight': 'lighter',
'color': 'black'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': 'black'
},
'.invalid': {
'color': 'black'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: ''
},
cvv: {
selector: '#cvv',
placeholder: ''
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YY'
},
postalCode: {
selector: '#postal-code',
placeholder: ''
}
}
}, function(err, hostedFieldsInstance) {
if (err) {
console.error(err);
return;
}
function findLabel(field) {
return jQuery('.hosted-field--label[for="' + field.container.id + '"]');
}
hostedFieldsInstance.on('focus', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).addClass('label-float').removeClass('filled');
jQuery(".error-msg").hide();
});
// Emulates floating label pattern
hostedFieldsInstance.on('blur', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isEmpty) {
label.removeClass('label-float');
} else if (field.isValid) {
label.addClass('filled');
} else {
label.addClass('invalid');
}
});
hostedFieldsInstance.on('empty', function (event) {
var field = event.fields[event.emittedBy];
findLabel(field).removeClass('filled').removeClass('invalid');
});
hostedFieldsInstance.on('validityChange', function (event) {
var field = event.fields[event.emittedBy];
var label = findLabel(field);
if (field.isPotentiallyValid) {
label.removeClass('invalid');
} else {
label.addClass('invalid');
}
});
//Submit function
jQuery("#register-form").validate({
submitHandler: function(form) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (err, payload) {
if (err) {
if (err.code === 'HOSTED_FIELDS_FIELDS_EMPTY') {
var msg = "All credit card fields are required.";
jQuery(".error-msg").text(msg);
jQuery(".error-msg").show();
} else if (err.code === 'HOSTED_FIELDS_FIELDS_INVALID') {
var invalidFields = err.details.invalidFieldKeys;
invalidFields.forEach(function (field) {
if (field == "number") {
var myid = "card-number";
var myobj = "credit card number";
} else if (field == "expirationDate") {
var myid = "expiration-date";
var myobj = "expiration date";
}
jQuery("#" + myid).append("<div class='error-msg'>Please enter a valid " + myobj + ".</div>");
});
} else {
var msg = "There was an error on the form."
alert (msg);
}
return;
}
vfirst = jQuery( "input#firstname" ).val(),
vlast = jQuery( "input#lastname" ).val(),
vemail = jQuery( "input#email" ).val(),
vproof = jQuery( "input[name='proof']" ).val(),
vprice = jQuery( "tr#total td.price" ).data('price'),
vcourse = 1950,
vnonce = 'fake-valid-nonce',
url = '/path/to/php_scripts/placeOrder.php';
// This is where you would submit payload.nonce to your server
// alert('Submit your cc nonce to your server here!');
});
//form.submit();
}
});
});
....more code below....
</script>
Any suggestions would be greatly appreciated.
Answering my own question:
CLIENT_AUTHORIZATION = jQuery.parseJSON(jQuery.ajax({
url: "/path/to/php_scripts/TokenScript.php",
dataType: "json",
async: false
}).responseText);
braintree.client.create({
authorization: CLIENT_AUTHORIZATION.token
}, function (clientErr, clientInstance) {
if (clientErr) {
console.error(clientErr);
return;
} code continues.....
The CLIENT_AUTHORIZATION.token is whatever the token was named on the client authorization script.
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());
}
}
}
});
});
}
how to run some code when user click on the notification? if user click push notification i want understand coming from push notification.
How can i do?
Thanks
-Gcm Module-
//my gcm module
var gcm = require("nl.vanvianen.android.gcm");
/* If the app is started or resumed act on pending data saved when the notification was received */
var lastData = gcm.getLastData();
if (lastData) {
Ti.API.info("Last notification received " + JSON.stringify(lastData));
gcm.clearLastData();
}
gcm.registerPush({
senderId : 'xxxxxxxx',
notificationSettings : {
sound : 'mysound.mp3',
smallIcon : 'notification_icon.png',
largeIcon : 'appicon.png',
vibrate : true
},
//Push registration success
success : function(event) {
Ti.API.info("Push registration success: " + JSON.stringify(event));
},
//Push registration error
error : function(event) {
Ti.API.info("Push registration error = " + JSON.stringify(event));
alert(event.error);
},
//i want this function Coming from push
data : function(event) {
// console.log(" ******* Coming from push : " + JSON.stringify(event));
},
//my callback funtion call device token
callback : function(event) {
Ti.API.info("Push callback = " + JSON.stringify(event));
var dialog = Ti.UI.createAlertDialog({
title : 'Push received',
message : JSON.stringify(event.data)
// buttonNames: ['View'],
// cancel: 1
});
dialog.addEventListener("click", function(event) {
dialog.hide();
if (event.index == 0) {
/* Do stuff to view the notification */
}
});
dialog.show();
},
});
Titanium.UI.setBackgroundColor('#000');
var win = Ti.UI.createWindow({
backgroundColor : '#ccc',
title : 'Android Cloud Push Notification'
});
var CloudPush = require('ti.cloudpush');
CloudPush.debug = true;
CloudPush.enabled = true;
CloudPush.showTrayNotification = true;
CloudPush.showTrayNotificationsWhenFocused = true;
CloudPush.focusAppOnPush = false;
var deviceToken;
var Cloud = require('ti.cloud');
Cloud.debug = true;
var submit = Ti.UI.createButton({
title : 'Register For Push Notification',
color : '#000',
height : 53,
width : 200,
top : 100,
});
win.add(submit);
submit.addEventListener('click', function(e) {
CloudPush.retrieveDeviceToken({
success : function deviceTokenSuccess(e) {
alert('Device Token: ' + e.deviceToken);
deviceToken = e.deviceToken;
loginDefault();
},
error : function deviceTokenError(e) {
alert('Failed to register for push! ' + e.error);
}
});
});
function loginDefault(e) {
// At first you need to create an user from the application dashboard
// Then login that email and password
Cloud.Users.login({
login : '.....',
password : '....'
}, function(e) {
if (e.success) {
alert("login success");
defaultSubscribe();
} else {
alert('Error: ' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
function defaultSubscribe() {
Cloud.PushNotifications.subscribe({
channel : 'alert',
device_token : deviceToken,
type : 'android'
}, function(e) {
if (e.success) {
alert('Subscribed for Push Notification!');
} else {
alert('Error:' + ((e.error && e.message) || JSON.stringify(e)));
}
});
}
CloudPush.addEventListener('callback', function(evt) {
//alert(evt);
//alert(evt.payload);
});
CloudPush.addEventListener('trayClickLaunchedApp', function(evt) {
Ti.API.info('Tray Click Launched App (app was not running)');
//alert('Tray Click Launched App (app was not running');
});
CloudPush.addEventListener('trayClickFocusedApp', function(evt) {
Ti.API.info('Tray Click Focused App (app was already running)');
//alert('Tray Click Focused App (app was already running)');
});
win.open();