How can I stop my site from being shown within Facebook? - php

I'm using Facebook to manage the login for my website. I also use the PHP SDK to call the Graph API to retrieve friend lists, comments, posts etc.
The problem I'm having is that I want the site to be standalone, so that the user follows a link from Facebook and then comes to the site.
It kind of works, but sometimes when the user follows the link, they see my site's index page in the Facebook canvas area. I haven't fully managed to reproduce this, so haven't nailed down the circumstances in which it happens. however, when it happens, if I click 'Back' in the browser, I get taken back to my own site.
It looks like the link takes the user from Facebook to my site, which then calls Facebook to check that the user is logged in, but then it doesn't return to my site for some reason. but as I say, I'm not sure.
Anyway, anyone have any ideas what the problem might be?
My login code is:
// Create new Facebook object
$facebook = new Facebook(array(
'appId' => APP_ID,
'secret' => APP_SECRET,
'cookie' => true, // enable optional cookie support
));
// Create login url, in case user is not logged in or session has expired
$loginUrl = $facebook->getLoginUrl($params = array('canvas' => 0, 'fbconnect' => 0, 'req_perms' => 'publish_stream', 'cancel_url' => 'http://www.pubfish.com'));
// Get current facebook session
$session = $facebook->getSession();
$me = null;
// Session based API call.
if ($session) { // If session exists, make sure it's still valid
try { // Get session to see whether it's valid
// User is logged in and has authorised application already
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
echo "<script type='text/javascript'>top.location.href = '".$loginUrl."';</script>";
error_log($e);
}
}else { // No session - so ask user to log in
$url=$facebook->getLoginUrl(array('canvas' => 1,'fbconnect' => 0));
echo ('<script type="text/javascript">top.location.href=\''.$url.'\';</script>');
}

Have you tried setting 'next', like this: $params = array('canvas' => 0, 'fbconnect' => 0, 'req_perms' => 'publish_stream', 'cancel_url' => 'http://www.pubfish.com', 'next'=>'http://www.pubfish.com')? If all else fails you can use this to break out of the canvas iframe:
<script>
$(document).ready (function () {
if (window != top) top.location.href = location.href;
});
</script>

Related

Facebook App canvas Page not loading

