javascript detect if the user liked a page [duplicate] - javascript

I think I'm going crazy. I can't get it to work.
I simply want to check if a user has liked my page with javascript in an iFrame app.
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
This returns: False
But I'm a fan of my page so shouldn't it return true?!

I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}

You can use (PHP)
$isFan = file_get_contents("https://api.facebook.com/method/pages.isFan?format=json&access_token=" . USER_TOKEN . "&page_id=" . FB_FANPAGE_ID);
That will return one of three:
string true string false json
formatted response of error if token
or page_id are not valid
I guess the only not-using-token way to achieve this is with the signed_request Jason Siffring just posted. My helper using PHP SDK:
function isFan(){
global $facebook;
$request = $facebook->getSignedRequest();
return $request['page']['liked'];
}

You can do it in JavaScript like so (Building off of #dwarfy's response to a similar question):
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<style type="text/css">
div#container_notlike, div#container_like {
display: none;
}
</style>
</head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : 'http(s)://YOUR_APP_DOMAIN/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
var page_id = "YOUR_PAGE_ID";
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
FB.login(function(response) {
if (response && response.authResponse) {
var user_id = response.authResponse.userID;
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
FB.Data.query(fql_query).wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
console.log("LIKE");
$('#container_like').show();
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
});
} else {
console.log("NO LIKEY");
$('#container_notlike').show();
}
}, {scope: 'user_likes'});
}
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<div id="container_notlike">
YOU DON'T LIKE ME :(
</div>
<div id="container_like">
YOU LIKE ME :)
</div>
</body>
</html>
Where the channel.html file on your server just contains the line:
<script src="//connect.facebook.net/en_US/all.js"></script>
There is a little code duplication in there, but you get the idea. This will pop up a login dialog the first time the user visits the page (which isn't exactly ideal, but works). On subsequent visits nothing should pop up though.

Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.
The basic code is rather simple:
FB.api("me/likes/SOME_ID", function(response) {
if ( response.data.length === 1 ) { //there should only be a single value inside "data"
console.log('You like it');
} else {
console.log("You don't like it");
}
});
ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:
FB.login(function(response) {
//do whatever you need to do after a (un)successfull login
}, { scope: 'user_likes' });

i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example:
url:
http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file.
in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.

Related

How do I prevent google oauth from auto signing in?

This is related to this question about google plus: Prevent auto sign in with Google plus
The difference is that I'm using the google sign in platform instead of google plus, which has a different api.
Background:
I have a pricing page that has a free trial signup form. The form has the google sign in button. I would like a signed in user to be able to still see the pricing page without the google sign-in causing a redirect.
My Code
I have the meta tag at the top of my page that identifies my application. <meta name="google-signin-client_id" content="MY_CLIENT_ID">
I include this script on my page:<script src="https://apis.google.com/js/platform.js"></script>
I have this div that renders the button: <div class="g-signin2" data-onsuccess="onSignIn"></div>
My onSignIn function looks like this:
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
$('#google_token').val(id_token); //hidden form value
$('#google-oauth').submit(); //hidden form
}
The hidden form is submitted to the backend, where the token is used to retrieve the user's email address and name, and then creates a user account and logs them in.
My problem is that if the user is already signed in, google will automatically call the onSignIn function causing the form to be submitted when the page is loaded. Is there a way for me to prevent the onSignIn function being automatically called?
Reference: https://developers.google.com/identity/sign-in/web/sign-in
Try signing out after you get the user information, I tried sign out, but disconnect did it
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var idToken = googleUser.getAuthResponse().id_token;
gapi.auth2.getAuthInstance().disconnect().then(function () {
//Do stuff here after the user has been signed out, you can still authenticate the token with Google on the server side
}
}
try this:
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
var auth2 = gapi.auth2.getAuthInstance();
auth2.disconnect();
//if this did not had time to sign out put below lines in setTimeout to make a delay
$('#google_token').val(id_token); //hidden form value
$('#google-oauth').submit(); //hidden form
}
See my answer here
I ended up using the custom integration which does not attempt to auto sign in (also allowed me to change the appearance in the same time)
Here is my way to do:
- when page load, if user loged by google, we _counter + 1
thus if _counter != 1 we can do anything because _counter==1 is pageload if loged
<script>
var GoogleOAuth = {
_counter: 0,
_gauth: null,
init:function() {
gapi.auth2.init({
client_id:'xxxxidclientxxx.apps.googleusercontent.com',
scope: 'email profile openid'
}).then(function() {
GoogleOAuth._gauth = gapi.auth2.getAuthInstance();
var isSigned = GoogleOAuth._gauth.isSignedIn.get();
if (isSigned) {
GoogleOAuth._counter++;
}
gapi.signin2.render('btnGooglelogin', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': GoogleOAuth.onSignIn,
'onfailure': GoogleOAuth.onFail
});
});
},
onSignIn: function (googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var name = profile.getName();
var avatarUrl = profile.getImageUrl();
var email = profile.getEmail();
var idToken = googleUser.getAuthResponse().id_token;
if (email == '' || idToken == '') {
alert('Your email will become username, please public your email');
return;
}
if (GoogleOAuth._counter == 1) {
GoogleOAuth._counter++;
return;
}
$.post('/User/Googlelogin', { idToken: idToken, googleId:id,name:name,avatarUrl:avatarUrl,email:email})
.done(function(data) {
if (data.Ok) {
window.location='/';
} else {
alert(data.Message);
}
}).fail(function() {
alert("Error. can not process");
});
},
signOut: function () {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut();
},
onFail:function(error){}
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=googleOnload" async defer></script>
<script>
function googleOnload() {
gapi.load('auth2', function () {
GoogleOAuth.init();
});
}
</script>

