Check if the user likes the facebook page or not - javascript

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!";
}
}

Related

XMLHttpRequest POST _self using localStorage with PHP

I'm using PHP 7.3 with MySQL v5.6.
Browsing a catalog page, I stored some items ids to localStorage.wishlistStorage.data, and now on the wishlist page I want to retrieve this list of ids for display. I'm using PHP because later I will be sending and retrieving items from a database. Also, it's easy to build HTML on the fly using PHP and a POST array. Unfortunately, I'm struggling with the AJAX XMLHttpRequest.
I am loading a Javascript file at the bottom of the page that retrieves the localStorage data:
var wishlistStorage = {};
window.addEventListener("load", function() {
wishlistStorage.get();
loadWishlist();
});
wishlistStorage = {
data : null, // empty storage
get : function() {
wishlistStorage.data = localStorage.getItem("wishlistStorage");
if(wishlistStorage.data === null) {
wishlistStorage.data = { items: [], item_notes: [], comments: '' };
wishlistStorage.save();
}
else {
wishlistStorage.data = JSON.parse(wishlistStorage.data);
}
}
};
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var wishlistRequest;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
console.log("Got them.");
} else {
console.log("I see nothing.");
}
wishlistRequest.open("POST", "_self", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items));
}
}
In the body of wishlist.php
<?php
if (array_key_exists('wishlist', $_POST)) {
$temporary_wishlist = $_POST['wishlist'];
echo "Yes, it works! $temporary_wishlist";
} else {
echo 'Invalid parameters!';
}
?>
All I get is the "Invalid Parameters" message. None of the console.log messages appear. Where am I going wrong?
source

Get specific section of AJAX response

When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML.
Here is the first two lines of the response:
{"returnVal":"registered"}<!DOCTYPE html>
<html lang="en">
Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in
loginData = "email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "loggingIn";
urlPath = "index.php";
} else { // we are registering
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
}
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert(result); // i need to get the value of 'returnVal' from the response
if(result.returnVal=="registered") {
document.getElementById('notification').innerHTML = "You have been registered";
} else if (result.returnVal=="username") {
document.getElementById('notification').innerHTML = "Username already taken";
} else if (result.returnVal=="email") {
document.getElementById('notification').innerHTML = "Email already taken";
} else if (result.returnVal=="notRegistered") {
document.getElementById('notification').innerHTML = "Please enter registered email";
} else if (result.returnVal=="loginFail") {
document.getElementById('notification').innerHTML = "Please enter correct password";
} else if (result.returnVal=="loggedIn") {
$('#myModal').modal('hide');
document.getElementById('loginButton').innerHTML = "Account Settings";
} else { // Something wrong, tell us
//alert(result);
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
})
}
index.php
<?php
ini_set("log_errors", 1);
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
}
}
$view->Begin();
?>
Ultra simple way is just exit() after you echo the json so the view never gets sent. If this controller is never intended to render a view get rid of $view->Begin();
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
exit();
}
}
This is a (messy but still) way to extract the data you need.
But please consider my first comment. You should do it the other way round.
var result = '{"returnVal":"registered"}<!DOCTYPE html>someother grap';
var n = result.indexOf("<!DOCTYPE");
var jsonString = input.substring(0, n);
var json = JSON.parse(jsonString);
console.log(json);
// your values are here:
// json.returnVal;
This relies on the strict convention, that every return has a '

Add video to user's Favorite/Like playlist on YouTube

