GoogleログインボタンでHelloWorld!〜Google+SignInButtonのサンプル

実行サンプル

解説

Google+のSign-in buttonの機能を使ってWebサイトでGoogleのサインインを実現するサンプルです。

Webサービスやアプリを提供する際に、いちいちユーザーのメールやパスワードを登録してもらうのはユーザーにとっても管理的にも煩雑です。

このGoogle+のSign-in buttonを使えば、わずかなコードでユーザーにGoogleにサインインして貰い、IDを取得できるのでそのままWebサービスやアプリのユーザーIDとして使うことができます。

Googleより

準備

  1. Google Developers ConsoleにてGoogle+APIをON。OAuth2.0のクライアントIDを取得しOriginsに呼び出し元のサイトURLを設定しておきます。
  2. span要素のdata-cliendid属性のCLIENT_IDに実際のクライアントIDを記入します。

ソースコード

<script src="https://apis.google.com/js/client:plusone.js"></script>

<script>
    function signOut(){
        document.getElementById('signinButton').setAttribute('style', 'display: inline');
        document.getElementById('signoutButton').setAttribute('style', 'display: none');
        gapi.auth.signOut()
        document.getElementById('message').innerHTML="サインアウトしました。"
    }

    function signinCallback(authResult){
         if (authResult['status']['signed_in']) {
            document.getElementById('signinButton').setAttribute('style', 'display: none');
            document.getElementById('signoutButton').setAttribute('style', 'display: inline');
            gapi.client.load('plus','v1', function(){
                 var request = gapi.client.plus.people.get({
                     'userId': 'me'
                 });
                 request.execute(function(resp) {
                    document.getElementById('message').innerHTML="Hello! "+resp.displayName+"("+resp.id+")"
                 });
            })
        }
    }
</script>

<div>
    <span id="signinButton">
         <span
            class="g-signin"
            data-callback="signinCallback"
            data-clientid="CLIENT_ID"
            data-cookiepolicy="single_host_origin"
            data-scope="profile">
        </span>
    </span>

    <input type='button' id='signoutButton' onclick='signOut()' style='display:none' value='サインアウト' ></input>
</div>

<div id='message'></div>

参考リンク

この記事を見た人がよく読んでいる記事

トップページ

節約テクノロジ > GoogleログインボタンでHelloWorld!〜Google+SignInButtonのサンプル