Facebook获取访问令牌

4

如何使用Facebook Graph API获取"访问令牌"。我有应用程序ID,用户的用户名和密码。我只需要获取访问令牌,以便可以访问新闻动态等内容。

1个回答

18

好的,您需要在JavaScript中获取用户的access_token。请看下面:

  1. Start reading the JavaScript SDK documentation
  2. Something like the below will get you started:

    <div id="fb-root"></div>
    <script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'YOUR_APP_ID', // App ID
            channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
            status     : true, // check login status
            cookie     : true, // enable cookies to allow the server to access the session
            xfbml      : true  // parse XFBML
        });
        // this shouldn't be called directly, but instead should be initiated with a user click event
        FB.login(function(response) {
            if (response.authResponse) {
                console.log('Access Token: ' + response.authResponse.accessToken);
            } else {
                console.log('User cancelled login or did not fully authorize.');
            }
        });
    
    };
    
    // 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>
    
  3. As mentioned in the documentation:

    Calling FB.login results in the JS SDK attempting to open a popup window. As such, this method should only be called after a user click event, otherwise the popup window will be blocked by most browsers.

  4. NEVER EVER ask for the user password nor give it to ANY application if it asks you! and if it does, report it to Facebook directly!

  5. It's "JavaScript" not "Java Script" :-)


@hhh,不用谢...我还编辑了代码,在FB.login上面添加了一条注释,为那些只是复制/粘贴代码而没有阅读完整答案的人提供帮助。;-) - ifaour

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接