利用 JavaScript SDK 部署网页版 Facebook 登录

本文档将分步介绍如何利用 JavaScript 版 Facebook SDK,在您的网页上实现 Facebook 登录。

准备工作

您需要准备以下各项:

基础的自动登录示例

以下代码示例展示了如何向网页添加 Javascript 版 Facebook SDK、初始化 SDK,以及如何在已登录 Facebook 的情况下,显示您的名字和邮箱。如果您尚未登录 Facebook,系统将自动显示登录对话框弹出窗口。

您可借助 public_profile 权限 获取名字和头像等公开信息,而 email 权限 无需经过应用审核,系统即可为使用 Facebook 登录的所有应用自动授予。

<!DOCTYPE html>
<html lang="en">
  <head></head>
  <body>

    <h2>Add Facebook Login to your webpage</h2>

      <!-- Set the element id for the JSON response -->
    
      <p id="profile"></p>

      <script>
  
        <!-- Add the Facebook SDK for Javascript -->
  
        (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 = "https://connect.facebook.net/en_US/sdk.js";
                              fjs.parentNode.insertBefore(js, fjs);
                            }(document, 'script', 'facebook-jssdk')
        );


        window.fbAsyncInit = function() {
            <!-- Initialize the SDK with your app and the Graph API version for your app -->
            FB.init({
                      appId            : '{your-facebook-app-id}',
                      xfbml            : true,
                      version          : '{the-graph-api-version-for-your-app}'
                    });
            <!-- If you are logged in, automatically get your name and email adress, your public profile information -->
            FB.login(function(response) {
                      if (response.authResponse) {
                           console.log('Welcome!  Fetching your information.... ');
                           FB.api('/me', {fields: 'name, email'}, function(response) {
                               document.getElementById("profile").innerHTML = "Good to see you, " + response.name + ". i see your email address is " + response.email
                           });
                      } else { 
                           <!-- If you are not logged in, the login dialog will open for you to login asking for permission to get your public profile and email -->
                           console.log('User cancelled login or did not fully authorize.'); }
            });
        };

      </script>

  </body>
</html>

1. 为 Facebook 登录功能启用 JavaScript SDK

应用面板中选择您的应用,然后滚动到添加产品,在 Facebook 登录图卡中点击设置。在左侧导航面板中选择设置,然后在客户端 OAuth 设置下的有效 OAuth 重定向 URI 字段中输入重定向网址,成功完成授权。

使用 JavaScript SDK 登录开关切换为“是”,表明使用 JavaScript SDK 来实现 Facebook 登录,并在 JavaScript SDK 允许使用的网域列表中输入托管 SDK 的页面的网域。这有助于确保访问口令仅返回到授权网域的回调。仅 https 页面支持使用 Facebook JavaScript SDK 执行验证操作。

2. 检查用户登录状态

网页加载时,首先应检查用户是否已使用 Facebook 登录功能登录您的网页。调用 FB.getLoginStatus 可以触发 Facebook 调用,获取登录状态。然后 Facebook 会调用您的回调函数,返回结果。

调用示例

FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
});

JSON 响应示例

{
    status: 'connected',
    authResponse: {
        accessToken: '{access-token}',
        expiresIn:'{unix-timestamp}',
        reauthorize_required_in:'{seconds-until-token-expires}',
        signedRequest:'{signed-parameter}',
        userID:'{user-id}'
    }
}

status 表示网页用户的登录状态。status 可以是以下其中一种类型:

Status 类型描述

connected

用户已登录 Facebook 和您的网页。

not_authorized

用户已登录 Facebook,但未登录您的网页。

unknown

用户未登录 Facebook,所以无法得知他们是否登录了您的网页。或者之前已调用 FB.logout(),因此无法连接至 Facebook。

如果状态为 connected,响应中会包含下列 authResponse 参数:

authResponse 参数

accessToken

网页用户的访问口令。

expiresIn

口令过期时的 UNIX 时间戳。口令到期后,用户将需重新登录。

reauthorize_required_in

距离登录到期的剩余时长(以秒为单位),之后用户将需要重新登录。

signedRequest

经签名的参数,其中包含网页用户的信息。

userID

