How to get facebook post by a user using graph api? - facebook

I have tried following code to get posts from a user using my app. But, I am getting error occurred in second case while trying to post to user's wall and in retrieving posts, i have only data and pagination.
FB.api('/platform/posts', { limit: 3 }, function(response) {
console.log('Good to see you, ' + response.length);
for (var i=0, l=response.length; i<l; i++) {
var post = response[i];
console.log('Good to see you, ' + post);
/*if (post.message) {
alert('Message: ' + post.message);
} else if (post.attachment && post.attachment.name) {
alert('Attachment: ' + post.attachment.name);
}*/
}
});
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
what's going wrong?
In the second block, alert, "Error occurred" is being displayed. And in the first block, following error occurred:
__d("sdk.ErrorHandling", ["sdk.feature","ManagedError","sdk.Runtime","sdk.Scribe","UserAgent","wrapFunction"],function(a,b,c,d,e,f){var g=b('sdk.feature'),h=b('ManagedError'),i=b('sdk.Runtime'),j=b('sdk.Scribe'),k=b('UserAgent'),l=b('wrapFunction'),m=g('error_handling',false),n='';function o(u){var v=u._originalError;delete u._originalError;j.log('jssdk_error',{appId:i.getClientID(),error:u.name||u.message,extra:u});throw v;}function p(u){var v={line:u.lineNumber||u.line,message:u.message,name:u.name,script:u.fileName||u.sourceURL||u.script,stack:u.stackTrace||u.stack};v._originalError=u;if(k.chrome()&&/([\w:\.\/]+\.js):(\d+)/.test(u.stack)){v.script=RegExp.$1;v.line=parseInt(RegExp.$2,10);}for(var w in v)(v[w]==null&&delete v[w]);return v;}function q(u,v){return function(){if(!m)return u.apply(this,arguments);try{n=v;return u.apply(this,arguments);}catch(w){if(w instanceof h)throw w;var x=p(w);x.entry=v;var y=ES5(Array.prototype.slice.call(arguments),'map',true,function(z){var aa=Object.prototype.toString.call(z);return (/^\[object (String|Number|Boolean|Object|Date)\]$/).test(aa)?z:z.toString();});x.args=ES5('JSON','stringify',false,y).substring(0,200);o(x);}finally{n='';}};}function r(u){if(!u.__wrapper)u.__wrapper=function(){try{return u.apply(this,arguments);}catch(v){window.setTimeout(function(){throw v;},0);return false;}};return u.__wrapper;}function s(u,v){return function(w,x){var y=v+':'+(n||'[global]')+':'+(w.name||'[anonymous]'+(arguments.callee.caller.name?'('+arguments.callee.caller.name+')':''));return u(l(w,'entry',y),x);};}if(m){setTimeout=s(setTimeout,'setTimeout');setInterval=s(setInterval,'setInterval');l.setWrapper(q,'entry');}var t={guard:q,unguard:r};e.exports=t;});
Thanks

Related

Facebook Open Graph: How to Post User Message with Custom Action

The Facebook tutorials suggest that you can add a user comment to a custom action in a Facebook App. The example javascript function for posting is:
<script type="text/javascript">
function postCook()
{
FB.api(
'/me/[YOUR_APP_NAMESPACE]:cook',
'post',
{ recipe: 'http://fbwerks.com:8000/zhen/cookie.html' },
function(response) {
if (!response || response.error) {
alert('Error occurred');
} else {
alert('Cook was successful! Action ID: ' + response.id);
}
});
}
</script>
I have an "Endorse" action defined with the object "Local Business". Everything is working. Now I want to give the user the option to add a user message to their endorsement but I can not find any help in Facebook docs on how to implement this in the api (the above code). Any help?
You need to specify the 'message' parameter when publishing the action. For example,
<script type="text/javascript">
function postCook(userMessage)
{
FB.api(
'/me/[YOUR_APP_NAMESPACE]:cook',
'post',
{ recipe: 'http://fbwerks.com:8000/zhen/cookie.html',
message: userMessage },
function(response) {
if (!response || response.error) {
alert('Error occurred');
} else {
alert('Cook was successful! Action ID: ' + response.id);
}
});
}
</script>
will submit userMessage as a user provided message on the action.
The full list of supported parameters for the OpenGraph publishing API is available here: https://developers.facebook.com/docs/technical-guides/opengraph/publish-action/#create

Publishing to the Facebook Graph API returns a strange response object