The aim is to create a Favorite/Like button using the YouTube API. When a user clicks the button, the video is saved into the user's Favorite/Like playlist.
Just like how it works when you implement a Facebook like button on your own site.
This is essentially a follow up question to the fantastic solution posted by Bertrand Martel on my previous question where we aimed to add a video to the Watch Later playlist.
The working code for this particular function is:
<!-- button 1 -->
<button type="submit" data-youtube-video-id="EH3gqI2NAiE" value="Watch Later" class="ma_youtube_watch_later" name="send">
<div class="ma_youtube_watch_later_text">Watch Later</div>
</button>
<!-- button 2 -->
<button type="submit" data-youtube-video-id="0EMmKIIF-zE" value="Watch Later" class="ma_youtube_watch_later" name="send">
<div class="ma_youtube_watch_later_text">Watch Later</div>
</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
// By Bertrand Martel: https://stackoverflow.com/a/42561941/1649673
var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
var init = false;
var youtube_video_id = '';
var button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.ma_youtube_watch_later').off('click');
jQuery('.ma_youtube_watch_later').click(function(e) {
button = this;
var youtube_video_id = jQuery(this).attr("data-youtube-video-id");
// Add a video ID specified in the form to the playlist.
function addVideoToPlaylist() {
//addToPlaylist(jQuery('#video-id').val());
addToPlaylist(youtube_video_id);
}
if (authResult && !authResult.error) {
addVideoToPlaylist();
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
button = this;
addVideoToPlaylist(self);
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addVideoToPlaylist();
}
});
}
// Add a video to a playlist. The "startPos" and "endPos" values let you
// start and stop the video at specific times when the video is played as
// part of the playlist. However, these values are not set in this example.
function addToPlaylist(id, startPos, endPos) {
var details = {
videoId: id,
kind: 'youtube#video'
}
if (startPos != undefined) {
details['startAt'] = startPos;
}
if (endPos != undefined) {
details['endAt'] = endPos;
}
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: "WL",
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
//jQuery('#status').html('<pre>Succesfully added the video : ' + JSON.stringify(response.result) + '</pre>');
// change button text
$(button).text('Video added');
} else if (response.code == 409) {
//jQuery('#status').html('<p>Conflict : this video is already on your Watch Later playlist</p>');
// change button text
$(button).text('Already added');
} else if (response.code == 404) {
//jQuery('#status').html('<p>Not Found : this video hasnt been found</p>');
// change button text
$(button).text('Video not found');
} else {
//jQuery('#status').html('<p>Error : code ' + response.code + '</p>');
// change button text
$(button).text('Error: Try again');
}
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
And we have a number of PHP code samples on the API docs. We also have some documentation on adding a video to playlist.
How can this be achieved using either PHP or/and javascript?
You can find Like & Favorite playlist ID with channel list endpoint with the following parameters (check this sample request) :
{
mine: true,
part: 'contentDetails'
}
You will get the list of playlists in relatedPlaylists including likes, favorites, uploads, watch later and watch history.
{
"kind": "youtube#channelListResponse",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/S1x68O9aSpvmndklrnSwKw_yYdE\"",
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
},
"items": [{
"kind": "youtube#channel",
"etag": "\"m2yskBQFythfE4irbTIeOgYYfBU/ura_vsrPt5tCZkjjGbH3ihN3Bq4\"",
"id": "UCnQt5EmYRfX1uVYtwPNj7Dg",
"contentDetails": {
"relatedPlaylists": {
"likes": "LLnQt5EmYRfX1uVYtwPNj7Dg",
"favorites": "FLnQt5EmYRfX1uVYtwPNj7Dg",
"uploads": "UUnQt5EmYRfX1uVYtwPNj7Dg",
"watchHistory": "HL",
"watchLater": "WL"
}
}
}]
}
For WatchLater & WatchHistory, the playlistId is the same for all users (respectively WL & HL)
You can call channel list endpoint in Javascript with gapi.client.youtube.channels.list the same way as you've called the playlist insert API.
Then with the playlistId you can insert your video to another playlist than Watch Later.
In the following code, you will find 3 buttons to add different videos to Watch Later playlist, Like playlist & Favorite playlist
Javascript
Here is a live demo with the source code (as below)
Here is a fiddle. Replace your client id and add as Authorized JavaScript origins in developer console : https://fiddle.jshell.net
<!doctype html>
<html>
<head>
<title>Add to multiple playlists</title>
</head>
<body>
<input type="submit" data-youtube-video-id="EH3gqI2NAiE" data-type="WL" value="Add to Watch Later playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="0EMmKIIF-z" data-type="likes" value="Add to Like playlist" class="yt_add_to_playlist" />
<input type="submit" data-youtube-video-id="T4ZE2KtoFzs" data-type="favorites" value="Add to Favorite playlist" class="yt_add_to_playlist" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
var OAUTH2_CLIENT_ID = '28993181493-c9o6hdll3di0ssvebfd4atf13edqfu9g.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
var init = false;
var button = null;
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
jQuery('.yt_add_to_playlist').off('click');
jQuery('.yt_add_to_playlist').click(function(e) {
button = this;
if (authResult && !authResult.error) {
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
} else {
init = true;
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
}
return false;
});
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
jQuery('.pre-auth').hide();
jQuery('.post-auth').show();
loadAPIClientInterfaces();
jQuery('#add_to_wl').click(function(e) {
button = this;
addToPlaylist($(this).attr("data-youtube-video-id"), $(this).attr("data-type"));
});
}
}
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
if (init) {
init = false;
addToPlaylist($(button).attr("data-youtube-video-id"), $(button).attr("data-type"));
}
});
}
function addToPlaylist(videoId, playlistType) {
console.log("add to playlist type : " + playlistType);
if (playlistType != "WL" && playlistType != "HL") {
var request = gapi.client.youtube.channels.list({
mine: true,
part: 'contentDetails'
});
request.execute(function(response) {
var playlistId = response.result.items[0].contentDetails.relatedPlaylists[playlistType];
if (typeof playlistId != 'undefined') {
console.log("found playlist id : " + playlistId);
insertToPlaylist(videoId, playlistId);
} else {
console.log("playlist not found");
}
});
} else {
insertToPlaylist(videoId, playlistType);
}
}
function insertToPlaylist(videoId, playlistId) {
var details = {
videoId: videoId,
kind: 'youtube#video'
};
var request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: playlistId,
resourceId: details
}
}
});
request.execute(function(response) {
console.log(response);
if (!response.code) {
$(button).val('Video added');
} else if (response.code == 409) {
$(button).val('Already added');
} else if (response.code == 404) {
$(button).val('Video not found');
} else {
$(button).val('Error: Try again');
}
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>
</body>
</html>
Replace OAUTH2_CLIENT_ID with your own client ID
In the API response, the status code is checked in case the video is not found (404). The 409 status code is returned if the video is already in the playlist but only for watch later playlist (adding an existing video to like/favorite playlist will not changed anything though)
PHP
The same as before, based on google-api php sample :
install composer : see instructions
install google-api client :
composer require google/apiclient:~2.0
The php script multi-playlist.php :
<?php
/**
* Library Requirements
*
* 1. Install composer (https://getcomposer.org)
* 2. On the command line, change to this directory (api-samples/php)
* 3. Require the google/apiclient library
* $ composer require google/apiclient:~2.0
*/
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
throw new \Exception('please run "composer require google/apiclient:~2.0" in "' . __DIR__ .'"');
}
require_once __DIR__ . '/vendor/autoload.php';
session_start();
$response = "";
/*
* You can acquire an OAuth 2.0 client ID and client secret from the
* {{ Google Cloud Console }} <{{ https://cloud.google.com/console }}>
* For more information about using OAuth 2.0 to access Google APIs, please see:
* <https://developers.google.com/youtube/v3/guides/authentication>
* Please ensure that you have enabled the YouTube Data API for your project.
*/
$OAUTH2_CLIENT_ID = 'YOUR_CLIENT_ID';
$OAUTH2_CLIENT_SECRET = 'YOUR_CLIENT_SECRET';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
// Check if an auth token exists for the required scopes
$tokenSessionKey = 'token-' . $client->prepareScopes();
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION[$tokenSessionKey])) {
$client->setAccessToken($_SESSION[$tokenSessionKey]);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
$videoId = "";
if (isset($_GET['video'])){
$videoId = $_GET['video'];
}
else if(isset($_SESSION['video'])){
$videoId = $_SESSION['video'];
}
if (isset($_GET['action'])){
$action = $_GET['action'];
}
else if(isset($_SESSION['action'])){
$action = $_SESSION['action'];
}
if(isset($videoId) && isset($action) && !isset($_GET['state'])) {
file_put_contents('php://stderr', print_r("adding video to watch later playlist " . $videoId . "\n", TRUE));
if ($action == "Add to Watch Later playlist") {
$playlistId = "WL";
}
else {
$listResponse = $youtube->channels->listChannels("contentDetails", array(
'mine' => true
));
if (!empty($listResponse)) {
if ($action == "Add to Like playlist"){
$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['likes'];
}
else if ($action == "Add to Favorite playlist"){
$playlistId = $listResponse['items'][0]['contentDetails']['relatedPlaylists']['favorites'];
}
}
}
if (isset($playlistId)){
// 5. Add a video to the playlist. First, define the resource being added
// to the playlist by setting its video ID and kind.
$resourceId = new Google_Service_YouTube_ResourceId();
$resourceId->setVideoId($videoId);
$resourceId->setKind('youtube#video');
// Then define a snippet for the playlist item. Set the playlist item's
// title if you want to display a different value than the title of the
// video being added. Add the resource ID and the playlist ID retrieved
// in step 4 to the snippet as well.
$playlistItemSnippet = new Google_Service_YouTube_PlaylistItemSnippet();
$playlistItemSnippet->setTitle('First video in the test playlist');
$playlistItemSnippet->setPlaylistId($playlistId);
$playlistItemSnippet->setResourceId($resourceId);
// Finally, create a playlistItem resource and add the snippet to the
// resource, then call the playlistItems.insert method to add the playlist
// item.
$playlistItem = new Google_Service_YouTube_PlaylistItem();
$playlistItem->setSnippet($playlistItemSnippet);
$playlistItemResponse = $youtube->playlistItems->insert(
'snippet,contentDetails', $playlistItem, array());
$response = json_encode($playlistItem);
}
else{
$response = "no playlist selected";
}
$_SESSION['video'] = "";
$_SESSION["action"] = "";
}
else{
file_put_contents('php://stderr', print_r("no video was specified", TRUE));
}
} catch (Google_Service_Exception $e) {
$response = htmlspecialchars($e->getMessage());
} catch (Google_Exception $e) {
$response = htmlspecialchars($e->getMessage());
}
$_SESSION[$tokenSessionKey] = $client->getAccessToken();
} else {
if(isset($_GET['video'])){
$_SESSION["video"] = $_GET['video'];
$_SESSION["action"] = $_GET['action'];
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
}
}
?>
<!doctype html>
<html>
<head>
<title>Add to playlists</title>
</head>
<body>
<div>
<form id="form" action="multi-playlist.php"">
<input type="hidden" name="video" value="EH3gqI2NAiE">
<input name="action" type="submit" value="Add to Watch Later playlist" />
<input name="action" type="submit" value="Add to Like playlist" />
<input name="action" type="submit" value="Add to Favorite playlist" />
</form>
<div>
<?php echo $response ?>
</div>
</div>
</body>
</html>
For this PHP version, note that in addition to the video id in the current session $_SESSION["video"], the target action is also stored in $_SESSION["action"] to be able to determine which playlist to use. Playlists are retrieved with channel list endpoint with $youtube->channels->listChannels.
Note that it can take some time for the video to appear in the playlists (sometimes a few seconds)

Javascriptvoid(0) wont call function

I have looked over my code and realized there where a few issues with the script. Now I have sorted it it will not pass through the checking you have the correct funds. i think it has something to do with the way i have declared my variable
<script type="text/javascript">
var money = "<?php echo $ir['money']; ?>";
var price = 5000;
function openAccount() {
var c = confirm("Are you sure you want to open a bank account for <?=money_formatter(price)?>?");
if(c) {
$('#main_text').html('Opening account');
$('#main_text').append('Checking you have the correct funds');
if(+money < +price) {
$('#main_text').append('<span style="color: red;">Incorrect funds, You need another <?=money_formatter((price)-$ir["money"])?>...</span>');
} else {
$.post('<?=file?>?open=true&print=1', function(data) {
if(data == 'not_enough_money') {
$('#main_text').append('Incorrect funds...');
} else if(data == 'opened') {
$('#main_text').append('You have succesfully opened your brand new bank account!>View Account');
}
});
}
}
}
You simply forgot two quotes.
Replace <a href="javascript:void(0); onClick=new_account();">
by <a href="javascript:void(0);" onClick="new_account();"> and everything will work.

javascript detect if the user liked a page [duplicate]

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.

Categories