Facebook share javascript SDK v3.x using Iframe - javascript

Facebook sharing using feed or share has a success call back and can tell if user shared or not, but when using iframe it allways says that the user canceled the dialog {error_code: 4201, error_message: "User+canceled+the+Dialog+flow"}and cant tell if the user shared or not, but same function without the use of iframe is working properly
function sharfeToFacebook() {
var deferred = $q.defer();
var options = {
method: 'share',
mobile_iframe: true,
href: photoUrl,
};
FB.ui(options, function(response) {
console.log('FB share dialog started with response: ', response);
if (response && !response.error_code) {
// fb does returns an emtpy object on success, undefined when fail or canceled
deferred.resolve(response);
} else {
deferred.reject(response);
}
});
}
return deferred.promise;

Related

Facebook Delete Comment API problems (#200) App does not have sufficient permission for this action for remove comments

I Logged-in with user that I am facebook pages administrator. I write api to delete spam comments in posts by use this method.
$scope.deleteComments = function (commentID) {
if (confirm("Confirm Delete Comments")) {
FB.api(
"/" + commentID,
"DELETE",
function (response) {
console.log(response, commentID);
if (response && !response.error) {
/* handle the result */
}
}
);
}
};
I followed instructions from "https://developers.facebook.com/docs/graph-api/reference/v2.5/comment". Before I use Facebook API I given and Permission with this code.
$scope.triggerLogin = function () {
FB.login(function () {
$scope.checkLoginState();
}, {
scope: "public_profile, publish_pages, manage_pages"
});
};
so that while I use deleteComments() function I get error object from facebook like this
error: Object
code: 200
message: "(#200) App does not have sufficient permission for this action"
type: "OAuthException"
Does anyone know how to fixed this problems, Thank you.
You are most likely not using a Page Token, right now it looks like you are using a User Token. You MUST use a Page Token to delete comments. Generate a Page token by using the /me/accounts endpoint (or /page-id?fields=access_token for a specific Page) and use it in the API call:
FB.api(
'/' + commentID,
'DELETE',
{access_token: 'your-page-token'},
function (response) {
console.log(response, commentID);
if (response && !response.error) {
/* handle the result */
}
}
);
More information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/

How do you deal with asynchronous return from $http.post in angularJS?

Stuck with a simple basic login problem here. My AuthService factory has following code inside of it (2 relevant functions and a local variable):
var username = '';
function login(uname, upwd, utype) {
// create a new instance of deferred
var deferred = $q.defer();
$http({
method: 'POST',
url: '/root',
headers: {
'Content-Type': 'application/json'
},
data: {
username: uname,
password: upwd,
type: utype
}
}).success(function(data, status, headers, config) {
if (status === 200) {
user = true;
username = data.username;
usertype = data.usertype;
deferred.resolve();
} else {
user = false;
deferred.reject();
}
})
.error(function(data, status, headers, config) {
user = false;
deferred.reject();
});
// return promise object
return deferred.promise;
}
function getusername() {
return username;
}
My controller looks like this:
angular.module('smApp').controller('rootloginController', ['$scope', '$location', 'notificationFactory', 'AuthService',
function($scope, $location, notificationFactory, AuthService) {
$scope.submit = function() {
AuthService.login($scope.rEmail, $scope.rootPassword, 'root')
if (AuthService.isLoggedIn()) {
$location.url('/dashboard');
notificationFactory.success('Logged in as ' + rootEmail);
} else {
//ngNotifier.notifyError($scope.rEmail);
notificationFactory.error('Invalid username & password combination');
}
};
};
}]);
I am calling my getusername() in the if statementright after login() and since login has $http post it's asynchronous and I think im hitting a wall here.
So my main problem here is the first click always gives me error message and the second clicks logs me in. I am assuming this has to do with the promise not being fulfilled right away and taking some time to execute. I was wondering if there was anyway around this? I really dont have any other code to execute beside wait since this is a login page and using a timeout doesnt seem like the proper way to do it.
In this case you need to use the Promise API. Calls to the server made via the $http service return a promise, which allow binding of .success and .error methods.
The .then method may be used as a shorthand for both .success and .error. It accepts two functions that it executes in success and error scenarios respectively. Returning a promise in those functions allows chaining calls to the server.
In most cases, this should suffice:
// In service
login: function () {
return $http.post('your:url').then( // `then` here is optional, but possible
function () {}, // update service values without having to involve the controller (and/or transform the response object)
function () {} // throw error log mesages
)
}
// In controller
$scope.submit = function () {
AuthService.login().then(
function () {
// success logic: redirect, assign scope variables, etc
},
function () {
// error logic: allow retry
}
);
}
You have to call AuthService.isLoggedIn() after the login request has been completed. For this, first return the promise of the deferred object you created.
function login(uname, upwd, utype) {
// create a new instance of deferred
var deferred = $q.defer();
$http({
method: 'POST',
...
return deferred.promise;
}
Now, you can wait for the request to complete.
AuthService.login($scope.rEmail, $scope.rootPassword, 'root').finally(function() {
if (AuthService.isLoggedIn()) {
$location.url('/dashboard');
notificationFactory.success('Logged in as ' + rootEmail);
} else {
//ngNotifier.notifyError($scope.rEmail);
notificationFactory.error('Invalid username & password combination');
}
});

Need to check if user selected only me to share [facebook api]

I am trying to figure out how can I get to know if a user shares a link to his feed selecting only me as an option. I want to know this because if the user shares my link to himself then the promotion of my website won't be possible.
<div id="fb-share">Share</div>
<div class="social-share-wrap"></div>
jQuery('#fb-share').on('click', function() {
checkLoginState();
});
function statusChangeCallback(response) {
console.log(response);
if (response.status === 'connected') {
shareUrl();
} else if (response.status === 'not_authorized') {
checkLoginState();
} else {
checkLoginState();
}
};
function checkLoginState() {
FB.login(function (response) {
console.log(response);
statusChangeCallback(response);
}, {scope: 'email'});
};
function shareUrl() {
FB.ui({
method: 'feed',
link: 'http://www.example.com',
}, function(response) {
if (response && response.post_id) {
FB.api('/me', function (response) {
jQuery.post('test.php',{name: response.name, email: response.email}).done(function(data) {
jQuery('.social-share-wrap').html(data);
jQuery.fancybox({
href: '#social-share',
centerOnScroll: true,
hideOnOverlayClick: false
});
return false;
});
});
} else {
console.log('cancelled by user');
}
});
};
In the above code what I'm doing is when a user clicks the share div the user gets the login popup and then the user gets the permission popup and then the share iframe appears now if the user shares successfully his info is posted to test.php and if the user cancels it gets logged in console. I did not find anything in the api where I can get to know if user selects custom and sets it to only me.
You can´t check the permission setting, it´s completely up to the user and there is no way to detect which one he selected. After all, you are not allowed to incentivize sharing according to the platform policy, so it´s not really relevant to know.

How to detect user cancelled share when using fb.ui

I'm using the documentation provided over here with the following code. The share dialog comes up correctly. The problem is that I'm not able to differentiate between "Cancel" and "Post" actions that the user takes on the dialog. I'd imagine this would be a part of the response.
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/',
}, function(response){
if (response && !response.error_code) {
console.log(response);
} else {
alert('Error while posting.');
}
});
edit: output from the console isn't doesn't provide any way of knowing
Cancel - Object {e2e: "{"submit_0":1401181811121}"}
Post - Object {e2e: "{"submit_0":1401181815112}"}
I tested this, and apparently there's some info in the response object you could use to determine if the dialog was cancelled.
Code
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Output upon cancellation:
{error_code: 4201, error_message: "User+canceled+the+Dialog+flow", e2e: "{"submit_0":1401188820613}"}
So, I guess you could check for cancellaction like this:
FB.ui({
method: 'share',
href: 'https://developers.facebook.com/docs/'
}, function(response){
if (response && !response.error_code) {
console.log("OK: "+JSON.stringify(response));
} else if (response && response.error_code === 4201) { //Cancelled
console.log("User cancelled: "+decodeURIComponent(response.error_message));
} else {
console.log("Not OK: "+JSON.stringify(response));
}
});
Unfortunately, FB.Events.subscribe() doesn't offer an Event for the Cancallation of this dialog: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/v2.0
This is intentionally so as to dissuade developers from using posting as a gating mechanism. It should be up to the person to choose whether to post or not, it should not be a requirement of the app.
Use "feed" method instead of "share" so that it doesn't require app permission to get the response.
FB.ui({
method: 'feed',
caption: 'My Caption',
link: 'http://www.google.com/'
}, function(response) {
if (response && response.post_id) {
alert('Thank you for sharing!');
} else {
alert('You have cancelled the share.');
}
});
I also have a problem with the response function, I'm currently coding and trying to use fb.UI
return FB.ui({
method: 'share',
href: this.shareUrl,
hashtag: "myHashTag",
quote: "myQuote"
}, function(res) {
console.log("res = ", res);
console.log("res? = ", res != null);
return App.vent.trigger("FBShareView:cancelled");
});
I'm finding that on a successful share, res is an empty array and res != null is true
I'm finding that for the cancel scenario, res is undefined.
I expected to see res as an object with an error_message as described here: https://developers.facebook.com/docs/sharing/reference/share-dialog
Could you tell me what may be going wrong please?

