Facebook login on cordova app shows blank white screen - facebook

This problem has been bugging me for a long time and I can't seem to find the solution, all the settings in my Facebook Developer panel are configured correctly, Site URL, App Domain and OAuth URLs.
When I run my app on my iPhone (I have it installed through iTunes) and click the authentication button I am successfully prompted with this screen:
However, after logging in, I am faced with a blank white screen instead of being redirected to my main.html page.
I am using the OpenFB plugin along with Parse and the Facebook Graph API to authenticate and store my users data, here is my login code:
login.html:
$('.facebookLogin').click(function(){
Parse.User.logOut(); // log current user out before logging in
login();
});
function login() {
openFB.login(function(response) {
if(response.status === 'connected') {
console.log('Facebook login succeeded');
Parse.FacebookUtils.logIn("email", { // permission request to use email
success: function(user) {
if (!user.existed()) {
FB.api('/me', function(response) {
var firstName = response.first_name;
var lastName = response.last_name;
var email = response.email;
var user_id = response.id;
user.set("firstName",firstName);
user.set("lastName",lastName);
user.set("email",email);
user.save();
});
window.location.href= "main.html";
}
else {
window.location.href= "main.html";
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
else {
alert('Facebook login failed: ' + response.error);
}
}, {scope: 'email'});
}
oauthcallback.html:
<html>
<body>
<script>
// redirects to main page
window.location.href= "main.html";
</script>
</body>
</html>
Note: I have added main.html, login.html and oauthcallback.html to the Valid OAuth redirect URIs list on my panel.

Check that your site is using SSL with a valid certificate.
There might be an error trying to redirect from a non-secure site to an encrypted site.

Related

How can I give the Facebook App access to the Facebook Page via the API?

As we all know, inside the Facebook for Developers interface, you can add Facebook Pages to a Facebook App as in the picture below and generate the Page Access Token.
I'm trying to do this programmatically via the API requests. Unfortunately, I did not find in the documentation of the request how to do this.
What have I done so far?
I can get the User ID and User Access Token via Facebook Login (Documentation).
I can get the list of Facebook Pages that a person owns. In the response, I have the Page ID and the Page Access Token (Documentation).
I have the Facebook app that is in development mode. That app has App ID and App Secret. With these values, I can get the App Access Token (Documentation).
I can set Webhook to the Facebook App with App ID and App Access Token (Documentation).
I can set the Webhook Subscriptions Fields for my Facebook App (Documentation).
Question: What kind of API request should I use to add a Facebook Page to the Facebook App?
The list of my requests:
I take Page ID and Page Access Token with this GET request cause this request returns the list of Facebook Pages that a person owns:
https://graph.facebook.com/v9.0/{user-id}/accounts?access_token={user-access-token}
I set the Webhook in my Facebook App with this POST request:
https://graph.facebook.com/v9.0/{app-id}/subscriptions?access_token={app-access-token}&callback_url={url-address}&verify_token={verify-token}&object=page&include_values=true
It successfully works and I see this Webhook in the "Webhooks" block of the Dashboard interface.
Then I make this POST request to set Webhook Subscriptions Fields:
https://graph.facebook.com/{page-id}/subscribed_apps?subscribed_fields=messages,messaging_postbacks,messaging_optins,message_deliveries,message_reads,messaging_payments,messaging_pre_checkouts,messaging_checkout_updates,messaging_account_linking,messaging_referrals,message_echoes,messaging_game_plays,standby,messaging_handovers,messaging_policy_enforcement,message_reactions,inbox_labels&access_token={page-access-token}
In this request, I use Page ID and Page Access Token from the first step.
Unfortunately, I have such an error message:
To subscribe to the messages field, one of these permissions is
needed: pages_messaging
I've been following down a similar rabbit hole. Indeed, Facebook documentation is confusing, but it ended up being pretty simple. Here is the modified Facebook Login example, which gets page access token and then adds necessary webhook subscriptions for page messaging. After you've run it, you will see the page is added to the App settings with the requested webhook subscriptions. Hope it helps πŸ€“
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8" />
</head>
<body>
<script>
let page_access_token = null
let page_id = null
function statusChangeCallback(response) {
// Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback')
console.log(response) // The current login status of the person.
if (response.status === 'connected') {
// Logged into your webpage and Facebook.
testAPI()
} else {
// Not logged into your webpage or we are unable to tell.
document.getElementById('status').innerHTML =
'Please log ' + 'into this webpage.'
}
}
function checkLoginState() {
// Called when a person is finished with the Login Button.
FB.getLoginStatus(function (response) {
// See the onlogin handler
statusChangeCallback(response)
})
}
window.fbAsyncInit = function () {
FB.init({
appId: 'YOUR_APP_ID',
cookie: true, // Enable cookies to allow the server to access the session.
xfbml: true, // Parse social plugins on this webpage.
version: 'v12.0', // Use this Graph API version for this call.
})
FB.getLoginStatus(function (response) {
// Called after the JS SDK has been initialized.
statusChangeCallback(response) // Returns the login status.
})
}
// add webhooks to page subscriptions
function addPageSubscriptions() {
FB.api(
`/${page_id}/subscribed_apps`,
'POST',
{
subscribed_fields: [
'messages',
// any other webhook event: https://developers.facebook.com/docs/messenger-platform/webhook/#events
],
access_token: page_access_token,
},
function (response) {
if (response && !response.error) {
console.log({ response })
} else {
console.error(response.error)
}
},
)
}
// pages I have access to
function getPages() {
FB.api('/me/accounts', function (response) {
if (response && !response.error) {
console.log({ response })
page_access_token = response.data[0].access_token
page_id = response.data[0].id
addPageSubscriptions()
} else {
console.error(response.error)
}
})
}
function testAPI() {
// Testing Graph API after login. See statusChangeCallback() for when this call is made.
console.log('Welcome! Fetching your information.... ')
// Me
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name)
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!'
getPages()
})
}
</script>
<!-- The JS SDK Login Button -->
<!-- IMPORTANT: Define the scopes for managing pages metadata and pages_messaging for the webhooks -->
<fb:login-button
scope="public_profile,email,pages_manage_metadata,pages_messaging"
onlogin="checkLoginState();"
>
</fb:login-button>
<div id="status"></div>
<!-- Load the JS SDK asynchronously -->
<script
async
defer
crossorigin="anonymous"
src="https://connect.facebook.net/en_US/sdk.js"
></script>
</body>
</html>

FB.getLoginStatus() needs page refreshed

I am using FB.getLoginStatus() and FB.Login() to log the user into my website using facebook. I first check for the status on page load using FB.getLoginStatus() and save the state in a hidden variable. When the user clicks on my facebook login button, I first check the value in the hidden variable and call FB.Login() only if FB.getLoginStatus() is not connected. If FB.getLoginStatus() returns 'Connected', then I just log the user into my website without FB.Login().
My scenario with issue
*user logs into my accont using facebook
*user logs out of my website
*my website is open in the logged out state
*in another tab, the current facebook user logs out of facebook and a new user logs into facebook
*user comes back to my website and clicks on facebook login button without refreshing the page
*the old facebook user (not the one currently logged into facebook) is logged into my account
How can I identify the most current user in facebook when user clicks the facebook login button?
<body>
<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 your Facebook API key
var AppID = '<%=AppID%>';
window.fbAsyncInit = function() {
FB.init({
appId: AppID,
status: true,
cookie: true,
xfbml: true,
channelUrl: 'http://<%=Request.ServerVariables("HTTP_HOST")%>/channel.html'
});
FB.Event.subscribe('auth.login', function(response) {
//alert('logged in');
});
FB.Event.subscribe('auth.logout', function(response) {
//alert('logged out');
});
FB.getLoginStatus(function(response) {
if (response.status === "connected") {
var uid = response.authResponse.userID;
document.getElementById('hdnFBConnected').value = uid;
}
else if (response.status === "not_authorized") {
//alert("Not authorized");
document.getElementById('hdnFBConnected').value = '';
}
else {
//alert("user not logged in to facebook");
document.getElementById('hdnFBConnected').value = '';
}
});
};
</script>
<img src="<%=global_language & "/images/FacebookSmall.gif"%>" />
<script type="text/javascript" language="javascript">
function WindowOpen() {
if (document.getElementById('hdnFBConnected').value != '') //user is connected
{
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = document.getElementById('hdnFBConnected').value;
//log the user into my site
})
}
else { //user is not connected, so calling FB.Login()
FB.login(function(response) {
if (response.authResponse) {
var access_token = response.authResponse.accessToken;
FB.api('/me', { fields: 'first_name, last_name, locale, email' }, function(result) {
var uid = response.authResponse.userID;
var globalLang = '<%=global_language%>';
//log the user into my site })
}
else {
//alert('User cancelled login or did not fully authorize.');
}
}, { scope: 'email' }
);
}
}
</script>
</body>
What you're describing is normal behavior. The JS SDK is sending the old user's signed_request object which allows the new user to access her account. Since this concerns you, include a logout button on your app's page and let the user know that it's important she clicks that button when she's done using your app. The logout button should call FB.logout like so:
FB.logout(function(response) {
// user is now logged out
});
For extra security, you can create an activity timer that prompts the user to click a button after X minutes of inactivity. If the user doesn't click within, say 1 minute, she is logged out automatically. This is how most banking sites deal with session security.

App Facebook login

I trying to make a login action for my Facebook App, the code is like this:
$("#btnLogin").click(function ()
{
FacebookLogin();
});
....
function FacebookLogin()
{
FB.login(function(response) {
if (response.authResponse) {
top.location.href = "result.html";
}
}, {scope: 'email'});
}
When I click on the login button, the Facebook login popup is showed and after the init session this pop up is not redirecting fine, is stopped in
https://www.facebook.com/dialog/permissions.request..
I think that the problem is related to the settings security. If I disable the navigation security, the App is working fine, otherwise the "Login popup" is stopped in the url
Any idea?

Facebook - How can i post to a company using the javascript sdk?

Im new to facebook posting but have had some success with posting offline with a user account but cannot post offline with a company page.
I have created my own "Facebook App" called "Nicks Poster App" via my own personal facebook account. I have granted three permissions (offline_access,read_stream,publish_stream) to the app for both my personal page and my company page.
i did this by following these steps for each account...
Creating the app...
1. Login to facebook with the account you want linked to the app
2. Follow this link http://www.facebook.com/developers/apps.php#!/developers/createapp.php
3. Create your app and take a note of you App Id and your App secret Id.
Giving the correct rights to the app and getting the access_token..
Method 1:
1. Get the account in question to login to facebook
2. However you like, direct the user to this link (replacing <App-Id> with the App Id of the created app) https://graph.facebook.com/oauth/authorize?client_id=<App-Id>&scope=offline_access,read_stream&redirect_uri=http://www.facebook.com/connect/login_success.html
3. Take a note of the result of the β€œcode” querystring.
4. Goto this url (replace β€œ<APP-ID>” with you appId and β€œ<APP-SECRET>” with your apps secret id and β€œ<code>” with the copied code)
https://graph.facebook.com/oauth/access_token?client_id=<APP-ID>&redirect_uri=http://www.facebook.com/connect/login_success.html&client_secret=<APP-SECRET>&code=<code>
5. Copy what you see, minus the expires querystring. That is your access_token.
After i had the access token for both accounts i used this code to make the post.
<!-- FACEBOOK -->
<div id="fb-root"></div>
<script>
(function () {
var e = document.createElement('script');
// replacing with an older version until FB fixes the cancel-login bug
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//e.src = 'scripts/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
} ());
</script>
<!-- END-OF-FACEBOOK -->
<script>
//initialise
window.fbAsyncInit = function () {
FB.init({
appId: '351023398277068',
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 authentication
});
};
function sendPost(inMessage) {
var opts = {
message: inMessage,
access_token: '<SAVED-TOKEN>'
};
FB.api('/me/feed', 'post', opts, function (response) {
if (!response || response.error) {
alert('Posting error occured');
}
else {
alert('Success - Post ID: ' + response.id);
}
});
}
</script>
When executing the "sendPost" command with the perameter 'Test post', it will work for my personal account (providing i put my access_token in place). This does not work for my company page, and im at a loss as to why(i do put my acess_token in place).
Facebok also havent documented this very well and it makes it hard to make progress, does anyone understand why this doesnt work for company pages?
Thank you in advance.
You can set the "to" parameter to target the page you wish to post to, "manage pages perms will be needed if you wish to post as your page to your page as the application.
<div id="msg"></div>
<script>
// uid is the id of the page or user you wish to post to.
function feedthis2(uid) {
// calling the API ...
var obj = {
method: 'feed',
to: ''+uid+''
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
feedthis2('AnotherFeed'); // to http://facebook.com/anotherfeed
//feedthis2('135669679827333');
</script>

In Facebook FB.ui (method: permissions.request) user is not redirect to proper location

Hi i m trying to show permission dialog using following code:
$permission = $facebook->api(array('method' =>'users.hasAppPermission','ext_perm'=>'publish_stream','uid'=> $uid));
if($permission != '1')
{
echo "<script type='text/javascript'>
var dialog = {
method: 'permissions.request',
perms: 'publish_stream',
redirect_uri: 'http://apps.facebook.com/abcd/'
};
FB.ui(dialog,null);
</script>";
}
This code works fine but problem is that when user allow to permissions he is not redirected to redirect_uri location(that is my canvas page) instead it goes to canvas url (that is my server's url). how to solve this problem Help me.
You can add the following javascript code in your page:
FB.Event.subscribe('auth.sessionChange', function(response) {
if (response.session) {
window.location.href = '/whatever/here';
} else {
// The user has logged out, and the cookie has been cleared
}
});