PHP & Javascript Asynchronous permissions Authentication - Facebook API's - javascript

What would I need to do to allow asynchronous login/authentication (permissions) between an external site for mobiles and a facebook tab app.
I essentially need one system that does both desktop/mobile.
Example
Case 1 (Mobile/external access) - Logs in using Javascript using login and works fine app works perfectly. - This works the way it's supposed to which is great!
case 2(Facebook user - tab app) - Logs in and gains permissions through PHP SDK onviously the user is already logged in. My problem is javascript knows the user is logged in but still asks the user to login for the permissions they've already given.
TLDR: Why won't Javascript pickup the Auth cookie from the PHP SDK and recognise the user has the correct permissions from PHP? This login flow is fine when the user has logged in via mobile or externally to the app. I've tried them seperately and they work fine just won't work together.
I've seen it working the other way around but I want JS only or PHP>JS NOT JS>PHP.
*Edit
window.fbAsyncInit = function()
{
FB.init({
appId : 'APP_ID_HERE', // App ID
channelUrl : 'channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
oauth : true // enable OAuth 2.0
});
my event handlers for login/logout and likes goes here.
(function(d)
{
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id))
{
return;
}
js = d.createElement('script');
js.id = id;
js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}
(document));
function fblogin()
{
FB.login(function(response)
{
},
{ scope: 'email, user_likes' }
);
}
function createRequestObject() {
var obj;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
obj = new XMLHttpRequest();
}
return obj;
}
Login for mobile/desktop works great it's picking up the scope but when I use the following code to setup the tab app, the permissions won't transfer to the javascript session.
PHP Code (which works):
<?php
require_once 'src/facebook.php'; // get facebook sdk
$facebook = new Facebook(array(
'appId' => 'APP ID HERE',
'secret' => 'APP SECRET HERE'
));
$user = $facebook->getUser();
$location = "". $facebook->getLoginUrl(array('scope' => 'email, user_likes'));
// check if we have valid user
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$permissions = $facebook->api('/me/permissions', 'get', array('access_token'=>$access_token));
} catch (FacebookApiException $e) {
$fb_user_id = NULL;
// seems we don't have enough permissions
// we use javascript to redirect user instead of header() due to Facebook bug
print '<script language="javascript" type="text/javascript"> top.location.href="' . $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
echo $e->getMessage();
die();
}
} else {
// seems our user hasn't logged in, redirect user to a FB login page
print '<script language="javascript" type="text/javascript"> top.location.href="'. $location .'"; </script>';
// kill the code so nothing else will happen before user gives us permissions
die();
}
// at this point we have an logged in user who has given permissions to our APP
// Facebook opens canvas page (which is the mobile/external page) but doesn't transfer permissions.
PHP works great it transfers the user to the mobile (canvas) page with login/like button. How do I get PHP to pass the perms to my canvas where my mobile/desktop site is?
*EDIT 2:
HTML/PHP:
<div class="container">
<div id="fb-root"></div>
<div id="facebook-div">
<fb:login-button autologoutlink="true" scope="email,user_likes" size="large"></fb:login-button>
<div id="facebook-right" class="fb-like" data-href="https://www.facebook.com/154456204613952" data-width="90" data-layout="button_count" data-show-faces="false" data-send="false"></div>
</div>
//Rest of the code here

Managed to resolve it thanks for your help!
After the PHP instantiated I didn't include the Canvas php file after the user was authenticated... I've been pulling my hair out for months trying to resolve this! This authentication gets passed to Javascript which deals with everything!
This means that both PHP and Javascript calls are able to work within the same application.

Related

How to use Facebook test app to do Facebook Login - Web JavaScript

This is my first time to write JavaScript.... I am using JSBin as the IDE. And I am trying to use JavaScript to allow users login and get their public data in Facebook Graph API.
I created a Facebook Web App, and then created a Test App for this App. None of these 2 Apps work. For each of these Apps, I have created a test user like this:
Below Are How I Failed....
First Try:
I have checked this Facebook Login Doc, changed the app id to my own app id, and version changed to 2.6 as my app settings. But, the problem is, on JSBin, nothing show up.....
Second Try:
Then I found an online example, and I modified the code to make it like this
<html>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '1814637902090044',
cookie : true,
xfbml : true, // parse social plugins on this page
version : 'v2.6' // use graph api version 2.6
});
FB.Event.subscribe('auth.authResponseChange', function(response)
{
if (response.status === 'connected')
{
document.getElementById("message").innerHTML += "<br>Connected to Facebook";
}
else if (response.status === 'not_authorized')
{
document.getElementById("message").innerHTML += "<br>Failed to Connect";
} else
{
document.getElementById("message").innerHTML += "<br>Logged Out";
}
});
};
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
} else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope: 'email'});
}
function getUserInfo() {
FB.api('/100012237662406', function(response) {
var str = "<b>Email:</b> "+response.email+"<br>";
document.getElementById("status").innerHTML=str;
});
}
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<div align="center">
<h2>Facebook OAuth Javascript Demo</h2>
<div id="status">
Click on Below Image to start the demo: <br/>
<img src="http://hayageek.com/examples/oauth/facebook/oauth- javascript/LoginWithFacebook.png" style="cursor:pointer;" onclick="Login()"/>
</div><div id="message">Logs:<br/>
</div></div>
</body>
As you can see, I am using the app id of my Test App, the user is my test user id, but when I click the button, always get this error
Third Try:
Since above error shows "app in development mode....", I have checked these 2 solutions: Solution 1, Solution 2. But I really cannot find those choices in App Review and I cannot find Status & Review. When it comes to Test App, it even has no App Review. Then I tried to public my App like this
But then I got the error:
Here are the url settings:
For that Redirect URL, I have also tried http://localhost/oauthcallback.html, but didn't work either. I don't have any real url can be used for redirect....
I think, if Test App without App Review can be used to test Facebook Login, it may not be the settings in App Review problems.
Do you know how to solve this problem, so that my Javascript will allow user login and send me their public data in Graph API?

