Javascript - how to wait for facebook - javascript

My app does the following:
1. Asks for the friends_online_presence permission.
2. If the user gave the permission (i.e the callback indicated success) I immidiately test for the permissions(*) and depending on the result pull the users' details (a call to getOnlineFriends).
The problem is that it takes a couple of miliseconds for facebook to update the permissions on their servers. So when I immidiately query for the permissions I just asked for facebook always says that I don't have the permission.
Using setTimout "solves" the problem.
How can this be solved deteministically?
I've tried some primitive form of polling but it got the browser stuck (and it also seems like a crooked solution).
(*) 'SELECT friends_online_presence FROM permissions WHERE uid=me()'
The code:
c2p.facebook = {
requestViewOnlineFriendsPerms: function (callback) {
myStuff.requestPermission('friends_online_presence', callback);
},
requestPermission: function (perms, callback) {
FB.ui({
method: 'permissions.request',
perms: perms,
display: 'popup'
}, function (response) {
if (response && response.perms) {
if (callback) {
callback(true);
}
} else if (!response.perms) {
if (callback) {
callback(false);
}
}
});
fql: function (q, callback) {
FB.api({ "method": "fql.query", "query": q }, callback);
},
getOnlineFriends: function (callback) {
var q = 'SELECT friends_online_presence FROM permissions WHERE uid=me()';
c2p.facebook.fql(q, function (rows) {
var isPermissionGranted = true;
var q2 = "SELECT uid, name, pic_square, online_presence FROM user WHERE online_presence IN ('active', 'idle') AND uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) ORDER BY name";
if (rows[0].friends_online_presence == 0) {
isPermissionGranted = false;
q2 = "SELECT uid, name, pic_square FROM user WHERE uid IN(SELECT uid2 FROM friend WHERE uid1=me()) ORDER BY name";
}
c2p.facebook.fql(q2, function (arr) {
callback(arr, isPermissionGranted);
});
});
}
}
// The way I call this code is:
c2p.facebook.getOnlineFriends(function (arr, isPermissionGranted) {
$("#tmplFriends").tmpl(arr, { getIndex: function () { return $.inArray(this.data, arr); } }).appendTo("#friendsDiv");
if (!isPermissionGranted) {
$('.c2p_hidden').show();
}
});

How c2p.facebook.fql(q2, function (arr) {...} could see the callback variable? it's crazy.
The callback is a local variable of the getOnlineFriends function.

Tom just place your FQL query inside the
if (response && response.perms) {
}
for example suppose I want to fetch user details thru fql what I do is:
function onloginCall(){
FB.login(handleSessionResponse,{perms:'email,read_stream,publish_stream,offline_access'});
}
function handleSessionResponse(response){
// if we dont have a session, just hide the user info
if (!response.session) {
return;
}
else{
FB.api({
method: 'fql.query',
query: 'SELECT name, pic_square , email FROM user WHERE uid=' + FB.getSession().uid
},
function(response) {
var user = response[0];
store_fbuser_data(FB.getSession().uid,user.name,user.pic_square,user.email) ;
}
);
}
}
I guess this will solve your problem of delay. As this query will only execute when you have sufficient permissions.

Related

how to do nativescript paytm integration

i have checked the native-script-paytm integration plugin. but both git-hub repository are not running instead it gives stack exception. so i created my own project and some how its doing something. but here i have lot of questions on how to get 'mid', 'order id' etc.
can anyone give step by step details for this.
const createViewModel = require("./main-view-model").createViewModel;
const Paytm = require("#nstudio/nativescript-paytm").Paytm;
const paytm = new Paytm();
exports.pageLoaded = function (args) {
const page = args.object;
page.bindingContext = createViewModel();
}
exports.onPayWithPaytm = function (args) {
console.log("Paying");
paytm.setIOSCallbacks({
didFinishedResponse: function (response) {
console.log("got response");
console.log(response);
},
didCancelTransaction: function () {
console.log("User cancelled transaction");
},
errorMissingParameterError: function (error) {
console.log(error);
}
});
const order = {
// This will fail saying duplicate order id
// generate your own order to test this.
MID: "Tomcas09769922377481",
ORDER_ID: "ORDER8874",
CUST_ID: "CUST6483",
INDUSTRY_TYPE_ID: "Retail",
CHANNEL_ID: "WAP",
TXN_AMOUNT: "10.00",
WEBSITE: "APP_STAGING",
CALLBACK_URL: "https://pguat.paytm.com/paytmchecksum/paytmCallback.jsp",
CHECKSUMHASH:
"NDspZhvSHbq44K3A9Y4daf9En3l2Ndu9fmOdLG+bIwugQ6682Q3JiNprqmhiWAgGUnNcxta3LT2Vtk3EPwDww8o87A8tyn7/jAS2UAS9m+c="
};
paytm.createOrder(order);
paytm.initialize("STAGING");
paytm.startPaymentTransaction({
someUIErrorOccurred: function (inErrorMessage) {
console.log(inErrorMessage);
},
onTransactionResponse: function (inResponse) {
console.log(inResponse);
},
networkNotAvailable: function () {
console.log("Network not available");
},
clientAuthenticationFailed: function (inErrorMessage) {
console.log(inErrorMessage);
},
onErrorLoadingWebPage: function (
iniErrorCode,
inErrorMessage,
inFailingUrl
) {
console.log(iniErrorCode, inErrorMessage, inFailingUrl);
},
onBackPressedCancelTransaction: function () {
console.log("User cancelled transaction by pressing back button");
},
onTransactionCancel: function (inErrorMessage, inResponse) {
console.log(inErrorMessage, inResponse);
}
});
}
For reference
As mentioned in the plugin's ReadMe file,
You will need a working backend server to generate paytm orders. Do not generate the order or checksum in the app.

Get parameters and store and use them on variables to use on my method

I want to get some parameters and use them to reset password function from firebase.
This is how my link looks like:
http://localhost:8080/passwordreset?mode=resetPassword&oobCode=y6FIOAtRUKYf88Rt5OlEwxUuTyEmb3M4gquZSIseX2UAAAFevpj-gw&apiKey=AIzaSyBaCCvq-ZEfQmdrL7fmElXDjZF_J-tku2I
I want to get mode, oobCode and apiKey.
Here is what I have for now:
export default {
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode:'',
actionCode: '',
continueUrl: '',
}
},
methods: {
handleResetPassword: function() {
var accountEmail;
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
var accountEmail = email;
firebase.auth().confirmPasswordReset(this.actionCode, this.passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
// Error occurred during confirmation. The code might have expired or the
// password is too weak.
console.log("error 1")
});
}).catch(function(error) {
// Invalid or expired action code. Ask user to try to reset the password
// again.
console.log("error 2")
});
},
}
}
From Firebase documentation:
Some user management actions, such as updating a user's email address
and resetting a user's password, result in emails being sent to the
user. These emails contain links that recipients can open to complete
or cancel the user management action. By default, user management
emails link to the default action handler, which is a web page hosted
at a URL in your project's Firebase Hosting domain.
link: https://firebase.google.com/docs/auth/custom-email-handler
You need to get those parameters and store them on variables, from firebase documentation i got those snippets and just wrote the getParameterByName function:
function getParameterByName( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Get the action to complete.
var mode = getParameterByName('mode');
// Get the one-time code from the query parameter.
var actionCode = getParameterByName('oobCode');
// (Optional) Get the continue URL from the query parameter if available.
var continueUrl = getParameterByName('continueUrl');
You need to get those parameters first and verify the actioncode on the verifyPasswordResetCode method, then you can change the password and store it along with the action code to the method.
In your export default :
data: function() {
return {
passwordNew: '',
passwordConfirm: '',
mode: mode,
actionCode: actionCode,
continueUrl: continueUrl,
}
},
methods: {
handleResetPassword: function() {
var passwordNew = this.passwordNew
var actionCode = this.actionCode
firebase.auth().verifyPasswordResetCode(actionCode).then(function(email) {
console.log("ActionCode: "+ actionCode);
firebase.auth().confirmPasswordReset(actionCode, passwordNew).then(function(resp) {
alert("Password reset success");
this.$router.push('hello')
}).catch(function(error) {
console.log("error 1"+ error)
});
}).catch(function(error) {
console.log("Action code is invalid"+ error)
});
},
}

Parse CC - success callback not firing

I've created a Cloud Code function for creating a new Stripe customer, which works okay. What I can't figure out is the returning of the customer ID to the calling code;
Calling Code
Parse.Cloud.run(
'createCustomer',
{
email: user.get('email'),
username: user.get('username')
},
{
success: function(customerId) {
// never called
console.log('Customer created: ' + customerId);
},
error: function() {
console.log('Error function');
}
}
);
Function
Parse.Cloud.define(
'createCustomer',
function(request, response) {
var email = request.params.email,
description = 'Username: ' + request.params.username;
Parse.Config.get().then(function(config) {
var Stripe = require('stripe');
Stripe.initialize(config.get('stripe_secret_test'));
Stripe.Customers.create({
description: description,
email: email
})
.then(function(customer) {
console.log(customer.id); // Logs out fine
response.success(customer.id);
});
});
}
);
Basically, the success callback in the calling code is never fired, so I can't access the customer ID I want to return. What am I missing? Thanks!
Turns out Cloud functions don't seem to play well if called from within Cloud Code, they run but I couldn't find a way to return a value.
Instead I used a Cloud Code Module, since this function only ever needed to be called from within Cloud Code. Final code is below;
Calling Code (User beforeSave)
var createCustomerModule = require('cloud/stripe/CreateCustomer.js');
createCustomerModule.createCustomer(
user.get('email'),
user.get('username'),
{
success: function(customer) {
request.object.set('stripeCustomerId', customer.id);
response.success();
},
error: function() {
response.error('Failed to create a new Stripe customer');
}
}
);
Function (cloud/stripe/CreateCustomer.js)
exports.createCustomer = function(email, username, callbacks) {
var description = 'Username: ' + username;
Parse.Config.get().then(function(config) {
var Stripe = require('stripe');
Stripe.initialize(config.get('stripe_secret_test'));
// Attempt to create the customer
Stripe.Customers.create({
description: description,
email: email
})
.then(callbacks.success, callbacks.error);
});
};

How to get any user details from facebook api

How to find user details by using his/her email ID or mobile number from Facebook? I want to get user details on my website using my app id access.
Please help me out this.
Try this. You need his facebook ID or his facebook name.
var fields = [
'id',
'name',
'first_name',
'middle_name',
'last_name',
'gender']
FB.api('/{insertIDhere}', {fields: fields}, function(details) {
// output the response
});
Or take this code from the FB Api Documentation
FB.api(
"/{user-id}",
function (response) {
if (response && !response.error) {
/* handle the result */
}
}
);
to login you need something like this :
FB.login(function(response) {
if (response.authResponse) {
//login successfull
} else {
//anything else
}
}, {scope: 'public_profile,email,user_friends'});
If you are logged in you could use something like this:
FB.api(
"/me?fields=id,name,picture.redirect(false).type(large)",
function (response) {
if (response && !response.error) {
facebookId = response.id;
facebookName = response.name;
facebookProfilePicture = response.picture.data.url;
callback(facebookUser);
}else{
}
}
);
You can't. Searching by email or phone is not possible.
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#search

(#210) User not visible

I'm writing a facebook app in which the logged in user (a) chooses a friends from their friends list (b) and then the app posts on their friends wall (a posts to b).
I ask from the user the publish_stream permissions.
This is the code for showing the friends selector popup:
function selectFriends() {
FB.ui({
method: 'apprequests',
message: 'You should learn more about this awesome game.', data: 'tracking information for the user'
},function(response) {
if (response && response.request_ids) {
//alert(typeof(response.request_ids));
//alert(response.request_ids);
alert (response.request_ids);
len=response.request_ids.length;
alert(len);
if (len>2) {
alert("Select no more than one friend");
}
else {
user_req_id = response.request_ids[0];
postOnFirendsWall(user_req_id);
}
}
else {
alert('Post was not published.');
}
});
}
This is the postOnFirendsWall(user_req_id) method:
function postOnFirendsWall(friend_id)
{
/** Auto Publish **/
var params = {};
params['message'] = 'message';
params['name'] = 'name';
params['description'] = '';
params['link'] = 'https://www.link.com/';
params['picture'] = 'http://profile.ak.fbcdn.net/hprofile-ak-snc4/203550_189420071078986_7788205_q.jpg';
params['caption'] = 'caption';
var stam = '/'+friend_id+'/feed';
FB.api('/'+friend_id+'/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
alert(response.error);
} else {
alert('Published to stream - you might want to delete it now!');
}
});
return false;
}
But I keep getting the following error: (#210) User not visible.
Can you see why?
Have you verified that user A has permission to write on the wall of user B? If not, this will never work.
Also, why are you using an apprequests dialog if you want to post on a friend's wall?

Categories

Resources