Facebook PHP SDK Capture Like Event - facebook

I need to record to the database if a user likes an iframe page tab using the official Facebook 'like' button at the top. I did a search here at stackoverflow and found a javascript snippet ...
FB.Event.subscribe('edge.create',
function(response) {
alert('You liked the URL: ' + response);
}
);
But it doesn't fire for the official button (only like buttons added to the page)? I declare it after FB.init and before FB.Canvas resize inside the asynchronous call. Is there a way in PHP to capture this - possible on refresh? Either JS or PHP is okay (since JS can simply ajax a php file). The signed request contains whether they like the page or not but I need to capture it as it happens (or just happened).
Any help greatly appreciated :-)

Try :
window.fbAsyncInit = function () {
FB.Event.subscribe('edge.create', function (targetUrl) {
_gaq.push(['_trackSocial', 'facebook', 'like', targetUrl]);
});
};
I think you just need to setup the subscript inside the fbAsyncInit.

Did it a purely PHP way in the end.
1: Get the signed request from facebook and extract the liked stats
2: Create a variable $liked and set to "yes" or "no" based on signed request value
3: Manipulate a session - use a session because the page gets refreshed when you "like" but the session remains (but the request value will have changed)
if(isset($_SESSION['likestatus'])){
if($_SESSION['likestatus'] == "no" && $liked == "yes"){
// do mysql updatestuff cause has liked page since session started
$_SESSION['likestatus'] = $liked;
}
else{
$_SESSION['likestatus'] = $liked;
}
}
else {
$_SESSION['likestatus'] = $liked;
}

Related

Display something for people who like or not like our facebook page

I search a solution for the problem highlighted in this question.
Unfortunately, the accepted solution (which dates back to 21/11/2012) doesn't work anymore, as you can this in this demo.
Does someone know why?
Body
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '179378788777832',
status : true,
cookie : true,
xfbml : true
});
</script>
<div id="login">
You are not logged in to FB, Please click here to login.
</div>
<div id="container_notlike">
YOU DONT LIKE
</div>
<div id="container_like">
YOU LIKE
</div>
JS
var hideLogin = function(){
$("#login").hide();
}
var showLogin = function(){
$("#login").show();
}
var doLogin = function(){
FB.login(function(response) {
if (response.session) {
hideLogin();
checkLike(response.session.uid)
} else {
// user is not logged in
}
});
}
var checkLike = function(user_id){
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
}
$(document).ready(function(){
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
hideLogin();
checkLike(response.authResponse.userID)
} else {
showLogin();
}
});
$("#login a").click(doLogin);
});
CSS
body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}
#container_notlike, #container_like, #login {
display:none
}
I search solution for hours but I didn't find anything what works.
Thank you for help.
Like Gating is not allowed anymore, that´s why it is not possible. The only reliable way to get that information is by authorizing a user with the user_likes permission and using /me/likes/[page-id]. But you will not get that permission approved for like gating in the Login Review.
People need to like something because they really want to, not because they get something for it:
Only incentivize a person to log into your app, enter a promotion on your app’s Page, or check-in at a place. Don’t incentivize other actions
Source: https://developers.facebook.com/policy/
Btw, you can also subscribe to the edge.create event to find out if a user just clicked your like button, but you can´t find out if the user liked it before: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
The problem on that code is that FQL is deprecated .
You can't do what you want to, and thats why changes are necessary .
Your code would work if your app is old, created before changes that turns like gating not allowed, but anyway, you cannot use that for show content. You can use that kind of implementation for creating an interactive experience, where you can for example changing the content, saying "Thanks for liking".. Or "Connect with us, liking our page.." ..
You can also think about interfaces, where you show up the page plugin, and just after user likes, you say Thank you ... and hide the page plugin ... But user must always be able to close without liking .
For checking if user likes a page, you need use :
FB.api get on '/me/likes', and with the response ...
if (response.data[likes].name == "Coca-Cola")
or... better
if (response.data[likes].id == "40796308305") {
}
I repeat, One thing has nothing to do with another ..
You can check if user likes a page, but you cannot restrict content, based on this kind of resource .
There are other ways to check it, for exaple :
Get api call to userid/likes/pageid returns page info if user likes the page, and returns nothing if user does not like the page .
You will waste time trying do that for controlling content consumption .
Your app must be aprooved for asking user_likes permission, and its better you think about creating another experience for users, instead of submitting something like that .
I also think that content with good open graph for sharing, commenting and optional liking is very much more efetive, because i noticed that many people used to like and dislike the page after getting the content .
If you just... Prompt a FB.UI for sharing after 1 minute, for example, you will have much more results .. Aways positioning the page plugin in strategic places, people will naturally like your page ..
Than you can say change the page plugin element :
Thank you for liking, please share with your friends ....
Who would also like ...
Or use a callback for triggering the share dialog ..
OLD SCHOOL API CALL
The method FB.Event.subscribe() allowed apps to subscribe to a range of events, and define callback functions for when they fire, is deprecated .
Also FQL Query is deprecated .
For checking if user likes a page, you need user.likes permission, so you can try :
FB.api get on '/me/likes', and with the response ...
if (response.data[likes].name == "Coca-Cola")
or... better
if (response.data[likes].id == "40796308305") { }
There are other ways to check it, for exaple :
Get api call to userid/likes/pageid returns page info if user likes the page, and returns nothing if user does not like the page .
You can check if user likes a page using this call, but you cannot restrict content, based on this kind of resource .
2018 UPDATED SOLUTION
But nowadays, in 2018 the best method for is setting Webhooks .
Webhooks are a subscription based system between Facebook and your server. Your app subscribes to receive updates from Facebook via a specified HTTPS endpoint .
This allows your to app to receive notifications whenever there are updates to a chosen set of topics and their fields, so, you can track changes to most sections of the user's profile, such as About, Photos, Posts, Friends, and Likes.
Webhooks update notifications are sent as POST requests to a callback URL that you supply. Notifications can be lightweight, indicating only that a field has been updated, or can include the newly updated value .
webhooks user reference
Full list of user profile fields that you can subscribe to, such as About, Photos, Posts, Friends, and Likes.
webhooks page reference
The easiest way to set up your app to receive Webhooks updates is to use the App Dashboard's, check out Facebook Platform documentation for more info .
Webhooks documentation