Facebook JavaScript API - Login failure in Chrome

The below code is from the official Facebook developer pages, and works in FF and Safari, and sometimes in Chrome — but more often not in Chrome.
On Snow Leopard with the latest Chrome, I click the login button and see a little flicker as the FB login dialog opens and closes. If, in my FB account, I remove and re-add the app, I get asked for permissions, but the auth.authResponseChange event never seems to fire.
Does anyone know if this is a bug, or where I might find a solution that doesn't require me to manually poll the server?
Is this a product of Google+ vs. Facebook?!
<html>
<head></head>
<body>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : $APP_ID$, // App ID from the app dashboard
channelUrl : $channelUrl$, // Channel file for x-domain comms
status : true, // Check Facebook Login status
cookie : true,
oauth : true,
xfbml : true // Look for social plugins on the page
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
console.log('auth.authResponseChange fired');
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
</script>
<!--
Below we include the Login Button social plugin. This button uses the JavaScript SDK to
present a graphical Login button that triggers the FB.login() function when clicked.
Learn more about options for the login button plugin:
/docs/reference/plugins/login/ -->
<!-- scope='publish_stream,read_stream' -->
<fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>
</body>
</html>
Go into chrome settings - advanced settings; Under privacy click "content settings". See if the "Block 3rd party cookies and site data" is checked.
I'm having a similar issue where in chrome the js-sdk will give me the momentary fb popup, but doesnt actually seem to log the user in or recognize the user being logged in/authorized. In my case I think I've narrowed my issue down to that setting.
If you have it enabled, try disabling it to see if that fixes it for you... although that's really just a diagnostic step, it's not a resolution since you would still have users who have that setting enabled.
I'm trying to determine the workaround if any.. possibly involving the use of fb login flow "for web" (ie not using their sdk and thereby potentially avoiding the use of 3rd-party cookies)
here's my post on my version of this issue... can facebook javascript/php SDK's "talk" to each other if 3rd-party cookies are disabled? facebook->getUser() returns 0

FB.login url serves a blank page when there is no facebook cookie set on mobile browsers

