I know, that my question was asked a lot of times here, but for me no answer worked.
I've created a Facebook Fanpage Tab. All the files are stored at my private Webspace.
Now I want to determine if a user already liked the page or haven't liked it yet!
So I used this code:
<?php
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) {
$isteinfan = "false";
}
else {
$isteinfan = "true";
}
}
//PHP Variable an JavaScript übergeben
echo "<script>";
echo "isteinfan = '$isteinfan';";
echo "console.log('ist ein fan: ');";
echo "console.log(isteinfan);";
echo "</script>";
?>
But it doesn't work.
Can u give me help, please!!!
Yours, Raphael
I would recommend you include the facebook php library, which you can download from https://github.com/facebook/php-sdk/tree/master/src. You have to place all the three files in the same directory. Then you can get the liked status very easily:
define('APP_ID','xxxxxxxx');
define('APP_SECRET','xxxxxxxx');
require ("facebook.php");
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$liked = $signed_request["page"]["liked"];
Now $liked is a boolean which can be true or false
Related
I'm using this code to check if the user has "liked" the page before going into my app.
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$this->facebook = new Facebook(array(
'appId' => 'APPID',
'secret' => 'APPSECRET',
'cookie' => true,
));
$session = $this->facebook->getSession();
if(!empty($session)) {
$access_token = $this->facebook->getAccessToken();
$fql_multiquery_url = 'https://graph.facebook.com/me/likes?access_token='.$access_token;
$fql_multiquery_result = file_get_contents($fql_multiquery_url);
$fql_multiquery_obj = json_decode($fql_multiquery_result, true);
$liked = false;
foreach($fql_multiquery_obj['data'] as $like){
if($like['id'] == 'PageID'){
$liked = true;
}
}
if($liked){
$data['main_content'] = 'welcome_message';
} else {
$data['main_content'] = 'before_like';
}
$this->load->view('includes/template', $data);
} else {
$req_perms = "publish_stream,offline_access,user_status,email,read_stream,user_likes";
$login_url = $this->facebook->getLoginUrl(array('canvas'=> 1,'fbconnect' => 0,'req_perms' => $req_perms, 'redirect_uri' => 'APP REDIRECT URL'));
echo "<script type='text/javascript'>top.location.href = '$login_url';</script>";exit;
}
(I know looping through your likes isn't the best solution, but it seems to work the most consistent for me).
It works for me just fine (and a couple other users in the office works fine too), but it fails for a few users (of course they send me no error message). Is there a better way I can check for likes and have it be consistent?
You should be able to get to a specific page like this:
$resp = $this->api('/me/likes/'.$page_id);
$is_fan = (count($resp['data']) !== 0);
However this doesn't help if facebook's internal cache is acting up, also if this request runs on a facebook tab, the signed request should also have the fan/no_fan information in signed_request (see the part about fields and values). In my experience the signed_request seemed to be the most reliable.
P.S.:
You seem to be using a fairly old version of the php sdk, the getSession() method have been deprecated.
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;
}
$signed_request = $_REQUEST['signed_request'];
//check for page liked or not
if($signed_request = parsePageSignedRequest())
{
if($signed_request->page->liked) {
echo "<link rel='stylesheet' type='text/css' href='style.css' />";
} else {
echo "<link rel='stylesheet' type='text/css' href='notfanstyle.css' />";
}
}
:) try this, it worked for me.
so basically im trying to get a like gate working but the $like_status variable never changes so my condition to change to the liked content will never work. Does anyone know why this never changes? Have added my app to a page tab on facebook and it gets all the other variables $page_id, $page_admin, $country and $locale but not $like_status.
Thanks Charlie
See Code Below
<?php
enter code here
require_once('AppInfo.php');
// Enforce https on production
if (substr(AppInfo::getUrl(), 0, 8) != 'https://' && $_SERVER['REMOTE_ADDR'] != '127.0.0.1') {
header('Location: https://'. $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
exit();
}
// This provides access to helper functions defined in 'utils.php'
require_once('utils.php');
require 'includes/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => AppInfo::appID(),
'secret' => AppInfo::appSecret(),
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
$page_id = $signed_request["page"]["id"];
$page_admin = $signed_request["page"]["admin"];
$like_status = $signed_request["page"]["liked"];
$country = $signed_request["user"]["country"];
$locale = $signed_request["user"]["locale"];
echo "<br>page id = $page_id";
echo "<br>page admin = $page_admin";
echo "<br>like status = $like_status";
echo "<br>country = $country";
echo "<br>locale = $locale";
function grokSignedRequest()
{
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;
}
// call the function to parse the signed request
$sr_data = grokSignedRequest();
// check like status
if ($sr_data->page->liked==1)
{
include ('includes/index2.php');
}
else
{
include ('includes/index1.php');
}
?>
If you are running your PHP code on a tab page, like_status is probably actually present, but set to a value of 0 (zero). Thus, the echo statement seems to be outputting nothing for $like_status, but in reality, it has a value of zero. To prove this try code like this:
if ($like_status == 0)
echo "it's zero";
else
echo "it's not zero";
Edit: Sorry, I didn´t see that #robbie solved this in the comments of the question
The user must arrive to the App from the page tab, and:
As with a Canvas Page, you will not receive all the user information accessible to your app in the signed_request until the user authorizes your app.
https://developers.facebook.com/docs/appsonfacebook/pagetabs/#integrating
So basically i am building a script for a client which is used as an iframe in his page. What it should do is when a user likes his page then he can see the contents and the "app" should auto post something to his wall (sounds like spam but im not sure if there is a problem with that). so i got the first bit working but for the love of god i cant make the second part.. here's my code
<? require 'facebook.php';
$app_id = "my_appid";
$app_secret = "my_secret";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
$signed_request = $facebook->getSignedRequest();
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!";
}
}
?>
i tried adding this on the "logged state"
$result = $facebook->api( '/me/feed/','post',
array('access_token' => $app_secret,
'message' => 'Playing around with FB Graph..')
);
with no luck as i get an error. please let me know if you can help. thanx
The first part, liking a url and autoposting to users stream has nothing todo with the code you show. this code is just a simple fan gateway.
no user is logedin.
The steps you would need are:
let the user login and ask for publish_stream permission (more info)
set a listener on the edge.create event (more info)
if this event fires send an ajax call to server to make the post. (more info)
I have read and tried to implement the scores system on the Facebook API almost word for word but am getting and getting an error
{"error":{"message":"Unsupported post
request.","type":"GraphMethodException"}}
So far no one has answered the solution to this problem, maybe I am doing some thing wrong. I am now re wording the question as to how other have managed to do it with code examples.
I would like to thank you in advance for you efforts in helping me.
The index.php has the following
require_once 'facebook.php';
$fbAppId = 'APPID';
$fbSecret = 'FBSECRET';
$fbCanvasUrl = 'CANVASURL';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => $fbAppId,
'secret' => $fbSecret,
));
// Get User ID
$user = $facebook->getUser();
// Redirect to the canvas url if we're authorized and logged in
// You can also use $_REQUEST['signed_request'] for this
if($_GET['code']) {
echo "<script>top.location.href='".$fbCanvasUrl."'</script>";
exit;
}
// We may or may not have this data based on whether the user is logged in.
//
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
else {
$loginUrl = $facebook->getLoginUrl();
echo "<script>top.location.href='".$loginUrl."'</script>";
exit;
}
It also includes the javascript
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({appId: '<?=$fbAppId?>', status: true, cookie: true, xfbml: true,oauth: true});
};
(function() {
var ts = new Date().getTime();
var e = document.createElement("script");
e.type = "text/javascript";
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js?ts='+ts;
e.async = true;
document.getElementById("fb-root").appendChild(e);
}());
</script>
So.... The index.php initiates everything, I have a Javascript file that will play the game and set a cookie with the score and the following php file picks up the cookie and sets the score....
<?php
require_once('facebook.php');
$config = array(
'appId' => 'APPID',
'secret' => 'SECRET',
);
$facebook = new Facebook($config);
$app_id = 'APPID';
$app_secret = 'SECRET';
$canvas_page_url = 'CANVASURL';
// Get the User ID
$signed_request = parse_signed_request($_POST['signed_request'],
$app_secret);
$uid = $signed_request['user_id'];
// Get an App Access Token
$token_url = 'https://graph.facebook.com/oauth/access_token?'
. 'client_id=' . $app_id
. '&client_secret=' . $app_secret
. '&grant_type=client_credentials';
$token_response = file_get_contents($token_url);
$params = null;
parse_str($token_response, $params);
$app_access_token = $params['access_token'];
//Get Score **************
if(isset($_COOKIE['Sscore']))
$cscore = $_COOKIE['Sscore'];
else
exit;
$score=$cscore;
// POST a user score
//print('Publish a User Score<br/>');
$score_URL = 'https://graph.facebook.com/' . $uid . '/scores';
$score_result = https_post($score_URL,
'score=' . $score
. '&access_token=' . $app_access_token
);
printf('<br/>%s<br/>',$score_result);
function https_post($uri, $postdata) {
$ch = curl_init($uri);
// curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
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, '-_', '+/'));
}
?>
I have a file named fbmain.php which will authenticate the user.
<?php
//set facebook application id, secret key and api key here
$fbconfig['appid' ] = "MY_APP_ID";
$fbconfig['secret'] = "MY_APP_SECRET";
$uid = null; //facebook user id
try{
include_once "facebook.php";
}catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
//Facebook Authentication part
$session = $facebook->getSession();
//Get permission from user
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update'
)
);
if (!$session) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
if ($session) {
try {
$uid = $facebook->getUser();
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
}
//signed_request part
$signed_request = $_REQUEST['signed_request'];
$secret = $fbconfig['secret'];
$data = parse_signed_request($signed_request, $secret);
$fan_page_id = $data['page']['id'];
$admin_check = $data['page']['admin'];
$like_check = $data['page']['liked']; //New
//Get fan page id
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, '-_', '+/'));
}
?>
I have included fbmain.php file to my index.php file and access user data.
Then later I wanted to access user birthday.So I added 'user_birthday' permission references to the fbmain.php file.code is given bellow
//Get permission from user
$loginUrl = $facebook->getLoginUrl(
array(
'canvas' => 1,
'fbconnect' => 0,
'req_perms' => 'email,publish_stream,status_update,user_birthday'
)
);
code of the index.php file is given bellow,
<?php
//index.php file
include_once "fbmain.php";
$me = $facebook->api('/me');
$_SESSION['id'] = $me['id'];
$_SESSION['name'] = $me['name'];
$_SESSION['link'] = $me['link'];
$_SESSION['email'] = $me['email'];
if($me['birthday'] == null){ ?>
<script>
top.location = 'http://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&scope=user_birthday';
</script>
<?php }else{ ?>
//Some other codes
<?php } ?>
I redirect user to permission window requesting user's birthday if $me['birthday'] returns null value. I had to add this part since I added user_birthday to the scope of permission references later.
This works for some users and display 'Request for Permission' window asking to access user's birthday.
But for some users it display a facebook error message(It may since I try to access user's birthday before display 'Request for Permission' window : $me['birthday']==null)
Can anyone tell me a proper way to get the re-permission from user to access user birthday?
Note that this problem occurs only for users those who have already authenticated in my app
You know facebook changed the parameter for the permissions from req_perms to scope in getLoginUrl() function. Try scope, may be it works.
https://github.com/facebook/php-sdk/issues/381
I don't understand php...bt check FB.ui
https://developers.facebook.com/docs/reference/dialogs/oauth/
Here you have oAuth dialog to ask for user permision.
You can use scope params for you requesting permission.
this is code for you want to replace
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday',
)
);
if you these this code ,your visitor who visit first time this code request full permision ,and already authendicate for other permisions user comes to this page it request only for birthday permisions .
you not need to use
if($me['birthday'] == null){ ?>
<script>
top.location = 'http://www.facebook.com/dialog/oauth?client_id=MY_APP_ID&redirect_uri=MY_REDIRECT_URL&scope=user_birthday';
</script>
<?php }else{ ?>
//Some other codes