Problem
I am using below mentioned JS code in my PHP try catch. Basically I am making facebook app. In that when users session gets timed out it shows an error message which doesn't look good but when a user refreshes the page it starts working perfectly. For that reason I used PHP try catch to know whether the session got timed out or not if yes then in catch I run the below JavaScript code. I want to auto refresh the page instead of asking user to do it manually.
The below code refreshes the page but then it keeps refreshing it. I'm new to javascript can you please suggest how should I get out of this condition once it gets true.
Code
try{
$facebook = new Facebook(array(
'appId' => '123456789',
'secret' => 'some_secret',
));
$accessToken = $facebook->getAccessToken();
$facebook->setAccessToken($accessToken);
$user_profile = $facebook->api('/me','GET');
$username= $user_profile['email'];
$fb_id= $user_profile['id'];
}catch(Exception $e){
location.reload(true);
console.log('Session has been timed out');
}
<script type="text/javascript">
if(window.location.hash==-1)
{
//add a # if it doesn't exist
newurl = document.URL+"#";
location = "#";
//Refresh page
location.reload(true);
}
</script>
or try this(will not work if the user has disabled local storage/cookies)
function()
{
if( window.localStorage )
{
if( !localStorage.getItem( 'firstLoad' ) )
{
localStorage[ 'firstLoad' ] = true;
location.reload(true);
}
else
localStorage.removeItem( 'firstLoad' );
}
}
Related
I am having a little trouble authenticating with the below code.
I have a page that produces a loginUrl for the user to login/authenticate my app on Facebook:
<?php
$loginUrl = $facebook->getLoginUrl(array('scope' => 'publish_stream, read_friendlists, user_birthday', 'redirect_uri' => 'complete.php'));
?>
<div id="connect_facebook">
<a class="button" href="<?php echo $loginUrl; ?>">Connect to Facebook</a>
</div>
And my complete.php has a script that does the following:
<script>
$(document).ready(function() {
pop_db();
});
function pop_db() {
$.post(
"pop_db.php",
function(data) {
alert(data);
}
);
}
</script>
And my pop_db.php file looks like:
<?php
require_once('constants.php');
$response = array();
$user = $facebook->getUser();
if($user) {
try {
// make API calls
$response['code'] = "success";
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
} else {
$response['code'] = "failure";
$response['userID'] = $facebook->getUser();
$response['access_token'] = $facebook->getAccessToken();
}
echo json_encode($response);
?>
And constants.php has my secret info for the Facebook object (and it also creates the $facebook object).
My issue is that when I do this using "complete.php" as the redirect and try to do the API calls async using this jQuery, I get back a response that userID = 0 (meaning the user isn't logged in) but it seems like I get a valid access token. When I use "pop_db.php" as my redirect instead of "complete.php" and therefore don't use any async calls, everything works fine.
Am I missing something? Why does it keep telling me the user isn't logged in?
Any suggestions are much appreciated.
Who are getting problem to login their own website thorough facebook / integrate facebook login to their website just follow the given link "http://developers.facebook.com/docs/howtos/login/server-side-login/#step2".It is a very nice link which can solve your problem definitely.
Thanks.
banalata.
"
NOTE: This is a facebook app which runs at page tab.
i have data.php file which gets all thing.
i get signed request with this following code:
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => false
));
$access_token = $facebook->getAccessToken();
$signedRequest = $facebook->getSignedRequest();
$user_id = $signedRequest['user_id'];
$liked = $signedRequest['page']['liked'];
In my index file i have some include action for fan or not fan and step php files.
Here is my index code:
require_once ('data.php');
if(isset($fid)){
if(isset($liked)){
$step = CHECK_STEP($fid);
if(isset($step)){
if($step == '1'){
include('fan-step1.php');
}
if($step == '2'){
include('fan-step2.php');
}
if($step == '3'){
include('fan-step3.php');
}
if($step == '4'){
include('fan-step4.php');
}
} else {
include('fan.php');
}
} else {
include('notfan.php');
}
} else {
if(isset($liked)){
include('fan.php');
} else {
include('notfan.php');
}
}
i'm using ajax in step php files to update database for step check. if ajax action complete, action reflesh the page. Code:
success: function(){
window.location = window.location.pathname;
}
after refreshing the page index file or data file cant get the page liked request. then if i refresh the page manual (ctrl+F5). It get the request and include next step php file.
What is wrong? why it cant get the liked request after js refresh?
With your redirection, you refresh your iframe. The signed request of facebook however, is sent via POST to your iframe. So if you just refresh your iframe, the signed request will not be sent again, since the second request (after the refresh), the request is not performed by facebook, but from within your application.
Reload the complete page (facebook + your tab) instead, using top.location.
I use Facebook PHP SDK 3.0.1 (latest currently).
What I need to be able to do is to post as a the identity of the Page on the Page.
I tried replacing the access_token with the access_token I get from the page (/me/accounts) however it now says token is invalid for some reason.
Facebook "impersonation" pages are offline now, and I don't see any info in the API regarding doing what I want.. maybe I'm lost or maybe not looking in the right direction..
Here's the example.php that I modified and use to archive this:
require '../src/facebook.php';
// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
'appId' => 'xxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxx'
));
// Get User ID
$user = $facebook->getUser();
//Lists all the applications and pages
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$accounts_list = $facebook->api('/me/accounts');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
$page_selected = 'xxxxxxxxxxxx';
$page_access_token = $accounts_list['data']['0']['access_token'];
echo 'page_access_token:' . $page_access_token;
<?php
if (isset($_GET['publish'])){
try {
$publishStream = $facebook->api("/$page_selected/feed", 'post', array(
'access_token' => '$page_access_token',
'message' => 'Development Test message',
'link' => 'http://xxxxxxx.com',
'picture' => 'http://xxxxxx/xxxx_logo.gif',
'name' => 'xxxxxxxx Goes Here',
'description'=> 'And the exciting description here!'
)
);
//as $_GET['publish'] is set so remove it by redirecting user to the base url
} catch (FacebookApiException $e) {
echo($e);
echo $publishStream;
echo 'catch goes here';
}
}
?>
Since I can't answer my own question I edited the question.
Went through the whole API..
Solution:
Before posting as the page you need to set your access_token to the one page owns.
$facebook->setAccessToken($page_access_token);
does just that, and afterwards everything goes as it normally would be expected, no need to modify post function and add "access_token" option to post.
1.First you have to get the page access token.
public function getPageToken()
{
$page_id = "xxxxxxxxxx";
$page_access_token = "";
$result = $this->facebook->api("/me/accounts");
if( !empty($result['data']) )
{
foreach($result["data"] as $page)
{
if($page["id"] == $page_id)
{
$page_access_token = $page["access_token"];
break;
}
}
}
else
{
$url = "https://www.facebook.com/dialog/oauth?client_id=xxxxxxxxxx&redirect_uri=http://apps.facebook.com/xxxxxx&scope=manage_pages&response_type=token";
echo "<script type='text/javascript'> top.location.href='".$url."'; </script>";
}
return $page_access_token;
}
2.After getting the page access token just include that token in your post to wall code.
<script src="//connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
var token = '<?php echo $page_access_token ?>';
var wallPost = {
access_token: token,
message : 'xxxxxxxx',
link : 'http://apps.facebook.com/xxxxxxx/',
picture : 'xxxxxxxx',
name : 'xxxxx',
caption : 'xxxxxx',
description : 'xxxxxxx',
};
FB.api('/pageid/feed', 'post', wallPost, function(response) {
if (!response || response.error) {
} else {
}
});
</script>
3.Remember this code will only publish your post on Fan page's wall and users who liked the fan page will be able to see that post as the post is posted on their own feed.
Hope this will solve your problem.
I've set up a Canvas Page which doe's a FB.login on click of a form submit button. During the following request it tries to access the users data via $facebook->api('/me') (last API version from Github). It works in Firefox and Chrome, but not in Safari and IE, where the API fails with "auth token required". Has anybody already had this problem or got an idea what could cause it?
BR Philipp
edit:
I call FB.login inside the click event of a form submit button:
$('.form-submit', this).click(function() {
FB.getLoginStatus(function(response) {
if (response.session) {
form.submit();
} else {
FB.login(function(response) {
if(response.session && (permissions == '' || response.perms)) {
form.submit();
}
else {
}
},{perms:permissions});
}
});
return false;
});
On server side in simply construct the php-api object and try to get user data:
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
if ($facebook) {
try {
$me = $api->api('/me');
}
catch (Exception $exc) {
// Failure in Safari and IE due to invalid auth token
}
}
The signed_request is passed inside a hidden form element.
I had the same problem and I've included a solution below.
I believe the reason this happens is because on a Javascript login attempt your server never receives any access tokens. The Javascript is only passing data between your browser and Facebook.com so your server has no idea what the authentication status is. Your server will only receive the new access tokens when the page is refreshed; this is where facebook hands over the access tokens.
Heres my solution.
Upon a successful login via FB.login you will receive the response object and inside it is an access_token. All you need to do is pass this access token to your script in some way. Here is an example:
// Hold the access token
var js_access_token = "";
// Connect to facebook
FB.login(function(response) {
if (response.session) {
if (response.perms) {
// user is logged in and granted some permissions.
// Save the access token
js_access_token = response.session.access_token;
// Do stuff on login
}
}
});
You then include the access token along with any requests. I've chosen an ajax example.
// Communication back to server.
$.ajax({
url: 'myurl.php',
data: {
js_access_token: js_access_token // Including the js_access_token
},
success: function(data) {
console.log(data);
}
});
Within your PHP you then need to have something which looks like this:
$facebook = new Facebook(array(
'appId' => $appid,
'secret' => $appsecret,
'cookie' => TRUE,
));
if ($facebook) {
// If we get the access token from javascript use it instead
if (isset($_REQUEST['js_access_token']) && $_REQUEST['js_access_token']) {
$facebook->setAccessToken($_REQUEST['js_access_token']);
}
try {
$me = $api->api('/me');
}
catch (Exception $exc) {
// Failure in Safari and IE due to invalid auth token
}
}
Hope this helps
I had a lot of troubles with the JS FB login stuff. I recommend using the simpler redirect login using oauth and the getLoginUrl function from php fb api.
So basically you do it from PHP, you check if you have your session, if not you use getLoginUrl and redirect to that page, your use will be then redirected to your app/site with a valid session (if he accepts).
Does this help ? I really lost HOURS trying to make the FB JS login work on any browser and I couldn't, I've switched since then to the simple redirect login method in all of my apps with complete success.
I liked Conor's answer as I had to pass my access token from the client side to server side as it was not working in Safari (cookie issues I presume). But this is an old question so a few things had to change. The vars are different now and as oliland pointed out we shouldn't be sending access tokens as GET params.
Anyway, here's what I ended up with in case it helps anyone
<a id="start-button" href="#">Start</a>
<form id="entry-form" action="nextpageurl" method="post">
<input type="hidden" name="access_token" />
</form>
<script>
$(document).ready(function() {
$('#start-button').click(function(e) {
e.preventDefault();
FB.login(function (response) {
if (response.authResponse) {
$('#entry-form input').val(response.authResponse.accessToken);
$('#entry-form').submit();
} else {
alert('Permissions required');
}
}, {});
});
});
</script>
and then in the PHP, pretty much same as Conor's answer, but getting the token from the $_POST var.
I created a facebook application and send request to a user through below code.Now when a user allow my application then i need his id and email address into my canvas url.But on that below code user don't go to my canvas URL.So,Please help me to solve ,how a user go to my canvas url when he allow my application and i get the user id of that user?My code is below:
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '#######',
'secret' => '###################',
'cookie' => true, ));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=>1,'fbconnect' => 0,'req_perms'=>$req_perms));
$me = null;
if (!$session)
{ echo "top.location.href= '$loginUrl';";exit;}
else{
try {
$uid = $facebook->getUser();
$me = $facebook->api('/me');
}
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href= '$loginUrl';</script>"; exit;}
}
So,please help me to get the user id.
Thanks in advance
riad
The Facebook ID & email for the current user can be accessed through:
$me['id'];
$me['email'];
Is that what you're after?
First of all, your code is "badly" written. The catch block in your code "when executed" does not mean that the user is not logged in. It means that something went wrong in your try block (a.k.a bad Facebook Call).
Now for your question, you just need to place this in your try block:
$data = $facebook->api('/me?fields=id,email');
IMPORTANT NOTE:
You may not get the user real email, the user may choose to not share it with you and this way Facebook will create a "mirror" email to share with your App.
I am not familiar with php to comment on the code above. However in general it would be better to use javascript sdk for login alone (faced the same issue in asp.net). That way post user login, the control comes back to the same page where it was initiated. For example:
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId: <app_id>, cookie: true, status: true, xfbml: true
});
function fblogin() {
FB.login(function (response) {
//Control comes back here
if (response.session) {
alert(response.session.access_token);
var url = '/me?fields=name,email';
FB.api(url, function (response) {
//You are now in the same page with the data you wanted. If necessary redirect.
alert(response.name);
alert(response.email);
});
}
else {
alert("User did not login successfully");
}
}, { perms: 'email' });
}
</script>
<img src="../Images/social_facebook.png" />
At last i solve my problem and now i can easily get the facebook user id and email address and other related information.Using this code i can hit to facebook for particular user's authentication and when user accept my application then i can get his/her facebook user id, email and other information into $user_info array.Hope it will help you.
Just see my code below:
<?php
require_once 'facebook.php';
$facebook = new Facebook(array(
'appId' => '########',
'secret' => '##########################',
'cookie' => true,
));
$req_perms = "publish_stream,offline_access,user_status,email,read_stream";
$session = $facebook->getSession();
$loginUrl = $facebook->getLoginUrl(array('canvas'=> 1,'fbconnect' => 0,'req_perms' => $req_perms));
$user_info = null;
if (!$session)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>";exit;}
else{
try { $user_info = $facebook->api('/me'); }
catch (FacebookApiException $e)
{ echo "<script type='text/javascript'>top.location.href = '$loginUrl';</script>"; exit;}
}
?>
<!doctype html>
<html>
<head>
</head>
<body>
<?php
$user_name=$user_info['name'];
echo "Hi $user_name ! Your Facebook ID is: ".$user_info['id']."<br/>";
echo "Hi $user_name ! Your E-mail Address is: ".$user_info['email']."<br/>";
echo "Thanks for accepting our application.";
//print_r($user_info);
?>
</body>
</html>