Facebook $facebook->getUser() always returns 0 - facebook

I am facing an issue based on a facebook app script. It always returning 0, even if the user is login to facebook. I have take a look at the old discussions , but I could not find out the solution . Please take a look at the code.
<?php
require "config/database.class.php";
require 'fbook/src/facebook.php';
require "core/corefunction.php";
$facebook = new Facebook(array(
'appId' => 'xxxxxxx',
'secret' => 'xxxxxxxxx',
));
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
echo "Yes";exit;
}
else{
$urlf= $facebook->getLoginUrl(array('scope' => 'user_status,publish_stream'));
?>
<script language="javascript" type="text/javascript">
document.location.href="<?php echo $urlf; ?>";
</script>
<?php
exit;
}
?>
I am getting an url like this after authenticating facebook,
http://www.example.com/fblog.php?state=91e3e7013fcfeb01df23eed352add987&code=AQAyitCNGSqtCEwMueFi5RvFILI0YC2P4IFdaY0TFK7_ay5vSU1RZh1Ab56DS6aUokQj9VS6RCoYTKmFa0H0AbUFsZBWZTLlFvWqVoOMpwZQcTeCoHcZ1o3NE2VljyoXgfJERreb2ZvL1MhwZ2rKSaInk9SMiyiaNrRXU86fkiL6GBbhrM1aCfuWPq7jqwqG_IM#_=_
it is called continuously ...

Related

Get the facebook accounts value in a particular file

I have used the facebook php sdk and I want to get the value in another file, so I give the redirection path, after login it is going on the page but $user is blank, when I am refreshing the page then I got the values. my code is like below
From where the login page is calling :
$facebook = new Facebook(array('appId' =>FB_APP_ID ,'secret' => FB_APP_SECRET));
$scope='email,user_birthday,user_location,user_work_history,user_about_me,user_hometown';
$parameters=array("redirect_uri"=>"http://www.xyz.com//test.php","scope"=>$scope);
$login_url= $facebook->getLoginUrl($parameters);
and the test.php is like below
$facebook = new Facebook(array(
'appId' => '224402951020359' ,
'secret' => 'd2731260cdd7425dc11eee5f265a3dee'
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_data = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
print_r($user_data);
How can I get the value in first time.
On your test.php page, put a test for !$user and if true then redirect again to the loginurl... something like the following is what I do in my code to avoid this same problem.
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'email,publish_stream,user_birthday,user_location'
)
);
if ($user) {
try {
//get user basic description
$userInfo = $facebook->api("/$user");
$fb_access_token = $facebook->getAccessToken();
} catch (FacebookApiException $e) {
//you should use error_log($e); instead of printing the info on browser
error_log('Sharebox: '.$e); // d is a debug function defined at the end of this file
$user = null;
}
}
if (!$user) {
echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";
exit;
}
Hope this helps.

Facebook - Publish Checkins using PHP SDK/JavaScript SDK