Facebook application: FB events work only for first time

I'm using the following code to subscribe to fb login and logout events.
FB.Event.subscribe('auth.logout', function(response) {
RefreshPageOnFBStatusChange(response);
});
FB.Event.subscribe('auth.login', function(response) {
RefreshPageOnFBStatusChange(response);
});
function RefreshPageOnFBStatusChange(response)
{
alert(response.status);
}
I want to redirect users to different pages when they are logged in or logged out. The function I'm using here gets called only during the actual page load, and never after that. I have a fb-like, fb-share and live stream plugin on a page. When I login and logout of live stream, nothing happens. Help!
Please modify your question and provide all FB-related code.
This may answer you question:
Facebook FB.Event.subscribe event does not fire:(
For User Status you can use if(FB._userStatus == "connected"){} to check user is login or not And for Logout & login you can use following simple code
FB.logout(function(response) { window.location = redriect_uri;
});
It seems like these events don't fire when you use the live chat plugin because it has its own way of handling the login and logout. What I had to do to solve this problem was to set a timeout of 5 seconds and call a javascript function that did a FB.GetLoginStatus, and based on what it was I would refresh the page. Not the best way of doing it, but I was left with no choice.

Uploading Image With Facebook JS SDK

I've put together a script, with the help of another SA post, but the issue I'm having is it's always returning error. When logging the error with console log it contains no properties so I can't determine why I am getting the error.
$(".add-image").click(function() {
FB.login(function(response) {
if (response.authResponse) {
var imgURL="http://farm4.staticflickr.com/3332/3451193407_b7f047f4b4_o.jpg";
FB.api('/album_id/photos', 'post', {
message:'Test',
url:imgURL
}, function(response){
if (!response || response.error) {
console.log(response);
} else {
alert('Post ID: ' + response.id);
}
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'publish_stream'});
});
I've created the app. Added the API ID when including the Javascript.
When running I get a pop up asking me to log in, and it seems to log me in without problems. But it returns an error when checking for a response or response.error.
Any advice.
Not sure if this is still a problem for you, but I've been looking into the same thing recently and I believe that, for this type of upload, FB basically requires source to be the image data itself, not a URL to the image. (See the create photos section on https://developers.facebook.com/docs/reference/api/album/ - it indicates that the source paramater must be multipart/form-data.)
So you have a few workarounds:
1) You may be able to do it from JS if you can create a custom Open Graph Object. I haven't tried this yet, but https://developers.facebook.com/docs/opengraph/usergeneratedphotos/ looks like it expects a URL rather than the post data itself.
2) If the image is originating on the user's computer, you can create an HTML form that submits to FB and have the image go directly from the user to FB without ever hitting your server. This blog post shows an example of that: https://developers.facebook.com/blog/post/498/
3) If the image is originating in your system, you can do a POST from your server to FB that mimics the above form. If it's somewhere else online (such as Flickr), you can download it to your system first and then POST it to FB. You'll have to include an access_token in the request. I don't know what language / framework you're using on your server, but there's probably a library to make creating POST requests easier.

Facebook logout button and redirect after logout

I use this code
<fb:login-button autologoutlink="true" perms="user_likes" size="large"></fb:login-button>
to create a login/logout fb button.
Everything works, after the login, the login button become a logout button. But If the user click on the logout button, the current page is not refreshed and so all the things that should appear only when the user is authenticated are still there until a manual page refresh is done.
This doesn't happen if I get the logout url (Javascript SDK)
$logoutUrl = $facebook->getLogoutUrl();
and then implement a logout button myself; in that case a proper "next" parameter (with the url of the current page) is passed and the current page is reloaded.
I still would like to use the first solution, is it possible to make it use the "next" parameter?
Do the redirect yourself - add this to JavaScript, somewhere after FB.init():
<script>
FB.Event.subscribe("auth.logout", function() {window.location = '/logout'});
</script>
This function will fire when logout through the FB button happens.
For integrated authentication (Facebook + Asp.Net MVC), I just use Javascript and FormsAuthentication.SignOut();
function LogoutFacebook() {
FB.logout(function (response) {
window.location = "/facebook/logout/";
}); }
Above answer by Piskvor did it for me. Its crazy how many hours I've spend trying to figure this out.
Main problem with plugins such as this Facebook for CakePHP is that they don't come with updates. APIs, especially popular ones like Facebook, change all the time because they are being imporved. If the guy who wrote it initially as a hobby moves on with his life and stops updating the SDK people who are less knowladgable on how to alter these things become stuck.
WORKING CODE:
Nevertheless, thanks for a great solution Piskvor, here is my piece of code for
apps/plugins/facebook/views/helpers/facebook.php
$init .= $this->Html->scriptBlock(
<<<JS
window.fbAsyncInit = function() {
FB.init({
appId : '{$appId}',
session : {$session}, // don't refetch the session when PHP already has it
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe("auth.logout", function() {
window.location = '/users/logout'
});
{$callback}
};
The key piece of code here is:
FB.Event.subscribe("auth.logout", function() {
window.location = '/users/logout'
});
{$callback}

Facebook standard status update popup?

Is there an API for opening a popup containing the same status update functionality as in the Facebook Wall?
I basically want to open the following UI in a popup...
How can I do that?
You have to mention the onclick function else what suits your need. oauth2 in facebook involves two steps, call authorize to get code, then call access_token to get token. One way to deal with the pop login:
open login url in new window just like you did,when the facebook redirects back to your url in the popup, you set the cookie either through server side code or using javascript to capture url query parameter, when page is loaded in the popup, close the window immediately window.close.
On your main page, after your window.open code, add JavaScript code to detect if popup is closed and capture the cookie:
var signinWin;
`$('#FacebookBtn').click(function () {
var pos = screenCenterPos(800, 500);
signinWin = window.open("[URL]", "SignIn", "width=780,height=410,toolbar=0,scrollbars=0,status=0,resizable=0,location=0,menuBar=0,left=" + pos.x + ",top=" + pos.y);
setTimeout(CheckLoginStatus, 2000);
signinWin.focus();
return false;
});
function CheckLoginStatus() {
if (signinWin.closed) {
$('#UserInfo').text($.cookie("some_cookie");
}
else setTimeout(CheckLoginStatus, 1000);
}`
hope it help you.
The facebook UI responsible to post a feed is described here.
If you want to have the same design in your application you have to design it yourself, which would be easy with jQuery + ajax