I am trying to implement FacbookSDK 2.8 for my website and below is the simplified version of the code.
<button onclick="logout()">Logout</button>
<button onclick="login()">LogIn</button>
<script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
setTimeout(() => {
window.fbAsyncInit = () => {
FB.init({
appId: 'xxxxxxx', //My app id here
cookie: true, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.8' // use graph api version 2.8
});
checkFBLoginStatus();
}
})
function checkFBLoginStatus() {
FB.getLoginStatus((response) => {
console.log(response)
});
}
function logout() {
FB.logout(function(response) {
console.log(response)
})
}
function login() {
FB.login(function(response) {
console.log(response)
FB.api('/me?fields=id,email,name', function(response) {
console.log(JSON.stringify(response));
});
}, {
scope: 'email'
})
}
function onLoginSuccess() {
FB.getLoginStatus(function(response) {
console.log(response)
})
}
</script>
I am getting the response on logout and login
Here are my questions
On FB.api call i am getting only ID and Name whereas i need user email to set as an unique user identifier.
When is the condition i can achieve not_authorized. I am getting status 'connected' if i login and 'unknown' if i logout. I am not able to reproduce the condition un_authorized, so that i could code for it.
You should use the ID of the user to identify him, not the email. Users do not have to have an email, they can also use their phone number to login. Make sure you get asked for the email permission in the login process/popup. Also, use this form instead:
FB.api('/me', {fields: 'id,email,name'}, function(response) {
console.log(JSON.stringify(response));
});
Related
I'm trying to get some basic information using Facebook api, but so far I only get the user's name and id. As in { name: "Juan Fuentes", id: "123456" }
I need to get mor einformation, like email, first name, last name and birthday
This is my js code
function facebookLogin() {
FB.login(function(response) {
var token = response.authResponse.accessToken;
var uid = response.authResponse.userID;
if (response.authResponse) {
FB.api('/me', 'get', { access_token: token }, function(response) {
console.log(response);
});
FB.api('/'+uid, 'get', { access_token: token }, function(response) {
console.log(response);
});
}
},
{ scope: 'public_profile' }
);
}
And this is the button that activates it
<a id="fb-login" href="#" onclick="facebookLogin()"></a>
You need to manually specify each field since Graph API v2.4:
https://developers.facebook.com/docs/apps/changelog#v2_4
https://developers.facebook.com/docs/javascript/reference/FB.api
Declarative Fields
To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/me/feed no longer includes likes and comments by default, but GET /v2.4/me/feed?fields=comments,likes will return the data. For more details see the docs on how to request specific fields.
E.g.
FB.api('/me', 'get', { access_token: token, fields: 'id,name,gender' }, function(response) {
console.log(response);
});
It's also possible to use this syntax for data from public_profile scope (tested in Graph API v2.9):
FB.api('/me?fields=birthday,link,gender,age_range', function(response) {
console.log(response);
});
You can test the possible values online in Graph API Explorer, just click "Get Token" button:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Dbirthday%2Clink%2Cgender%2Cage_range&version=v2.9
Here is the complete Script:
jQuery(document).ready(function () {
openLoginPopup();
})
function openLoginPopup() {
FB.getLoginStatus(function (response) {
if (response.status == 'connected') {
getCurrentUserInfo(response);
} else {
FB.login(function (response) {
if (response.authResponse) {
getCurrentUserInfo(response);
} else {
console.log('Auth cancelled.');
}
}, {scope: 'email'});
}
});
}
function getCurrentUserInfo() {
FB.api('/me?fields=id,email,first_name,last_name,name', function (userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
window.fbAsyncInit = function () {
FB.init({
// appId: 'xxxxxxxxxxxxxxxxxxxxx', //livemode
appId: 'xxxxxxxxxxxx', //testmode
cookie: true, // Enable cookies to allow the server to access the session.
xfbml: true, // Parse social plugins on this webpage.
version: 'v4.0' // Use this Graph API version for this call.
});
};
(function (d, s, id) { // Load the SDK asynchronously
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Thanks.
Note that email is not always returned by a call to the me api with email as field, even if scope email was requested and granted, if e.g. the user signed up with a phone number:
https://developers.facebook.com/docs/facebook-login/permissions#reference-email
I'm trying to get some basic information using Facebook api, but so far I only get the user's name and id. As in { name: "Juan Fuentes", id: "123456" }
I need to get mor einformation, like email, first name, last name and birthday
This is my js code
function facebookLogin() {
FB.login(function(response) {
var token = response.authResponse.accessToken;
var uid = response.authResponse.userID;
if (response.authResponse) {
FB.api('/me', 'get', { access_token: token }, function(response) {
console.log(response);
});
FB.api('/'+uid, 'get', { access_token: token }, function(response) {
console.log(response);
});
}
},
{ scope: 'public_profile' }
);
}
And this is the button that activates it
<a id="fb-login" href="#" onclick="facebookLogin()"></a>
You need to manually specify each field since Graph API v2.4:
https://developers.facebook.com/docs/apps/changelog#v2_4
https://developers.facebook.com/docs/javascript/reference/FB.api
Declarative Fields
To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/me/feed no longer includes likes and comments by default, but GET /v2.4/me/feed?fields=comments,likes will return the data. For more details see the docs on how to request specific fields.
E.g.
FB.api('/me', 'get', { access_token: token, fields: 'id,name,gender' }, function(response) {
console.log(response);
});
It's also possible to use this syntax for data from public_profile scope (tested in Graph API v2.9):
FB.api('/me?fields=birthday,link,gender,age_range', function(response) {
console.log(response);
});
You can test the possible values online in Graph API Explorer, just click "Get Token" button:
https://developers.facebook.com/tools/explorer/?method=GET&path=me%3Ffields%3Dbirthday%2Clink%2Cgender%2Cage_range&version=v2.9
Here is the complete Script:
jQuery(document).ready(function () {
openLoginPopup();
})
function openLoginPopup() {
FB.getLoginStatus(function (response) {
if (response.status == 'connected') {
getCurrentUserInfo(response);
} else {
FB.login(function (response) {
if (response.authResponse) {
getCurrentUserInfo(response);
} else {
console.log('Auth cancelled.');
}
}, {scope: 'email'});
}
});
}
function getCurrentUserInfo() {
FB.api('/me?fields=id,email,first_name,last_name,name', function (userInfo) {
console.log(userInfo.name + ': ' + userInfo.email);
});
}
window.fbAsyncInit = function () {
FB.init({
// appId: 'xxxxxxxxxxxxxxxxxxxxx', //livemode
appId: 'xxxxxxxxxxxx', //testmode
cookie: true, // Enable cookies to allow the server to access the session.
xfbml: true, // Parse social plugins on this webpage.
version: 'v4.0' // Use this Graph API version for this call.
});
};
(function (d, s, id) { // Load the SDK asynchronously
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id))
return;
js = d.createElement(s);
js.id = id;
js.src = "https://connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
Thanks.
Note that email is not always returned by a call to the me api with email as field, even if scope email was requested and granted, if e.g. the user signed up with a phone number:
https://developers.facebook.com/docs/facebook-login/permissions#reference-email
I have created a Facebook app which will share a link to users wall
but the issue is the link is posted on my wall but not on any other user's wall
i have put on live link Link to post on wall app
the code of app that will post on users wall is given below is there anything i need to approve it from the facebook or is there any mistake in my code please i need a real help any one could do ?
waiting for your kind response i am new to the Facebook API
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId: '763390233734216', // App ID from the app dashboard
//channelUrl : '//local.facebook-test/channel.html', // Channel file for x-domain comms
status: true, // Check Facebook Login status
xfbml: true, // Look for social plugins on the page
oauth: true // Enable oauth authentication
});
// Additional initialization code such as adding Event Listeners goes here
FB.login(function(response) {
if (response.authResponse) {
console.log(response.authResponse.accessToken);
var params = {};
params['name'] = 'Seasons Canola';
params['description'] = 'Description';
params['link'] = 'http://vimeo.com/99708842';
FB.api('/me/feed', 'post', params, function(response) {
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
} else {
alert('Not logged in');
}
}, {
scope: 'public_profile,email,publish_actions'
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
Im trying to send posts to a wall of a page im an admin to through the js sdk. I have made it do i can do it for myself(my personal user) but i cannot get it to work as the "page".
<div id="fb-root"></div>
<script type="text/javascript">
function SendToFacebook()
{
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '**CORRECT ID**', // App ID from the app dashboard
channelUrl: '**MYPAGE**/channel.html', // Channel file for x-domain comms
status: false, // Check Facebook Login status
xfbml: true // Look for social plugins on the page
});
FB.ui(
{
method: 'feed',
name: 'MyFeed',
link: '',
// picture: '',
caption: 'My caption',
description: 'test',
message: 'MESSAGE?',
},
function (response) {
if (response && response.post_id) {
alert('Delat på facebook.');
} else {
alert('Inte delat på facebook.');
}
}
);
// Additional initialization code such as adding Event Listeners goes here
};
// Load the SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
}
</script>
This posts to my own user page, and ive tried the "to" parameter but it send the post from my personal user to the page. Is there any way to make this though the login function?
bare in mind that im fairly new to this so demos and examples are welcome.
I got it to work after a hard days work, if any1 is interested heres how i did.
<script type="text/javascript">
function SendToFacebook()
{
window.fbAsyncInit = function () {
// init the FB JS SDK
FB.init({
appId: '***', // App ID from the app dashboard
channelUrl: '***', // Channel file for x-domain comms
status: false, // Check Facebook Login status
xfbml: true // Look for social plugins on the page
});
FB.login(function (response) {
FB.api('/me/accounts', function (apiresponse) {
var data = {
message: "mymessage",
display: 'iframe',
caption: "caption",
name: "name",
description: "description",
to: **wallid**,
from: **wallid**
};
FB.api('/**wallid**/feed', 'post', data, function () {
console.log(arguments);
});
});
}, { scope: 'manage_pages' });
};
// Load the SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
}
</script>
I found this solution and I tried it, although I dont know how it was 3 years ago, now you need to append page access token you receive via /me/accounts calling (also you must be admin of that page etc.) so todays working solution could look like this:
FB.api('/me/accounts', function (apiresponse) {
console.log(apiresponse);
var data = {
message: "mymessage",
//display: 'iframe',
caption: "caption",
picture: 'www.bla.com/image.jpg',
link: 'www.facebook.com',
name: "name",
description: "description",
to: **APP IP**,
from: **APP IP**,
access_token: apiresponse.data[0].access_token
};
FB.api('/**APP IP**/feed', 'post', data, function () {
console.log(arguments);
});
});
I need to get the access token from FB.login method in Javascript SDK. My login code is
FB.login(function(response) {
if (response.session) {
if (response.perms) {
} else {
// user is logged in, but did not grant any permissions
alert("No Permission..");
}
} else {
// user is not logged in
alert("Please login to facebook");
}
}, {perms:'read_stream,publish_stream,offline_access'});
Is there any way to get access token? I am able to get the access token using PHP.
You can get access token using FB.getAuthResponse()['accessToken']:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
response.session.access_token doesn't work in my code. But this works:
response.authResponse.accessToken
FB.login(function(response) { alert(response.authResponse.accessToken);
}, {perms:'read_stream,publish_stream,offline_access'});
If you are already connected, simply type this in the javascript console:
FB.getAuthResponse()['accessToken']
https://developers.facebook.com/docs/facebook-login/login-flow-for-web/
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
FB.login(function(response) {
if (response.authResponse) {
// The person logged into your app
} else {
// The person cancelled the login dialog
}
});
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// Load the SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>
window.fbAsyncInit = function () {
FB.init({
appId: 'Your-appId',
cookie: false, // enable cookies to allow the server to access
// the session
xfbml: true, // parse social plugins on this page
version: 'v2.0' // use version 2.0
});
};
// Load the SDK asynchronously
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function fb_login() {
FB.login(function (response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function (response) {
var email = response.email;
var name = response.name;
window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;
// used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'email'
});
}
<!-- custom image -->
<img src="/Public/assets/images/facebook/facebook_connect_button.png" />
<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
</fb:login-button>