Something starange is happening when trying to login to facebook with the javascript SDK on mobile Safari and Android browser. When I clear both my 'history' and my 'cookies and data' and try to login to Facebook using the FB.login method, Safari and Android browser open a new tab with the auth url but stays blank. In all the desktop browsers, everything works just fine.
The strange thing is, is that when I clear my 'history' and my 'cookies and data', then visit facebook.com (not logging in or anything), close the site, open my site and then try to login to FB, it actually works like it should!
So this seems like facebook.com sets a cookie which causes the authentication URL to succesfully load.
I have looked all over for a solution for this problem but couldn't find anything and thus my first stackoverflow post...
Just to be complete, this is the code I use to init the FB SDK:
window.isFacebookSDKLoaded = false;
window.onFacebookSDKLoaded = function () {}; //is injected with a function from another js app on the site
window.fbAsyncInit = function() {
FB.init({
appId : '{{ appID }}', // App ID
channelUrl : '{{ baseUrl }}channel.php', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
window.isFacebookSDKLoaded = true;
window.onFacebookSDKLoaded();
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
Someplace else in my app I just simply do:
(using google closure)
mm.controller.facebook.DoFBLogin.prototype.doLogin = function ()
{
FB.login( goog.bind( this.loginResult, this ), { scope: app.Config.getFBPermissions() } );
}
mm.controller.facebook.DoFBLogin.prototype.loginResult = function ( result )
{
// logged in
};
If someone has a solution... Thanks in advance!

facebook and twitter iframes requesting access set 'document.domain' error

I'm putting Tweet and Facebook Like buttons on the project im working. Everything seems to be working but when click the btns I get this JS error:
Unsafe JavaScript attempt to access frame with URL http://platform.twitter.com/widgets/tweet_button.1357735024.html#_=1357834238249&count=none&id=twitter-widget-0&lang=en&original_referer=http%3A%2F%2Fwww.sandals.com%2Fmain%2Fnegril%2Fne-home.cfm&size=m&text=Negril%2C%20Jamaica%20All%20Inclusive%20Vacation%20-%20Sandals%20Negril%20Beach%20Resort%20%26%20Spa&url=http%3A%2F%2Fwww.sandals.com%2Fmain%2Fnegril%2Fne-home.cfm&via=SandalsResorts from frame with URL http://www.facebook.com/plugins/like.php?locale=en_US&app_id=150389325070106&href=www.sandals.com/main/negril/ne-home.cfm&send=false&layout=button_count&width=60&show_faces=false&action=like&colorscheme=light&font&height=21. The frame requesting access set 'document.domain' to 'facebook.com', the frame being accessed set it to 'twitter.com'. Both must set 'document.domain' to the same value to allow access.
this is the code im using for fb and twitter
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '150389325070106', // App ID from the App Dashboard
channelUrl : '//www.sandals.com', // Channel File for x-domain communication
status : false, // check the login status upon init?
cookie : true, // set sessions cookies to allow your server to access the session?
xfbml : true, // parse XFBML tags on this page?
frictionlessRequests: true
});
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK's source Asynchronously
(function(d, debug){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all" + (debug ? "/debug" : "") + ".js";
ref.parentNode.insertBefore(js, ref);
}(document, /*debug*/ false));
// Twitter Btn JS
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
i followed the steps in fb dev site but still get those errors :S
As you can read in the linked answer, this is an issue with Twitter's API. Alternatively to the answer on the linked question, I created a custom tweet button that looks exactly like the one of Twitter's JS API but doesn't use it and still includes the share count. Feel free to use it.
Demo: http://fiddle.jshell.net/eyecatchup/Th6P2/2/show/
Code: https://github.com/eyecatchup/tweetbutton

API Key Error in Facebook Connect (javascript sdk)

I am trying to implement Facebook Connect on a website. I am trying to work with Javascript SDK of Facebok. I am new to it and unfortunately most of links provided in Facebook WIKI are out of date... Returning 404 not found. Anyway I added this code before the ending </body>:
<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
<div id="fb-root"></div>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId : '12344', // my real app id is here
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : false // parse XFBML
});
FB.login(function(response) {
if (response.session) {
if (response.perms) {
alert('user is logged in and granted some permissions');
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
} else {
alert('user is logged in, but did not grant any permissions');
// user is logged in, but did not grant any permissions
}
} else {
alert('user is not logged in');
// user is not logged in
}
}, {perms:'email'});
</script>
And I have a login button at some other place (much before the above scripts) in the same page rendered with:
<fb:login-button v="2">Connect with Facebook</fb:login-button>
This button renders as a normal fb connect button and clicking it opens a new popup window as it normally should. Problem is that it shows 'invalid api key specified' error. On inspecting address bar of popup, I see that api_key=undefined is passed to it :(
Any idea about this? I am trying to fix this for last 5 hours now... Please help me found out why correct API key is not being passed to popup window.
Thanks in advance.
I'm doing the same thing, and i found an example that is very simple to implement and understand (here thay use jQuery, but you can do the same without libraries):
<body>
<div>
<button id="login">Login</button>
<button id="disconnect">Disconnect</button>
</div>
<div id="user-info" style="display: none;"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
// initialize the library with the API key
FB.init({ appId : '12344' });
// fetch the status on load
FB.getLoginStatus(handleSessionResponse);
$('#login').bind('click', function() {
FB.login(handleSessionResponse);
});
$('#disconnect').bind('click', function() {
FB.api({ method: 'Auth.revokeAuthorization' }, function(response) {
clearDisplay();
});
});
// no user, clear display
function clearDisplay() {
$('#user-info').hide('fast');
}
// handle a session response from any of the auth related calls
function handleSessionResponse(response) {
// if we dont have a session, just hide the user info
if (!response.session) {
clearDisplay();
return;
}
// if we have a session, query for the user's profile picture and name
FB.api(
{
method: 'fql.query',
query: 'SELECT name, pic FROM profile WHERE id=' + FB.getSession().uid
},
function(response) {
var user = response[0];
$('#user-info').html('<img src="' + user.pic + '">' + user.name).show('fast');
}
);
}
</script>
</body>
Look here for the entire code, and here you can find other resource.
I had set my facebook connect address to have www and I was accessing my test site with non www, when I switched to the www version fb connect worked fine.
You need to set the canvas post-authorize url, and make sure that the base canvas url is a prefix of the post-authorize url.

Categories

Resources