I'm stuck with sharing and commenting Facebook posts from my website.
Look.
In Twitter we can reply a tweet simply by a link
https://twitter.com/intent/tweet?in_reply_to=35782000644194304
or
we can retweet the tweet by this link
https://twitter.com/intent/retweet?tweet_id=35782000644194304
it's so easy, after clicking you redirecting to twitter where you can do this, and i like it.
With facebook posts it is not so easy.
I have Facebook posts (copies of posts, i parsed them before and saved to my DB, ID of that posts I saved too) at my website and I'd like to share/comment/like this posts. Maybe Facebook have the links like twitter, or some another way to do it, I don't know, but i spend all day to find solution and I failed.
Maybe it is possible to create links like this:
http://facebook.com/ID_OF_THAT_FB_POST/share
or
http://facebook.com/ID_OF_THAT_FB_POST/comment
and.. after clicking the link, it redirects to facebook page, where you can share this post or comment?
Well let me see if I understand, If you want to SHARE/COMMENT/LIKE a post on Facebook, from your website then you can use the Graph API, POST, connection section.
https://developers.facebook.com/docs/reference/api/post/
This allows you to create a comment and a like, having the right access_token and the stream_publish permission.
Create:
You can write to the POST_ID/comments connection to post a comment to the post by issuing an HTTP POST request with the publish_stream permission and following parameters.
So you have yo make an HTTP POST request to http://graph.facebook.com/POST_ID/comments?message=HELLO+WORLD&access_token=YOUR_ACCESS_TOKEN
same thing for the like:
make an HTTP POST request to http://graph.facebook.com/POST_ID/likes?access_token=YOUR_ACCESS_TOKEN
with Javascript SDK would be something like this :
var postID='POST_ID';
var msg = 'Comment this post';
FB.api('/'+postID+'/comments', 'post', { message: msg }, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
If you want to share the there is no API documentation for that, but you can use something like this:
<script type="text/javascript">
function sharePost(){
var page = 'https://www.facebook.com/permalink.php?story_fbid=POST_ID&id=PAGE_ID';
var sharer= 'https://www.facebook.com/sharer/sharer.php?u='+encodeURIComponent(page);
var w=660;
var h=460;
var sTop=window.screen.height/2-(h/2);
var sLeft=window.screen.width/2-(w/2);
var sharer= window.open(sharer,"Share","status=1,height="+h+",width="+w+",top="+sTop+",left="+sLeft+",resizable=0");
return false;
}
</script>
<a onclick="sharePOST()">SHARE POST</a>
Do not think facebook yet has such kind of api, though you may look up the iframe url structure for any kind of social widget and try to play around. Here is the list you may look it up https://developers.facebook.com/docs/guides/web/#plugins. Take in consideration that share button is deprecated in favor of like. Also I would rather escape heavy code customization and trying to use API as much as it possible, this would help avoid future incompatibilities while facebook's evolution)
Related
I'm trying to make a website using Google Sign For Websites. Mostly just for the sake of learning about how it works.
I've followed the steps outlined in that tutorial Google Provides which works fine. Users can successfully sign into my site, it is able to pass the users ID to the backend and then verify the ID server side using a php script.
Php then creates a session for the user on the website. What I can't figure out is how would I refresh the page when a user clicks the Google Sign in button and the sign in is successful. Refreshing the page would allow the home page to be reloaded with the new php session data.
<div class="g-signin2 signin-button" data-onsuccess="onSignIn" data-theme="dark"></div>
function onSignIn(googleUser){
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://mywebsite.com/tokensignin.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
};
I've tried using simply location.reload() inside of the onload = function() portion of the code. This causes the page to just infinately refresh every time it is loaded however since Google verifys that the user is signed in through this xhr variable every time.
I've tried looking through their reference to use GoogleAuth.isSignedIn.listen(listener) to monitor any changes but it doesn't seem to fullfull what I want it to or I'm not using it correctly since I don't exactly know what the listener should be.
The other option might be to use their GoogleAuth.attachClickHandler(container, options, onsuccess, onfailure) function but I'm not entirely sure how the properly configure the options field/variable.
If someone could provide some insight as to how this world work I would greatly appreciate it.
To summarize if the user is already signed into my website using Google I want the page to do nothing, if they click the signin button, after the sign in is successful I want to refresh the page they are on.
You could add a listener to xhr with a callback function.
xhr.addEventListener("load", loginComplete);
And then create a function:
function loginComplete(evt) {
console.log("Login Complete");
window.location.reload();
}
EDIT:
Ok. Since the listener doesn't help. You will need to check if the user is already logged in. To save that information one thing I could think of would be using cookies.
So you could store the Auth Token you receive from Google and set a cookie for it and check everytime before you make your POST.
Here is a nice js cookie library: https://github.com/js-cookie/js-cookie
Then onload you save the id:
xhr.onload = function() {
Cookie.set('google_token', id_token);
window.location.reload();
};
And the onSignIn function would be like:
function onSignIn(googleUser){
var cookie = Cookie.get('google_token');
if(cookie != undefined){
//cookie is set
return;
}
...
//rest of the function
}
Of course you need to improve this code, for example, check if the token stored in the cookies is still valid, some cases you can just refresh it instead of making the user log in again (the oAuth API provide such things).
Make some security measures to be sure the token is not being injected and etc..
My approach was the same as yours and I indeed ran into the same problem with constant refreshing.
I tried a couple of solutions, the best working one was as follows:
User signs in using GAPI2 triggering callback onGoogleSignIn
Backend checks ID token validity, and signs user in through session on my webapp
If successful, I log the user out using GAPI2, preventing infinite reload, because onGoogleSignIn is never called again
Then I refresh the page and replace the sign-in button with a logout button for my webapp
This solution is of course pretty much useless if you want to manipulate some data on user's Google account, but I found no use for this functionality.
Code for signing someone out of their google account.
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
Why not have your back end redirect (or send info so the page so it can redirect on success)?
What is the need for reloading the login screen?
You could also check out the listener documentation it seems like this may solve what you want. ie. listen for user change and trigger a function or redirect.
https://developers.google.com/identity/sign-in/web/listeners
i want to create a post that will appear on the recipients 'Visitors Post'. As a test, I am trying to target this page: https://www.facebook.com/SenatorMikulski/. I went to this site http://findmyfbid.com/ to get the user id, which is 142890125771427. Then I am doing this in my code;
ezfb.api('/me/feed','post',{message:'We will miss you',to:[142890125771427]}, function (res) {
debugger
});
The post succeeds but it appears on my timeline and not on the Senator's Visitor Post. What am I doing wrong?
Ok i figured out my mistake. The end point should be 142890125771427/feed
I've a facebook application and I'm using a Feed and Share Dialog popup to post an image on my personal profile. My goal is to tag a friend of mine (instead of posting it on his timeline, I can not change this behaviour for a customer request - considered less spammy).
So, the question is, is there a way to tag a friend in the post? According the API of Feed and Share Dialogs it's not possible, but how can I do that?
Here's the code.
var sIdPersonalProfile = [my personal id profile];
var sIdFriendProfile = [my friend id profile];
var hFacebookData = {
method: 'feed',
display : 'popup',
name: 'NAME_APP',
caption: 'CAPTION_APP',
description: 'DESCRIPTION_APP',
picture: 'URL_APP',
to: sIdPersonalProfile
};
FB.ui(hFacebookData, callback);
thanks in advance.
Assuming you have already figured out how to POST the image to your personal profile. Then, to tag yourself or someone else is quite easy. You need to issue POST request to one of the following urls:
https://graph.facebook.com/PHOTO_ID/tags/USER_ID
https://graph.facebook.com/PHOTO_ID/tags?to=USER_ID
or, if you need to tag more than one user you need to pass an array of user ids...
'https://graph.facebook.com/PHOTO_ID/tags?tags=[{"tag_uid":"1234"}, {"tag_uid":"12345"}]`
This operations will require the following permissions are passed in the scope parameter...
user_photos
publish_stream
You can also specify some extra parameters such as the coordinates of the location of the tag in the image and a tag caption. For more info, check out the Facebook Developer Photo API to publish tags
I'm developing a prototype with two simple pages and google plus integration. I have two pages, first one with a "login" button, the second one with a link. When the user clicks on the login button, I am calling:
var params = {"client_id":"<client_id>", "scope":"https://www.googleapis.com/auth/plus.login"};
gapi.auth.authorize(params, signinCallback);
The signinCallback looks like this:
var signinCallback = function(authResult) {
if (authResult['access_token']) {
gapi.auth.setToken(authResult);
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.list({
'userId': 'me',
'collection': 'visible'
});
request.execute(function(resp) {
console.log(resp);
});
});
} else if (authResult['error']) {
console.error('Sign-in state: ' + authResult['error']);
}
}
So when the user clicks the button, signs in and provides permissions to the app, I'm storing the token and making a people list call. This all works perfect.
My problem is when I navigate to the second page and try to make the same call I made before:
gapi.client.load('plus','v1', function(){
var request = gapi.client.plus.people.list({
'userId': 'me',
'collection': 'visible'
});
request.execute(function(resp) {
console.log(resp);
});
});
The call fails with the error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.
I thought when I did "setToken" after signing up originally, I wouldn't have to continue authenticating every single subsequent call, what am I doing wrong?
If these are truly two different pages (as opposed to one page that has made some AJAX or other calls to your server to get additional data), then each page has a completely different JavaScript environment. This means that the gapi object is a different copy on each page, and the authentication you've set on the first page hasn't been set on the gapi object on the second page. You are not setting a token for the session - you're setting it on a specific JavaScript object.
If you are using something like the Google+ Sign In, you could put the button on each page, and each page would get its own token when the user visits it, but this is somewhat inefficient, since it also means a round-trip to the server each time.
You could probably also do something like put the authentication token into temporary/session local storage, but you should be careful in this case that the token can not leak out and cause you a security issue.
There are other potential solutions, but it really boils down to how you intend to use the authenticated user as part of your client.
I am using the HTML5 version of Facebook Comment in my website. I have my own Facebook APP Id.
Using Graph-API, and FQL (I think this is how to do it), I want to list all the Comments posted in my website.
Example -
Page Title1
--Comment1
--Comment2
--Comment3
Page Title2
--Comment1
--Comment2
--Comment3
Page Title3
--Comment1
--Comment2
--Comment3
etc.
Please help me out.
It is possible, in two different ways, as long as you have a fixed set of sub-pages you want to fetch comments from.
If you have a large amount of sub-pages, or a variable amount, then you don't have a good scalable solution - and many have been looking for one:
Facebook fb:comments Graph API
How to display recent comments from Facebook Comments social plugin?
Facebook FQL query to return all comments against an application
Retrieve all comments with FQL by application ID
Facebook FQL query to return all comments against an application
fql query to get comment count no longer working
http://facebook.stackoverflow.com/questions/10023179/retrieve-all-the-comments-posted-using-fql
For a Fixed set of sub-pages in your website, you can either use a batch request, or an FQL query.
Batch Request
First, you need your access token. Just enter the following as a url in a browser (credit to this website ):
https://graph.facebook.com/oauth/access_token?type=client_cred&client_id=APP_ID&client_secret=APP_SECRET
And this is the javascript jquery code to make a batch request to fetch comments from several urls at once:
$.ajax({
url: 'https://graph.facebook.com/',
type : "POST",
data: {
access_token : 'YOUR_APP_ACCESS_TOKEN',
batch : '[ \
{"method":"GET","relative_url":"URL1"}, \
{"method":"GET","relative_url":"URL2"} \
]'
},
success: function(data) {
jdata = JSON.parse(data);
$.each(jdata, function(index,value){
jdata[index].body = JSON.parse(value.body);
console.log(value.body);
});
// Do whatever you want with jdata
}
});
FQL
inspired from this post
FB.api({
method: 'fql.query',
query: 'select text from comment where object_id in (select comments_fbid from link_stat where url="URL1" or url="URL2")'
}, function(response) {
// Do something with results
});
Conclusion
Because of this limitation of Facebook, I plan to switch to disqus.com, which apparently supports this feature (As you can see from this blog, for example. (search for 'recent comments')
Rather than list all the comments on your site, Facebook wants you to implement code to get notified when a new comment is posted anywhere on your site.
To make this happen, you have to put some Javascript into the page where the comment is posted to also notify yourself:
window.fbAsyncInit = function(){
console.log("subscribing to comment create");
FB.Event.subscribe('comment.create',function(response){
console.log("facbeook comment created: " + JSON.stringify(response));
var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=\'' + response.commentID + '\' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=\'' + response.href + '\')');
FB.Data.waitOn([commentQuery], function () {
console.log("Facebook comment: " + JSON.stringify(commentQuery));
});
});
};
Where rather than just logging the comment to the console, you would need to implement some AJAX that would send the comment back to your site where you could store the comment in your database, or send yourself an email notifying you that the comment has been posted.
Reference: Facebook Comments Plugin
Say your website is http://mywebsite.com/blog.php?id=3 and you have a facebook comments plugin on it,
you can access comments this way
https://graph.facebook.com/comments/?ids={YOUR_URL}.
{YOUR_URL} becomes http://mywebsite.com/blog.php?id=3
Example 1: (Comments plugin installed on developers facebook doc website )
website: http://developers.facebook.com/docs/reference/plugins/comments
fetch comments: https://graph.facebook.com/comments/?ids=http://developers.facebook.com/docs/reference/plugins/comments
Example 2:
website: http://techcrunch.com/2011/04/08/the-seven-most-interesting-startups-at-500-startups-demo-day/
fetch comments: https://graph.facebook.com/comments/?ids=http://techcrunch.com/2011/04/08/the-seven-most-interesting-startups-at-500-startups-demo-day/
Check this too
Sample code for pulling comments can be found on this blog post