I follow a tutor for connection with Facebook which uses the following code to connect to Facebook successfully.
The code follows -
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// TODO: Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", 'loadMainPage.ashx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
};
How can I ask for publish_actions permission ?
What platform are you using? See Facebook's official docs.
An excerpt:
Requesting permissions
Each type of login flow has its own method of requesting these permissions:
Web login with the JavaScript SDK uses a scope option with the FB.login function call.
Other types of web login should add the scope parameter to the Login
dialog URL that they redirect to.
Android login uses the setReadPermissions and setPublishPermissions
on the LoginButton class.
iOS login uses the readPermissions and publishPermissions properties
in the FBLoginView class.
Related
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>
I have the following code to display the users on my site.
function getFBData()
{
FB.api(
'/*fbID*/',
function (response) {
if (response && !response.error) {
/*CODE*/
}
}
);
}
getFBData();
It was working fine when a user is logged in, via Facebook plugin, into the site. But nothing is fetched when the user is not logged in.
Is a user really needed to be logged in to execute FB.api?
Actually user must be logged in to Facebook to use Facebook Api,
you can use the code below to check the state of the user to either get his data if connected or ask him to login again.
FB.init({
appId: 'xxxxxxxxxxxxxxxxxxx',
channelUrl: '//www.yoursite.com/fbsdk-channel.aspx',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.getLoginStatus(function (response) {
if (response.status === 'not_authorized') {
/* The user has already logged into FB but not authorized the your webpage */
}
else if (response.status === 'connected') {
/* The user has logged into FB and authorized the "App" to get their user information */
}
else { /* The user has not yet logged into FB */ }
}
It depends, you CAN use FB.api without authorization, but only for API calls that need an App Access Token. For API calls with a User Token, you do need authorization. Of course you can´t grab details of a user (by ID) without authborization, so in your case you must authorize the user.
More information about Access Tokens and login:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
http://www.devils-heaven.com/facebook-javascript-sdk-login/
To detect the facebook user online/offline status we use the method FB.getLoginStatus method.
But, what does the paramater("response") mean and where does it come from in the below code snippet
the parameter response mean in the line " FB.getLoginStatus(function(response) "
FB.getLoginStatus(function(response) {
console.log(response);
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
console.log('User logged in and autenticated');
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
console.log('User logged in, but not autorized');
} else {
// the user isn't logged in to Facebook.
console.log('User not logged in');
}
}, true);
You are specifying a function to be called when the Facebook API has completed retrieving a response from the server. It passes the response object to the function which you specify. A typical response would be:
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
See facebook javascript docs for more info
I'm using the Facebook C# SDK to allow users to log in to my site using Facebook.
To log out, I can use fb.logout, but this logs the user out of facebook as well as my site, which seems really annoying and unnecessary for the user.
I'm pretty confident that they don't have to log out of Facebook when they log out of my site, as digg.com provides exactly the functionality I'm after - log in and out with facebook, without logging the user out of their Facebook account.
Here's the code I'm using for the log in/out:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function () {
FB.init({
appId: 'XXXXXXXXXXXX', // App ID
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
xfbml: true // parse XFBML
});
// Handle successful log in.
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// Handle the access token
// Do a post to the server to finish the logon
// This is a form post since we don't want to use AJAX
var form = document.createElement("form");
form.setAttribute("method", 'post');
form.setAttribute("action", '/login.aspx');
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
alert("Logged in to facebook but not authenticated MT");
} else {
// the user isn't logged in to Facebook.
}
});
};
// 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 class="fb-login-button" autologoutlink="true"></div>
You'll see that when the user logs in, I redirect to /login.aspx, which provides my site's login functionality (using .net authentication), and also saves the accesstoken to a session for use during the user's session.
I need the log out button to do the same thing, but in reverse, without logging the user out of facebook altogether.
I've looked for hours online, but can't seem to find any way of calling fb.logout without logging the user out of their facebook account too. If digg.com can do it, I must be able to as well, surely?
Many thanks,
Paul
I'm pretty confident that they don't have to log out of Facebook when they log out of my site
Facebook Platform Policies say otherwise – section I. Features and Functionality, #6:
Your website must offer an explicit "Log Out" option that also logs the user out of Facebook.
I want to get the user's FID, Email and Name after login with Javascript so I make an Ajax call and save them to the database.
This is currently the code to login users:
if (response.status === 'connected') { // the user is logged in and connected to your application
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
// Alert with fid, email and name
} else { //the user isn't logged in to Facebook or isn't connected to the application
FB.login(function(response) {
if (response.authResponse) {
accessToken = response.authResponse.accessToken;
// Alert with fid, email and name
}
}, {scope: 'email'});
}
How can I do it?
Call
https://graph.facebook.com/me
or
https://graph.facebook.com/USER_ID
or
https://graph.facebook.com/fql?q=SELECT uid,name,email FROM user WHERE uid=me()
You'll need the
email
permission