setting up facebook api login with php authorization - facebook

Currently I have the facebook api working. I have included scope string to grab extra permissions.
I am lacking the ability to authorize access to restricted pages on my site. How can I set it up so when facebook logs the user in they are also logged in to my site?
<?php
include 'src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => '****************',
'secret' => '****************',
'cookie' => true
));
// Get User ID
$user = $facebook->getUser();
// 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;
}
}
// Login or logout url will be needed depending on current user state.
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
echo "<a href='$logoutUrl'>Logout</a>";
} else {
$statusUrl = $facebook->getLoginStatusUrl();
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'user_checkins, user_location, friends_checkins')
);
echo "<a href='$loginUrl'>Login</a>";
}
?>
<h3>Welcome to your profile</h3>
<?php
echo $user_profile['first_name'];
echo ' <span> </span> ';
echo $user_profile['last_name'];
?>
This is the basic php api from facebook.

There are endless ways to do this, but you should just be able to place the private content inside of an IF block checking for the logged in Facebook user:
<?php if ($user): // Show the private content ?>
<h3>Welcome to your profile</h3>
<?php
echo $user_profile['first_name'];
echo ' <span> </span> ';
echo $user_profile['last_name'];
?>
<?php endif; ?>

Related

Publishing comments on a user post wtih graph api

I am new to facebook graph api
i have written a small application for posting comments on the user profile.
the following is the code:
<?php
require_once 'config.php';
/* Get a valid session */
$user= $facebook->getUser();
$me = null;
if($user) {
//Check if session is valid
$me = $facebook->api('/me');
}
if($me) {
echo 'User is logged in and has a valid session';
print_r($me);
$id=getfirstpostid($facebook->api('/me/posts'));
echo "id is ".$id;
$message="This is done programatically";
$comment_id = $facebook->api('/'.$id.'/comments','POST',
array('message' => $message,));
//$like_id = $facebook->api('/'.$id.'/likes', 'POST');
}
else {
//$login_url = $facebook->getLoginUrl();
//header("Location: {$login_url}");
echo 'Session expired or user has not logged in yet.
Redirecting...';
$login_url=$facebook->getLoginUrl(array('req_perms'=>'publish_actions,user_likes,offline_access,manage_pages,user_friends',));
echo '<script>top.location.href="'. $login_url .'";</script>';
}
function getfirstpostid($feeds)
{
return $feeds['data'][0]['id'];
}
?>
<?php
$logoutUrl = $facebook->getLogoutUrl(array('next' => 'http://distanceeducationhelpline.org/',));
?>
<a href='<?php echo $appBaseUrl?>about.php' target='_top'>
About Us</a>
<a href='http://www.9itech.com' target='_top'>External Link</a>
<br/>
<br/>
<a href ="#" onclick="top.location.href='<?php echo $logoutUrl; ?>';
return false;">Logout</a>
a. While creating the app ,i have not provided secure Canvas Url and accordingly the Canvas page does not show up in facebook.
is it due to the secure canvas url not being proper that blank page comes in the canvas page url.
b. when i am accessing the user profile the profile does not ask for permission to post on his profile even though i have given permissions .
i am not able to get the likes and post comments to work.kindly update if there is any problem in code.
do we need to get access tokens in this case or the code is proper.
thanks

Facebook PHP SDK: getAccessToken not correct on refresh