Fb.api post to user wall only on login

I would like to use fb.api to post on logged user, but just once. If I put this
var params = {};
params['message'] = 'gegeegeggegall! Check out www.facebook.com/trashcandyrock for more info.';
params['name'] = 'gegeggeeg - gegegege';
params['description'] = 'Check out Tegegegeg! Win merch by playing and reccomending to your friends.';
params['link'] = 'http://www.bblblba.com';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Tgegegegeeg';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Published to stream - you might want to delete it now!');
}
});
It posts to users wall everytime he refreshes the site?
What to do?
What is triggering the FB.api call? If it's just code within a tag then it's going to run as soon as the browser gets to that point.
You could possibly store some sort of cookie value or something after the FB.api call then check it on page load, but that seems like more work than is probably needed.
Do you want him to post it only once, ever?
If so, you're going to need to create a "state". In order to do this, you could do it client sided (with cookies), or server sided (with a database).
Create a boolean variable named "posted", and store it in a cookie or in a database (since you're using javascript, it's probably easier to use a cookie).
var posted=getCookie("posted");
if(!posted)
{
//call the FB.api();
setCookie("posted", true, duration);
}
Definition of setCookie and getCookie: http://www.w3schools.com/JS/js_cookies.asp
You could run a FQL query and check to see if the message has already been posted by querying the stream table with your app id. Something like:
<!DOCTYPE html>
<html>
<body>
<div id="fb-root"></div>
Post To Wall
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({ appId : '**yourAppID**', status : true, cookie : true, xfbml : true });
function postToWall() {
FB.login(function(response) {
if (response.session) {
FB.api(
{
method: 'fql.query',
query: 'SELECT post_id, message from stream where app_id = **yourAppID** and source_id = me()'
},
function(response) {
if(response.length == 0){
FB.ui(
{
method: 'feed',
name: 'Facebook Dialogs',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
caption: 'Reference Documentation',
description: 'Dialogs provide a simple, consistent interface for applications to interface with users.',
message: 'Facebook Dialogs are easy!'
},
function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
}
else {
alert('User already posted this message');
}
}
);
}
} , {perms:''});
}
</script>
</body>
</html>

Categories

Resources