[그림] 프론트 자바스크립트만으로 페이스북 로그인 구현 (2015년 3월판)

소개



Facebook의 API는 코로코로 바뀌어 귀찮네요.
2012년이나 2013년에 쓰여진 기사는 거의 참고가 되지 않습니다. (dis라고 하는 것이 아닙니다. 사실입니다 땀)

오랜만에 만져 보았으므로 현시점(2015년 3월)에서의 실장 순서를 정리해 보았습니다.

톱 페이지



개발자 톱 페이지
htps : //에서 ゔぇぺぺrs. 후세보오 k. 코m/

My Apps > Add a new app > 웹사이트를 선택하세요.
그건 바로 ↓ 링크도 괜찮습니다.

웹사이트용 링크



웹 페이지용 기능을 만드는 경우는 이쪽
htps : //에서 ゔぇぺぺrs. 후세보오 k. 이 m / 쿠이 cks rts /? p t t rm = u b



입력 양식에 새로 만들 응용 프로그램의 이름을 쓰고 Create New Facebook App ID를 선택합니다.



카테고리에 원하는 항목을 선택하고 Create App ID를 선택하세요.


그러면 화면 아래쪽에 코드가 생성됩니다. 우선 생성된 AppID를 메모해 둡니다. (이미지의 덮여있는 부분)


다른 코드는 스루하고 아래쪽에 URL을 입력하는 양식이 있기 때문에
우선, 자신의 로컬 머신상의 호스트 or 실제로 이용하는 사이트의 URL을 입력해 다음을 선택합시다.



다음과 유사한 코드가 표시됩니다. 을 통해 맨 아래 로그인을 선택합니다.



이 페이지로 리디렉션합니다.
htps : //에서 ゔぇぺぺrs. 후세보오 k. 코 m/도 cs/후세보오 k-㎉ 긴/ぉ ギン-fぉ w-ふぉr-ぇ b/v2.2



여기서 마침내 Quick Start 코드를 살펴 보겠습니다.

login.html
<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<script>
  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
      testAPI();
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
      document.getElementById('status').innerHTML = 'Please log ' +
        'into Facebook.';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
  FB.init({
    appId      : '{your-app-id}',
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2' // use version 2.2
  });

  // Now that we've initialized the JavaScript SDK, we call 
  // FB.getLoginStatus().  This function gets the state of the
  // person visiting this page and can return one of three states to
  // the callback you provide.  They can be:
  //
  // 1. Logged into your app ('connected')
  // 2. Logged into Facebook, but not your app ('not_authorized')
  // 3. Not logged into Facebook and can't tell if they are logged into
  //    your app or not.
  //
  // These three cases are handled in the callback function.

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

  };

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

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.
  function testAPI() {
    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>

<!--
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

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

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

</body>
</html>

적당히 에디터로 방금 전의 코드의 appId 부분에 메모한 숫자를 넣어 주세요.


이상입니다.

실제로 Facebook에 로그인해 봅시다.



마지막으로 브라우저에서 액세스하면 Facebook 인증을 할 수 있습니다.



쉽게 페이스 북 로그인 기능이 가능했습니다. 서버측의 스킬 없음입니다.

좋은 웹페이지 즐겨찾기