I keep getting this error when I try to use my app I created for Facebook. When I go the the url for the app it take me to the login page, but when I log in I get a pop up box with the error.
App Not Setup: The developers of this app have not set up this app
properly for Facebook Login.
Every time I click ok it just reloads the popup again.
I have already changes the satatus to Live under status and review in my dashboard.
When I log into my account on facebook, it works fine, but I suppose this is because I am set as an admin for the app on the dashboard.
But other users get the problem above.
The code used:
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
redirect($login_url, 'refresh');
}
This code is in my controller of my codeigniter application which I built the app.
How do I fix this?
UPDATE:
After I added the app as a canvas app this error seemed to go away, however there is still a problem.
I added the Facebook app platform and entered the canvas url, secure canvas url etc.
When I go to the app at the canvas page https://apps.facebook.com/MyApp/ - it work fine as I am a app administrator I guess.
However when an external user goes to the canvas page it just remain blank, but if a user goes to the canvas url http://apps.mydomain.com/MyAPP the app asks for their permissions and works fine as a website.
It just remains blank to users on the canvas page. Why doesn't the canvas page ask for permission?
Help Please.
EDIT:
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
require_once('facebook-php-sdk/src/facebook.php');
$facebook= new Facebook(array(
'appId' => $this->config->item('app_id'),
'secret' => $this->config->item('app_secret'),
'allowSignedRequest' => true,
));
$_REQUEST += $_GET;
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me?fields=picture.width(100).height(100),first_name,last_name,username,email');
} catch (FacebookApiException $e) {
$user = null;
}
} else {
$login_url = $facebook->getLoginUrl(array(
'scope' => 'email'
));
echo("<script> top.location.href='" . $login_url . "'</script>");
}
Why doesn't the canvas page ask for permission?
Because you are redirecting inside of the iframe, but the FB login dialog does not want to be displayed in (i(frames) – for the obvious reason, that that would lead to a lot of phishing, since users are supposed to see that the page they are entering their login credentials too is actually the real FB site.
So you have to redirect within the top window instance, via JavaScript:
top.location.href = '…';

Login with facebook suddenly stopped working

Suddenly login with facebook in my web application stopped working.
The following is code of my login page for website. i am using facebook php sdk which was working fine till 5 hours back now it stopped.
I am confused and want to know what the hell happen to it as i am not able to solve it since last 5 hours. I have removed my php code connecting to database and query code to make it look simple.
I take only two scopes that is email and publish_stream
output of below code is hello your fb user id is
<?php
require_once 'include/data.php';
//check to see if they're logged in
if(isset($_SESSION['logged_in'])) {
header("Location: index.php");
}
$site_url = "http://example.com/facebook.php";
require_once ('phpsdk/src/facebook.php');
// Create our application instance
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
'allowSignedRequest' => false
));
// 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;
}
}
if($user){
// Get logout URL
$logoutUrl = $facebook->getLogoutUrl(array(
'redirect_uri' => 'http://example.com/logout.php',
));
}else{
// Get login URL
$loginUrl = $facebook->getLoginUrl(array(
'scope' => 'email, publish_stream',
'redirect_uri' => $site_url,
));
}
// checking
if(!$user) {
//echo "<a href='$loginUrl' >Login</a>";
header("Location:$loginUrl");
} else {
// echo "<a href='$logoutUrl' >Logout</a><br />";
$f_name = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['first_name']);
$l_name = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['last_name']);
$fb_email = $user_info['email'];
$fb_uid = $user_info['id'];
echo "hello your fb user id is $fb_uid"; // just sample to check
}
?>
The lifetime of the FB token is valid for just 2 hours. From the FB Docs...
When retrieving a Facebook access token, an expiration time associated
with the access token is also typically returned. If this expiration
time is exceeded, your application will need to obtain a new access
token (which will also have a new expiration time associated with it).
However you can exchange the token and get a new one that has an extended validity say 60 days.. Something like this..
$this->getUrl('graph', '/oauth/access_token'), array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type'=>'fb_exchange_token',
'fb_exchange_token'=>$this->getAccessToken()
)
More information regarding this can be found here

How to obtain Facebook page access_token without logging in or having user interaction

I have been reading the Facebook documentation and I must be missing something, as I just cant understand how to get the access token for a page without actually logging in first. I am trying to create a PHP function using the PHP facebook API so that when I add new stories or tutorials on my site, my site's apps can then automatically post as the page a blurb about them on myy facebook page.
I have this function working but only when I get the access token from the Graph API Explorer, though the access tokens expire in about an hour. I can't seem to figure out how to programatically obtain the access_token for the page and query for a new one each time from within my PHP scripts so they don't expire and do not require user interaction.
function post_to_facebook($title, $message, $link, $picture) {
require '../facebook/src/facebook.php';
$page_token = 'xxx';
$page_id = 'xx';
$facebook = new Facebook(array(
'appId' => '<app_id>',
'secret' => '<app_secret>',
'cookie' => false,
));
$facebook->setAccessToken($page_token);
try {
$ret_obj = $facebook->api('/'.$page_id.'/feed', 'POST', array(
'caption' => $title,
'link' => $link,
'message' => $message,
'picture' => $picture
));
} catch(FacebookApiException $e) {
error_log($e->getType());
error_log($e->getMessage());
return false;
}
return true;
}
Can someone explain how I can go about retrieving the access token without manually having to look it up via graph api explorer or having a user login?
It's not possible.
The only correct (and legal) way to achieve the access token is with user interaction (through login process).

PHP loop issues with facebook app auth