I'm using the Facebook JS SDK to publish to the GRAPH API, and while my post publishes successfully, it returns a strange response object that gets caught by the jQuery .error chain. Here's my code:
var jqxhr = $.post("https://graph.facebook.com/"+sbFacebook.authentication.userID+"/feed",
{
'message' : $("#question-text").val(),
'access_token' : sbFacebook.authentication.accessToken
}).success(
function(response) {
console.log(response);
})
.error(function(response) {
alert(response);
})
The response object looks like this:
http://img689.imageshack.us/img689/964/screenshotfrom201302222.png
Anyone have any idea what's going on and why it's getting caught by the error() function?
Thanks.
This is not how you should use Facebook JS SDK.
var body = 'Reading JS SDK documentation';
FB.api('/me/feed', 'post', { message: body }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
Don't forget to initialize the JS SDK:

Facebook Graph API - Error on success?

I am using the Facebook Javascript SDK to upload a photo to the user's timeline. This is my call:
function post_photo_to_facebook() {
var file_name = 'https://my-image.url.com/image.jpg';
var access_token = FB.getAuthResponse()['accessToken'];
$.ajax({
type: "POST",
url: "https://graph.facebook.com/me/photos",
data: {
message: "Here is my message",
url: file_name,
access_token: access_token,
format: "json"
},
success: function(data){
alert("POST SUCCESSFUL");
},
error: function(data){
alert('Error');
console.log(data);
}
});
}
When in Chrome, I am receiving an Error back from this AJAX call, yet the statusText is "OK", and the image is being successfully uploaded to my timeline. I am just wondering what I am missing here - why is the error being called?
You should be using FB.api to upload images, rather than ajax POST due to CORS reasons.
So your code above would look like this:
var file_name = 'https://my-image.url.com/image.jpg';
FB.api('/me/photos', 'post', {
message:'Here is my message',
url:file_name
}, function(response){
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
and you use FB.init to set up your tokens etc.

How to find out who has published a post using my OG action

Hoping someone can point me in the right direction.
I have an open graph action that has finally been approved and is active on my app now. Is there any way to track who publishes a post using my OG action from within my app?
Here is the code I'm using for my action:
<script type="text/javascript">
function postEndorse()
{
FB.api(
'/me/namespace:endorse',
'post',
{ photo: '<?php the_permalink(); ?>' },
function(response) {
if (!response || response.error) {
alert('Error Occurred' + response + " " + response.error);
} else {
alert('Thank you!');
}
});
}
</script>
I am requesting the publish_actions permissions when people log in.
Thanks
The response in your JavaScript code above has the id of the action.
{
id: “{action-instance-id}”
}
You need to store your actions via database or otherwise. Once you have that you can make a call against it
/action-instance-id?fields=from.fields(id)
Which will give a response such as
{
"from": {
"id": "{user-id}"
},
"id": "{action-instance-id}"
}
There are many ways to store this data, one way would be AJAX to PHP/MySQL.
I suggest reading up on it. The following hasn't been tested, just gives an idea of how to send the data across. Think of it as pseudocode
Add jQuery to the <head>
<script src="jquery.js"></script>
Send the id of the user, like
<script type="text/javascript">
function postEndorse()
{
FB.api(
'/me/namespace:endorse',
'post',
{ photo: '<?php the_permalink(); ?>' },
function(response) {
if (!response || response.error) {
alert('Error Occurred' + response + " " + response.error);
} else {
FB.api(
response.id + "?fields=from.fields(id)",
function(resp) {
if (!resp || resp.error) {
alert('Error Occurred' + resp + " " + resp.error);
} else {
$.ajax({
type: "POST",
url: "fbdata.php",
data: { id: resp.from.id, actionid: resp.id }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
}
});
}
</script>
Then in fbdata.php something like
<?php
include("database.inc.php");
mysql_connect($server,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$id = mysql_real_escape_string($_POST['id']);
$actionid = mysql_real_escape_string($_POST['actionid']);
$database_entry = "INSERT INTO Actions (Id, Action) VALUES ('$id', '$actionid') ;
mysql_query($database_ntry) or die(mysql_error());
mysql_close();
?>
References that you should read
http://api.jquery.com/jQuery.ajax/
http://www.php.net/manual/en/mysql.examples-basic.php
What about if you change
/me/namespace:endorse to /users facebook id/namespace:endorse Then you can store the facebook id of the person and then track them back using that.

Check if Facebook JS-API app already has been given permission

I have a small script that unlocks some content on a page when a user logs in via Facebook and posts some information on their wall.
I want to avoid any duplicate posts (spam) in the event the user visits the page a second time and repeats the process.
Is there a way of (when asking for the permissions) to tell if they have already been given and therefore skip the sharing part of the script?
Here's my code:
$('.preview a').click(function(e) {
e.preventDefault();
FB.login(function(response) {
if (response.session) {
FB.api('/me/feed', 'post', {
message: 'Just unlocked the exclusive preview of...',
picture: 'http://website.com/share.png',
link: 'http://www.website.com',
name: 'Name goes here',
description: 'Description here'
},
function(response) {
if (!response || response.error) {
alert(response.error);
} else {
$('.preview').hide();
$('.clip').show();
}
});
}
},
{perms:'read_stream,publish_stream'});
});
From 2011 to 2014 a lot of things change..
I made this solution to check for "user_friends" and "publish_actions" permissions, if not allowed the both, force the user to "re-autenticate". The callback method will only be called when all permissions are given.
function login(cb,forceAuth) {
FB.getLoginStatus(function (response) {
if (response.status !== 'connected' || forceAuth==true){
FB.login(function (response) {
checkPermissions(cb,false);
}, {scope: 'publish_actions,user_friends'});
} else {
checkPermissions(cb);
}
});
}
function checkPermissions(cb,forceAuth){
FB.api(
"/me/permissions",
function (response) {
if (response.data[0]['publish_actions']==undefined || response.data[0]['publish_actions']==0 ||
response.data[0]['user_friends']==undefined || response.data[0]['user_friends']==0) {
if (forceAuth!=false)
login(cb,true);
} else {
cb();
}
}
);
}
How to use:
login(function () {
myLogedAndAllowedFunction();
});
I've written a tutorial about this here, and here's an example:
FB.api({ method: 'fql.query', query: 'SELECT read_stream,offline_access,publish_stream FROM permissions WHERE uid=me()' }, function(resp) {
for(var key in resp[0]) {
if(resp[0][key] === "1")
console.log(key+' is granted')
else
console.log(key+' is not granted')
}
});
There's also a JS REST example there in the article just for reference.