Nice programing

JavaScript SDK의 FB.login 메서드에서 액세스 토큰을 얻는 방법

nicepro 2020. 12. 28. 22:32
반응형

JavaScript SDK의 FB.login 메서드에서 액세스 토큰을 얻는 방법


FB.loginJavascript SDK의 메서드에서 액세스 토큰을 가져와야합니다. 내 로그인 코드는

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

액세스 토큰을 얻을 수있는 방법이 있습니까? 을 사용하여 액세스 토큰을 얻을 수 있습니다 PHP.


다음을 사용하여 액세스 토큰을 얻을 수 있습니다 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: ''});

편집 : 2011 년 12 월 이후로 필요한 Oauth 2.0을 사용하도록 업데이트되었습니다. 이제 FB.getAuthResponse();콘솔이없는 브라우저를 사용하는 경우 (인터넷 익스플로러) console.log라인 을 주석 처리 하거나 로그를 사용하십시오. -다음과 같은 오류 방지 스크립트 :

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

response.session.access_token내 코드에서 작동하지 않습니다. 그러나 이것은 작동합니다.response.authResponse.accessToken

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

이미 연결되어 있는 경우 자바 스크립트 콘솔에 다음을 입력하면됩니다.

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 -->
<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>


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>

ReferenceURL : https://stackoverflow.com/questions/4758770/how-to-get-access-token-from-fb-login-method-in-javascript-sdk

반응형