网页用户的编号。

JavaScript SDK 会自动检测登录状态,您无需执行任何操作即可启用此行为。

3. 让用户登录

如果用户打开网页后并没有登录网页,或是没有登录 Facebook,您可以使用登录对话框来提示他们登录两者。如果用户未登录 Facebook,系统首先会提示他们登录 Facebook,然后提示登录您的网页。

下面是用户登录的两种方式:

A. 通过“登录”按钮登录

如要使用 Facebook 登录按钮,请使用我们的插件配置器自定义“登录”按钮并获取代码。

插件配置器

Width
按钮大小
按钮文本
按钮布局形状
[?]

B. 通过 JavaScript SDK 登录对话框登录

如要使用您自己的“登录”按钮,请向 FB.login() 发出调用,以调用登录对话框。

FB.login(function(response){
  // handle the response 
});

请求更多权限

当用户点击 HTML 按钮时,页面会显示带有登录对话框的弹出窗口。您可以通过此对话框请求权限,以访问用户的数据。scope 参数可随 FB.login() 函数调用一同传递。此可选参数是一个以逗号分隔的权限列表,用户必须确认这些权限才能授权您的网页访问其数据。Facebook 登录需要取得高级 public_profile 权限,才能供外部用户使用。

调用示例

此示例会询问登录用户是否愿意授权,以允许您的网页访问他们的公开资料和邮箱。

FB.login(function(response) {
  // handle the response
}, {scope: 'public_profile,email'});

处理登录对话框响应

响应(连接或取消)会向调用 FB.login() 时指定的回调返回 authResponse 对象。您可在 FB.login() 内检测和处理此响应。

调用示例

FB.login(function(response) {
  if (response.status === 'connected') {
    // Logged into your webpage and Facebook.
  } else {
    // The person is not logged into your webpage or we are unable to tell. 
  }
});

4. 让用户退出

在按钮或链接中附加 JavaScript SDK 函数 FB.logout(),即可让用户退出网页。

调用示例

FB.logout(function(response) {
   // Person is now logged out
});

注意:调用此函数还可能会让用户退出 Facebook。

请考虑下列情形

  1. 用户先登录 Facebook,然后再登录您的网页。用户退出您的应用时,仍保持 Facebook 登录状态。
  2. 用户登录您的网页,并在应用登录流程中登录 Facebook。用户退出您的应用时,同时也将退出 Facebook。
  3. 用户登录了另一网页,并在该网页的登录流程中登录 Facebook,然后再登录您的网页。当该用户退出任一网页时,同时也退出 Facebook。

此外,用户退出您的网页并不会撤销其在登录期间授予网页的权限。撤销权限操作必须单独执行。构建您的网页时,应让已退出的用户在重新登录时不会看到登录对话框。

完整代码示例

下面的代码将在 HTML 页面中加载和初始化 JavaScript SDK。将 {app-id} 替换为您的应用编号,并将 {api-version} 替换为要使用的图谱 API 版本。除非有特殊原因必须使用较旧版本,否则请指定最新版本: v19.0

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>

  function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
    console.log('statusChangeCallback');
    console.log(response);                   // The current login status of the person.
    if (response.status === 'connected') {   // Logged into your webpage and Facebook.
      testAPI();  
    } else {                                 // Not logged into your webpage or we are unable to tell.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this webpage.';
    }
  }


  function checkLoginState() {               // Called when a person is finished with the Login Button.
    FB.getLoginStatus(function(response) {   // See the onlogin handler
      statusChangeCallback(response);
    });
  }


  window.fbAsyncInit = function() {
    FB.init({
      appId      : '{app-id}',
      cookie     : true,                     // Enable cookies to allow the server to access the session.
      xfbml      : true,                     // Parse social plugins on this webpage.
      version    : '{api-version}'           // Use this Graph API version for this call.
    });


    FB.getLoginStatus(function(response) {   // Called after the JS SDK has been initialized.
      statusChangeCallback(response);        // Returns the login status.
    });
  };
 
  function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
  }

</script>


<!-- The JS SDK Login Button -->

<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>

<div id="status">
</div>

<!-- Load the JS SDK asynchronously -->
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>
</body>
</html>