I'm trying to publish checkin using Facebook Graph API. I've gone through Facebook API documentation (checkins) and also have the publish_checkins permission. However, my checkin is not getting published. May I know is there anything wrong or am I missing anything else? Thank you for your time :)
fbmain.php
$user = $facebook->getUser();
$access_token = $facebook->getAccessToken();
// Session based API call
if ($user) {
try {
$me = $facebook->api('/me');
if($me)
{
$_SESSION['fbID'] = $me['id'];
$uid = $me['id'];
}
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href='$loginUrl';</script>";
exit;
}
$loginUrl = $facebook->getLoginUrl(
array(
'redirect_uri' => $redirect_url,
'scope' => status_update, publish_stream, publish_checkins,
user_checkins, user_location, user_status'
)
);
main.php - Using PHP SDK (Wrong SDK used in this example, should use JavaScript SDK instead)
<?php
include_once "fbmain.php";
if (!isset($_POST['latitude']) && !isset($_POST['longitude']))
{
?>
<html>
<head>
//ajax POST of latitude and longitude
</head>
<body>
<input type="button" value="Check In!" onclick="checkin();"/></span>
</body>
</html>
<?php
}
else
{
?>
<script type="text/javascript">
function checkin()
{
try
{
$tryCatch = $facebook->api('/'.$uid.'/checkins', 'POST', array(
'access_token' => $facebook->getAccessToken(),
'place' => '165122993538708',
'message' =>'MESSAGE_HERE',
'coordinates' => json_encode(array(
'latitude' => '1.3019399200902',
'longitude' => '103.84067653695'
))
));
}
catch(FacebookApiException $e)
{
$tryCatch=$e->getMessage();
}
return $tryCatch;
}
</script>
<?php
}
?>
Question solved - Things to take note when publishing checkin
Make sure publish_checkins permission is granted.
Must use json_encode() to encode coordinates parameter for PHP SDK.
place and coordinates parameters are compulsory.
A re-authentication is required if you have just added publish_checkins permission to your existing list of allowed permissions.
Apparently, the configuration and the PHP checkin function that I have posted in the question are correct. However, I should use JavaScript SDK instead of PHP SDK for my case as pointed out by Nehal. For future references...
Using JavaScript SDK
function checkin()
{
FB.api('/me/checkins', 'post',
{ message: 'MESSAGE_HERE',
place: 165122993538708,
coordinates: {
'latitude': 1.3019399200902,
'longitude': 103.84067653695
}
},
function (response) {
alert("Checked in!");
}
);
}
You also need to learn PHP and variable scoping.
$facebook = new Facebook(array(
'appId' => FB_API_KEY,
'secret' => FB_SECRET_KEY,
'cookie' => true,
));
$loginUrl = $facebook->getLoginUrl(
array('scope' => 'status_update,publish_stream,publish_checkins,user_checkins,user_location,user_status,user_checkins')
);
// Session based API call
if ($user) {
try {
$me = $facebook->api('/me');
if($me)
{
$_SESSION['fbID'] = $me['id'];
}
} catch (FacebookApiException $e) {
error_log($e);
}
}
else {
echo "<script type='text/javascript'>top.location.href='$loginUrl';</script>";
exit;
}
function checkin($fb)
{
try
{
$tryCatch = $fb->api('/'.$_SESSION['fbID'].'/checkins', 'POST', array(
'access_token' => $fb->getAccessToken(), //corrected
'place' => '165122993538708',
'message' =>'I went to placename today',
'coordinates' => json_encode(array(
'latitude' => '1.3019399200902',
'longitude' => '103.84067653695'
))
));
}
catch(FacebookApiException $e)
{
$tryCatch=$e->getMessage();
}
return $tryCatch;
}
checkin($facebook); //calling the function and passing facebook object to function

Fan-Gate on Facebook App url + Facebook Tab Display Blank

I have a problem on Facebook App.
I want to make a fan-gate when any one enter the app url, Ex. apps.facebook.com/zoomcompetition/
I can't make it on the tab because it display blank.
but it works on the app url so I want to add fan-gate on the app appoint to Facebook Page.
This is the code
<?php
require 'src/facebook.php';
//require 'fbconfig.php';
require 'functions.php';
// Create An instance of our Facebook Application.
$facebook = new Facebook(array(
'appId' => ***************,
'secret' => **************,
));
// Get the app User ID
$user = $facebook->getUser();
if ($user) {
try {
// If the user is authenticated and logged-in
$user_profile = $facebook->api('/me');
//var_dump($user_profile);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
// If the user is authenticated then generate the variable for the logout URL
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
?>
<!-- Insert Logged in HTML here -->
Logout
<?php
//Always place this code at the top of the Page
session_start();
if (!isset($_SESSION['id'])) {
// Redirection to login page facebook
header("location: index.php");
}
echo ' Welcome '.$_SESSION['username']; // or whatever you want your user to see.
$varri = "http://www.*****.ps";
?>
<iframe src=<?php print $varri; ?> scrolling="auto" width=100% height=100% frameborder="0"> </iframe>
<?php
$user = $facebook->getUser();
if ($user) {
$ret_obj = $facebook->api('/me/feed', 'POST',
array(
'link' => 'https://www.************.com',
'picture' => 'http://www.*******************.jpg',
'caption' => "أهلا وسهلا!",
'message' => ' Welcome '.$_SESSION['username'],
'uid'=> $facebook->getUser()
));
}
?>
<?php
} else {
$loginUrl = $facebook->getLoginUrl();
}
if (!empty($user_profile )) {
$username = $user_profile['name'];
$uid = $user_profile['id'];
$email = $user_profile['email'];
$user = new User();
$userdata = $user->checkUser($uid, 'facebook', $username,$email,$twitter_otoken,$twitter_otoken_secret);
if(!empty($userdata)){
session_start();
$_SESSION['id'] = $userdata['id'];
$_SESSION['oauth_id'] = $uid;
$_SESSION['username'] = $userdata['username'];
$_SESSION['email'] = $email;
$_SESSION['oauth_provider'] = $userdata['oauth_provider'];
//header("Location: home.php");
?>
<!--<!DOCTYPE>
<HTML>
<head>
<script>
function run(){
window.location.href = '/facebook/home.php';
}
</script>
</head>
<body onLoad="run()">
</body>
</html> -->
<?php
}
} else {
die("There was an error.");
}
}
else {
// Generate a session if there is none.
$login_url = $facebook->getLoginUrl(array( 'scope' => ' read_stream, publish_stream, email'));
?>
<!DOCTYPE>
<HTML>
<head>
<script>
function run(){
window.location.href = '<?php echo $login_url ?>';
}
</script>
</head>
<body onLoad="run()">
</body>
</html>
<?php
}
?>
Can you help me to solve one of the following:
What do I need to make it not display "Blank" on the tab?
2- How can I make a fan-gate for specific Facebook Pae if any one go to App
url directly?
What do I need to make it not display "Blank" on the tab?
Generate some output instead of nothing, I’d guess …?
How can I make a fan-gate for specific Facebook Pae if any one go to App url directly?
You can redirect from the canvas page to a specific page/app combination via JavaScript (top.location.href = "FB-Address of your page/app id combo"). And to check whether you’re on the canvas page, the simplest way to do so is give it an extra GET parameter in the canvas page address, which you then can evaluate in your code.

api call only delivers "1" instead of user data

if i use this peace of code:
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true,
));
?>
<html>
<head></head>
<body>
<?
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$userData = $facebook->api("/me");
echo "Name: " . $userData['name'];
echo "<br>userData: " . print_r($userData);
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
// If a user haven't been loged in, so the user have to authorize
if (!$user) {
$loginUrl = $facebook->getLoginUrl(
array(
'scope' => 'publish_stream',
'redirect_uri' => APP_BASEHREF
)
);
echo("<script> top.location.href='" . $loginUrl . "'</script>");
}
i only get this responce:
Name: userData: 1
i don't know the issue. The user is correctly logged in.
i also try it with some test users with the same problem. it seems that the api call does not work correctly. but why.
please can you help me?
still no solution, can anybody help me?
thx
You need to do print_r($userData, true).