Check if the user likes the facebook page or not

I'm trying to check if the user liked my page before use my app on it with the following code
<body onload="liked()">
<script type="text/javascript">
function liked() {
FB.api("me/likes/2002200279160150349", function(response) {
if (response.data.length == 1) {
alert("page liked already");
} else {
alert("page is NOT liked ");
}
});
}
</script>
</body>
determine that the user is authnticated in another page and logged in properly
Simple Approach use this method
FB.api({
method: "pages.isFan",
page_id: my_page_id,
}, function(response) {
console.log(response);
if(response){
alert('You Likey');
} else {
alert('You not Likey :(');
}
}
);
But,This code only works if the user has granted an extended permission for that which is not ideal.
Here's another approach.
In a nutshell, if you turn on the "OAuth 2.0 for Canvas" advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.
function parsePageSignedRequest() {
if (isset($_REQUEST['signed_request'])) {
$encoded_sig = null;
$payload = null;
list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
$sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
$data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
return $data;
}
return false;
}
if($signed_request = parsePageSignedRequest()) {
if($signed_request->page->liked) {
echo "This content is for Fans only!";
} else {
echo "Please click on the Like button to view this tab!";
}
}

JS FQL to Comment_Info keeps returning: "Service temporarily unavailable"

I run a very basic FQL query with JavaScript, and keep getting back an error Object {error_code: "2", error_msg: "Service temporarily unavailable", request_args: Array[8]}
My aim is to read the comment_info.XID of the recent comments posted via Facebook to my website (all the website, not limited to a specific post).
This is my code, based on some samples posted on StackOverflow mostly:
<div id="fb-root"></div>
<div id="fbcomments"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
var fb_app_id = '*';
FB.init({
appId : fb_app_id,
session : null, // 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.getLoginStatus(function (response) {
if (response.status === 'connected') {
if (response.authResponse) {
var fb_access_token = response.authResponse.accessToken; // I even tried hard-coding the value from: https://graph.facebook.com/oauth/access_token?type=client_cred
FB.api(
{
method: 'fql.query',
query: 'SELECT xid,count FROM comments_info WHERE app_id="'+fb_app_id+'"',
access_token : fb_access_token
},
function(newresponse) {
$.each(newresponse, function(i, e) {
$("#fbcomments").append(""+e.text+""); // we get here, but e.text is undefined (see my error on top)
});
}
); //FB.api
} else { //response.authResponse
console.log('no response.authResponse');// do something...maybe show a login prompt
}
} else if (response.status === 'not_authorized') {
console.log(' not_authorized')
} else {
console.log('not_logged_in')
}
});
};
</script>
<script type="text/javascript"> (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true;js.src = "//connect.facebook.net/he_IL/all.js#appId=*&xfbml=1";d.getElementsByTagName('head')[0].appendChild(js); }(document)); </script>
Notes:
I AM the admin of the app for which the app_id is used.
Once I succeed in this current task, I plan on wrapping this FQL query with a match to table comments that will return the actual comment body, not just its XID.
Using standard graph.facebook will only return comments for specific page url. I want all the comments made to my website.
I don't want to iFrame the Facebook Comments Moderation Tool.
I tried:
using and not using FB.init({'session'...}
hard coding fb_access_token.
using and not using #app_id=* in the <script src=""> value.
logging out of Facebook, logging in, and etc.
waiting a few days (even two weeks) between running this query.
UPDATE:
I used PHP as well, but got the same error. This is my PHP script:
// get user access_token
$token_url = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
// response is of the format "access_token=AAAC..."
$access_token = substr(file_get_contents($token_url), 13);
$config = array(
'appId' => $app_id,
'secret' => $app_secret
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if ($user_id) {
$params = array(
'method' => 'fql.query',
'query' => "SELECT xid,count FROM comments_info WHERE app_id=$app_id",
'access_token' => $access_token
);
try {
$result = $facebook->api($params);
var_dump($result);
} catch (Exception $e) {
var_dump($e);
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
Nothing seems to work.
Any ideas what's wrong?

Facebook edge.create

I have added the edge.create event and the event can be fired by the browser as well. But how can I check if the user has liked the page when they come back to the site?
<div id="fb-root"></div>
<script type="text/javascript">
<!--
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR_FACEBOOK_APP_ID', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
// OK
});
};
You are going to want to take a look at the signed_request documentation...
This signed request is facebooks method of validating that the user that made the request is indeed "who he/she says they are". It is encrypted and and uses your application secret to decode the values. Once you parse this signed request you will have the data you need.
function parse_signed_request($signed_request, $secret) {
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = base64_url_decode($encoded_sig);
$data = json_decode(base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
If your question is about like for URL that you can get this information only for user who authorized your application and granted user_likes permission. To do so issue next FQL query:
SELECT user_id, url FROM url_like WHERE user_id = me() and url="URL_OF_PAGE"
If your page have an ID in OpenGraph (or you speak about Facebook Page), by querying Graph API for user's likes connection:
GET https://graph.facebook.com/me/likes/OPEN_GRAPH_OBJECT_ID
But if you speaking about Facebook Page and Application running in Page Tab, you don't need anything special to get this information since it will be passed within signed_request (sample php code using PHP-SDK):
$signedRequest = $facebook->getSignedRequest();
$data = $signedRequest['data'];
if ($data['page']['liked']){
// User is liked this Facebook Page
} else {
// User is not yet liked Facebook Page
}

Facebook Javascript, How to detect if user is a fan of my facebook page? While on my site?

I have the following JS code.
The code's purpose is to first get the users facebook id, and then using FQL check that id against my page ID and make sure the user is a fan.
The problem I am running into is that the only time the code actually works is if i login with my own personal facebook profile. I think its because my profile and the FB.init appid are somehow linked?
Can someone take a look at this code and show me where I am going wrong?
My goal again is to use JS to first get the users id (thus their thumbnail image), and then cross reference that against my own facebook page to check and see if they are a fan. If they are a facebook fan, then I will probably give them a coupon or something.
Thanks in advance.
<script src="http://connect.facebook.net/en_US/all.js"></script>
//Connect to facebook with my app id..
FB.init({
appId:'135445813195028',
cookie:false,
status:true,
xfbml:true
});
//Check to see if user is actually CONNECTED???
FB.getLoginStatus(function(response) {
if (response.session) {
// USER IS CONNECTED
FB.api('/me', function(user) {
if (user != null) {
var image = document.getElementById('imagez');
image.src = 'http://graph.facebook.com/' + user.id + '/picture?type=large';
var name = document.getElementById('name');
name.innerHTML = user.name;
FBID = user.id;
console.log('Facebook ID:' + FBID);
//assemble an FQL query to see if the guy is a fan of our page...
myquery = 'SELECT uid FROM page_fan WHERE page_id = 126923080686340 AND uid = ' + FBID;
console.log('query = ' + myquery);
///Run FQL Query to see if user is a fan
FB.api({
method: 'fql.query',
query: myquery
}, function(resp) {
if (resp.length) {
var IsFan = true;
alert('You are A fan!')
console.log('Visitor is a fan');
//show coupon code...
} else {
alert('Signed into facebook, but Not a fan!');
var IsFan = false;
console.log('Visitor is not a fan');
//show like button...
//once like is clicked then refresh the page...
}
});
//END Run FQL Query to see if user is a fan
}
});
//Figure out if they are a fan...
} else {
// USER IS NOT CONNECTED
alert('NO USER session, user is not logged into facebook!!!');
}
});
The FB.getLoginStatus check to see if the user is connected to your application .. not to facebook.
But when the user is not connected to your application, the .status property can tell you the reason of the fail (if the user is not logged-in at all, or just to your app).
So the structure you should use is
FB.getLoginStatus(function(response) {
if(response.session) {
alert('connected to Application');
} else {
// no user session available, someone you dont know
if(response.status == "notConnected") {
// But user is logged into facebook
alert("Not connected to Application, but is logged in to Facebook");
} else {
// User is not logged into facebook
alert('Not logged in to facebook');
}
}
});
But you cannot access the ID of a user that has not authorized your Application.
Not through Javascript API.

Categories