I am using the latest PHP-SDK(3.11) and i have issues when users come on my app for the first time. The application make infinite loops.
When the user have to give permissions to the application, he is redirected to :
https://www.facebook.com/connect/uiserver.php?app_id=**myappId**&method=permissions.request&display=page&next=http%3A%2F%2Fapps.facebook.com%2F**myApp**%2F&response_type=code&state=**theSate**&canvas=1&perms=user_birthday%2Cuser_location%2Cuser_work_history%2Cuser_about_me%2Cuser_hometown
and when he accept i have the following link returned :
http://apps.facebook.com/**myApp**/?error_reason=user_denied&error=access_denied&error_description=***The+user+denied+your+request.***&state=**theSate**#_
i don't understand why the access is denied when the user click on "allow".
if ($this->fbUser) {
.... Do Somthing
} else {
$this->loginUrl = $this->fb->facebook->getLoginUrl(array(
'scope' => implode(',', sfConfig::get('app_facebook_perms')
), 'next' => 'http://apps.facebook.com'. sfConfig::get('app_facebook_app_url')));
$this->logMessage($this->loginUrl, 'info');
sfConfig::set('sf_escaping_strategy', false);
}
<script type='text/javascript'>
top.location.href = "echo $this->loginUrl ";
</script>
Try something like this, since you need to store the access token, one way or another. Hard to know what you are doing (or not doing) from that snippet.
<?php
# We require the library
require("facebook.php");
# Creating the facebook object
$facebook = new Facebook(array(
'appId' => 'APP_ID_HERE',
'secret' => 'APP_SECRET_HERE',
'cookie' => true
));
# Let's see if we have an active session
$session = $facebook->getUser();
if(empty($session)) {
# There's no active session, let's generate one
$url = $facebook->getLoginUrl(array(
"response_type"=>"token", //Can also be "code" if you need to
"scope" => 'email,user_birthday,status_update,publish_stream,user_photos,user_videos' ,
"redirect_uri"=> "http://test.com" //Your app callback url
));
header("Location: $url");
exit;
}
// user is logged in

Facebook PHP SDK - require login on specific account

I'm tired of digging through tons of tutorials/documentations which don't help me at all.
What I have now (everything is placed inside admin control panel):
If user is logged on correct account (administrator of page with granted rights), everything works fine, post on page is posted as impersonated site.
If he is logged on other account, nothing happens. Site redirects him to his wall.
If he isn't logged on any account, he's redirected to facebook login - if he logs onto correct account, he returns to acp (it's bad solution, because it'll clear his form)
I want to achieve:
If logged in, everything as it was
Else popup with login to specific (correct) account
At the moment I'm using only PHP, but solution with JS is permitted.
My code:
<?php
/*(...)*/
$facebook = new Facebook(array(
'appId' => $apiid,
'secret' => $secret,
'cookie' => true,
));
$session = $facebook->getSession();
$me = null;
if ($session) {
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
}
if($me) {
//In order to post to the page later on we need to generate an Access Token for that page, to do this we get me-accounts in the following api call
$accounts = $facebook->api('/me/accounts');
//Loop through the array off accounts to find the page with a matching ID to the one we need
foreach($accounts['data'] as $account){
if($account['id'] == PAGEID){
$ACCESS_TOKEN = $account['access_token'];
}
}
}
$message=$data['facebook_text'];
$attachment = array(
'message' => $data['facebook_text'],
'name' => $data['name'],
'description' => '',
'link'=>$someurl,
'access_token' => $ACCESS_TOKEN
);
if($image_url != NULL) $attachment['picture'] = $image_url;
try {
if($facebook->api('/PAGEID/feed', 'post', $attachment))
{
//other stuff
}
} catch (FacebookApiException $e) {
error_log($e);
//other stuff
}
}
else
{
$login_url = $facebook->getLoginUrl();
header("Location: $login_url");
exit;
}
/* (...) */
?>
Solution can't redirect anywhere, because it's inside form, so all data'll be lost.
I'm not really sure I understand what you want to do here, but this is what I use in a similar situation:
$session = $this->get_admin_session_of_page ($page_id);
$session = unserialize ($session);
$facebook->setSession ($session, false);
In the facebook php SDK there is a method to manually set the session, setSession. I save the page admin user session in DB with serialize, with the offline access and manage pages permission. Then when you need some admin privileges for the application you just unserialize it, and then use setSession. The second parameter is set to FALSE, so that this session is not saved in a cookie and logout the current user.
This way it's not important who is logged in, the work is always done as an admin of the page. I think this is safe to use in an automated script, for example to upload a user photo in a page album.
Of course, you must use caution with this if it gets more involved then that, or implement your own security.

Categories