On my facebook app, I'm logging a user in using the Javascript SDK.
If OK, I redirect him to this PHP page (designed to illustrate my problem):
test.php:
<?php
include('config.php');
require('phpsdk.php');
$access_token = $facebook->getAccessToken();
echo $access_token;
echo "<br /><br />";
$user = $facebook->getUser();
echo $user;
?>
(phpsdk.php handels the PHP SDK initiation)
Accessing test.php the FIRST time, returns a valid access token and the ID of the logged user.
However, when I refresh the page, the access token becomes of the type appID|appSecret.
The user is still logged in: getUser still returns the correct user ID.
Anyone knows what's causing this?
Clearing the Facebook Session with php sdk in redirect when user logs out.
Logout.php redirect user and use sdk to clear session data.
example redirect url. yourdomain.com/Logout.php?destroy=true
refer to: https://developers.facebook.com/docs/reference/php/facebook-destroySession/
<?php
session_start();
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => 'appID',
'secret' => 'appSecret',
'cookie' => true, // enable optional cookie support
));
if(isset($_GET['destroy'])){
$facebook->destroySession();
}
?>
It is not recommended to call getAccessToken(); over and over the way you described.
You should try first to see if the token is in the browser as a session and if not then try to use the SDK to find or request it.
Check browser for a user, if no user call sdk for user, if still null or 0 auth or reauth.
If user, check browser for access_token, if no token call sdk for token.
<?php
session_start();
include('config.php');
require('phpsdk.php');
// need to replace Your_App_ID and YourAppId with your applications id.
$facebook = new Facebook(array(
'appId' => 'Your_App_ID',
'secret' => 'Your_App_Secret',
'cookie' => true, // enable optional cookie support
));
if(isset($_SESSION['fb_YourAppId_user_id'])){
$user = $_SESSION['fb_YourAppId_user_id'];
}else{
$user = $facebook->getUser();
}
if($user){
if(isset($_SESSION['fb_YourAppId_access_token'])){
$access_token = $_SESSION['fb_YourAppId_access_token'];
}else{
$access_token = $facebook->getAccessToken();
}
}
echo $user;
echo "<br /><br />";
echo $access_token;
?>

Facebook Canvas App Login for new Users

i have created a facebook app and it works well for new users if they start the app with the direct server link (https://www.mydomain.com/app/index.php) and use the login button.
But if they try to use the app within facebook (https://apps.facebook.com/myapp) as a canvas app(for the first time) then they see the "landing" page of my app and the log in button. But if they click on it, an errormessage appears, that the content of the iframe couldn't be displayed. If they start the app in a new tab, then the login process works. (see the error below, sorry it's german, maybe you are familiar with this type of error message?)
It would be desirable if the new user could use the login link in the canvas app.
How can this be achieved? My index.php looks like this: (i am using the facebook SDK)
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'YOUR_APP_ID',
'secret' => 'YOUR_APP_SECRET',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
<html>
<head></head>
<body>
<?php
if($user_id) {
try {
$user_profile = $facebook->api('/me','GET');
echo "Name: " . $user_profile['name'];
} catch(FacebookApiException $e) {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
$login_url = $facebook->getLoginUrl();
echo 'Please login.';
}
?>
</body>
</html>

Get facebook user id

I have searched the web high and low and can´t figure out the problem I´m facing. I have a page tab application on Facebook, the user likes the page to start and then he can answer some questions, I can get the facebook connect to function but I can not get the user id and save it to the database.
I have this in my index page
<? include('db.php');
include_once("config.php");
// Finnur út hvaða spurninga sett á að nota
$sp_set = 1;
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook( array('appId' => '289393321124676',
'secret' => 'd47b7871e0a7fb475db6e2a643f675ed', 'cookie' => true, ));
$signed_request = $facebook -> getSignedRequest();
$like_status = $signed_request["page"]["liked"];
$user = $facebook->getUser();
//If the page is liked then display full app.
?>
And the user id is always null, when the user submits the questions everything is saved to the database but user is 0.
Please help
$user = $facebook->getUser();
This will not get you any user id, unless the user has connected to your app first.
So you have to implement either the client-side or the server-side Auth flow in your app. https://developers.facebook.com/docs/authentication/pagetab/
Try this example:
<?php
$secret = '********************************'; // App Secret
$app_id = '***************'; // App ID
$page_url = 'https://www.facebook.com/*******'; // FB fan page URL, where the application tab is installed
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $secret,
));
// Get User ID
$user = $facebook->getUser();
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;
}
}
// Login url will be needed depending on current user state.
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array('redirect_uri' => $page_url.'?sk=app_'.$app_id));
}
$signed_request = $facebook->getSignedRequest();
?><!DOCTYPE html>
<html>
<body><pre>
<?php
if (!$user): // isn't authorized
echo 'Authorize app';
else:
if ($signed_request['page']['liked']): // likes
echo 'The page is liked by user with id '.$signed_request['user_id'];
else:
echo 'The page is <strong>NOT</strong> liked by user with id '.$signed_request['user_id'];
endif;
endif;
?>
</pre></body>
</html>
I was having a similar issue. I ended up using the FB JS-SDK to invoke the oAuth dialog to allow the user to connect to my app and grant me permissions. At that point you can access their user id and whatever other info they're granted you permission for.
Add the following code to your window.fbAsyncInit call:
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
});
Source: https://developers.facebook.com/docs/reference/javascript/FB.login/

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.