Facebook php sdk: ask permission with link, not redirect

I want to change my code so, that first it will check if the user has liked the page. After this (if yes) a question will come up, to accept the terms and if he clicks on the accept button the Facebook permissions request dialog will come up. How can i do this?
The problem is that everytime a user clicks on the app link the $user variable is always false, but he is logged in...
<?php
require 'facebook.php';
$facebook = new Facebook(array(
'appId' => 'xxxxx',
'secret' => 'yyyyy',
'baseUrl' => 'http://hosting.address/',
'appBaseUrl' => 'http://apps.facebook.com/app-name/',
'fileUpload' => 'true',
));
// Get User ID
$user = $facebook->getUser();
$params = array(
scope => 'publish_stream,user_photos',
redirect_uri => 'http://www.facebook.com/xxxxx?sk=app_yyyyy&app_data=1'
);
$signed_request = $facebook->getSignedRequest();
$app_data = $signed_request["app_data"];
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>the title</title>
</head>
<body>
<?php if ($user){
try {
$user_profile = $facebook->api('/me');
$likes = $facebook->api("/me/likes/123123123"); //page ID
if( !empty($likes['data']) ){
$scope = 'publish_stream,user_photos';
$scope_params = explode(',',$scope);
$permissions = $facebook->api("/me/permissions");
if( array_key_exists('publish_stream', $permissions['data'][0]) && array_key_exists('user_photos', $permissions['data'][0]) && isset($app_data)) {
} else {
echo "accept</td>";
echo "deny</td>";
}
}else{
echo "<img width=\"520px\" src=\"no-fan.jpg\" />";
}
} catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
if ($user) {
} else {
$loginUrl = $facebook->getLoginUrl($params);
echo '<script type="text/javascript">top.location.href = "'.$loginUrl .'";</script>';
}
?>
</body>
</html>
Try following this excellent example:
http://www.jelecos.com/default/blog/11-04-18/Facebook_PHP_SDK_Fangate_Creation.aspx
Then on the fanpage.php have your code to ask them to log in.