one's way blog

ワクワクを生み出せるWebエンジニアを目指して。

【43:Facebook SDK for JavaScript】JavaScriptでFacebookログインを実装する

f:id:seintoseiya:20151203010502p:plain
プロジェクトNo.43:Facebook SDK for JavaScript - DEMO

Facebookページのタイムライン表示やいいねボタンの実装なんかはソーシャルプラグインを使えば簡単に実装できます。
ソーシャルプラグイン - ドキュメンテーション - Facebook for Developers


しかし、Facebookログインを利用してユーザ管理などしたい場合は、Facebook側でアプリを作成してSDKに沿った実装をする必要があります。
大きく分けて2つの実装方法があり、JavaScriptを使ってクライアント側のみで認証処理を行う方法と、PHPなどのサーバ側で認証処理を行う方法があります。

今回はより簡単なJavaScriptを使った方法をご紹介しようかと思います。

Facebookアプリを作成

まずはFacebookデベロッパー向け公式サイトの以下からFacebook側の連携用アプリを作成する。
https://developers.facebook.com/apps/

[Add a New App]をクリックして、プラットフォームを選択し(今回はWeb)、アプリ名を適当に付けてください。
これだけで連携に必要なAppIdがゲットできます。
Facebookアプリ側の設定として、自分のローカルマシン上のホスト or 実際に利用するサイトのURLの設定だけすれば準備完了です。

index.htmlを作成

QuickStartの画面の通りに実装するといいねボタンの実装ができますが、
今回はログイン機能を実装するので、一番下のログインリンクをクリックして、
f:id:seintoseiya:20151203010909p:plain
そこのQuickStartに載っているソースをコピペします。
以下のAppIdの部分だけ、ご自身のアプリのものに変更してください。

appId      : '{your-app-id}',

この状態で既にログイン機能は実装されてます。
一度index.htmlにアクセスして試してみてください。

結果

f:id:seintoseiya:20151203011139p:plain

サンプルコードの内容確認

まずは以下の部分が実行され、Facebookサーバ上のSDKをロードしています。

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

SDKが読み込めたら以下の部分が実行されます。

window.fbAsyncInit = function() {
  FB.init({
    appId      : '*****', // 自分のIDを入れる
    cookie     : true,  // enable cookies to allow the server to access 
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.5' // use version 2.5
  });

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

  };

FB.initではAppIdの設定など初期処理を行い、
FB.getLoginStatus()ではログイン状態を確認しています。


statusChangeCallback()では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.';
    }
  }

ログイン状態の場合はtestAPI()を実行し、FB.apiを使って名前情報を取得しています。
もし認証前や失敗してたり、なんらかのエラーでログイン状態でなかったら、それぞれのメッセージが表示されます。

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

ログインボタンを押下すると、ログイン画面がポップアップして、
認証が完了したら、checkLoginState()が実行されFB.getLoginStatus()でログイン状態を確認。

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

ログイン状態の場合の処理は上記の通り。

アプリを公開する

ローカル開発の時はこのままでも良いのですが、
実際にサーバにあげて公開する時は、以下の設定が必要になります。

  • SettingからEmailの設定(複数ドメインで1つのアプリを使用の際はApp Domainsにドメイン名を入力)
  • Status & Reviewから上部のボタンをクリックして、アプリを公開する。

f:id:seintoseiya:20151203011008p:plain

全ソースはこちら

github.com