Sunday, June 10, 2012

How to get access token from FB.login method in javascript SDK


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.



Thanks in advance....


Source: Tips4all

3 comments:

  1. You can get access token using response.session.access_token:

    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.getAuthResoponse();
    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; } }

    ReplyDelete
  2. 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'});

    ReplyDelete
  3. 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

    ReplyDelete