web-dev-qa-db-fra.com

Comment obtenir un jeton d'accès à partir de la méthode FB.login dans le SDK javascript

J'ai besoin d'obtenir le jeton d'accès de FB.login méthode en Javascript SDK. Mon code de connexion est

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

Est-il possible d'obtenir un jeton d'accès? Je peux obtenir le jeton d'accès en utilisant PHP.

56
Damodaran

Vous pouvez obtenir un jeton d'accès en utilisant 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: mis à jour pour utiliser Oauth 2.0, obligatoire depuis décembre 2011. Utilise maintenant FB.getAuthResponse();) si vous utilisez un navigateur qui ne possède pas de console, vous, Internet Explorer) veillez à mettre en commentaire les lignes console.log ou à utiliser un script log-failafe tel que:

if (typeof(console) == "undefined") { console = {}; } 
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
117
Pavel Surmenok

response.session.access_token ne fonctionne pas dans mon code. Mais cela fonctionne: response.authResponse.accessToken

     FB.login(function(response) { alert(response.authResponse.accessToken);
     }, {perms:'read_stream,publish_stream,offline_access'});
12
johannes

Si vous êtes déjà connecté, tapez simplement ceci dans la console javascript:

FB.getAuthResponse()['accessToken']
4
Nimo

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
    }
});
3
Virus

response.session ne fonctionne plus car response.authResponse est le nouveau moyen d'accéder au contenu de la réponse après la migration oauth).
Vérifiez ceci pour plus de détails: SDK & Tools ›SDK JavaScript› FB.login

2
Raul Vejar
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 -->
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>

<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
                </fb:login-button>
0
Mehdi Benkirane
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 -->
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>

<!-- Facebook button -->
<fb:login-button scope="public_profile,email" onlogin="fb_login();">
                </fb:login-button>
0
Prince Zain