使用 javascript SDK 來做 FB/Google 的社群登入

現在網站為求方便,許多都會讓使用者可以用社群網站登入減少認證的麻煩,這邊來筆記一下該怎麼使用 FB 跟 Google 登入的方法。

Google


google 的話要先到 Google API 服務的地方申請一個新的憑證。



接著可以設定一下容易辨識的名字,就可以拿 api 的 id 跟密鑰了。





因為我們是要用 javascript 登入,所以這邊設定網址就不是這麼重要,再來就是實作登入了。

放一顆按鈕:


初始化 google javascript SDK


let Google_appId = "*****.apps.googleusercontent.com";

// Called when Google Javascript API Javascript is loaded
        function HandleGoogleApiLibrary() {
            // Load "client" & "auth2" libraries
            gapi.load('client:auth2', {
                callback: function () {
                    // Initialize client & auth libraries
                    gapi.client.init({
                        clientId: Google_appId,
                        scope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me'
                    }).then(
                        function (success) {
                            // Google Libraries are initialized successfully
                            // You can now make API calls 
                            console.log("Google Libraries are initialized successfully");
                        },
                        function (error) {
                            // Error occurred
                            console.log(error);// to find the reason 
                        }
                    );
                },
                onerror: function () {
                    // Failed to load libraries
                    console.log("Failed to load libraries");
                }
            });
        }



        function GoogleLogin() {
            // API call for Google login  
            gapi.auth2.getAuthInstance().signIn().then(
                function (success) {
                    // Login API call is successful 
                    console.log(success);
                    let Google_ID = success["El"];
                   //這邊可以寫抓到登入資訊後要做的事,比如將會員資料寫到資料庫之類的
                    
                },
                function (error) {
                    // Error occurred
                    // console.log(error) to find the reason
                    console.log(error);
                }
            );

        }

接著就可以這樣拿到 google 登入後的資料了。
// API call to get user profile information
gapi.client.request({ path: 'https://www.googleapis.com/plus/v1/people/me' }).then(
 function(success) {
  // API call is successful

  var user_info = JSON.parse(success.body);

  // user profile information
  console.log(user_info);
 },
 function(error) {
  // Error occurred
  // console.log(error) to find the reason
 }
);

參考:Google Login with Javascript API


Facebook


首先也是先到 Facebook Developer 申請一個 app,並設定一下要用的網域以及拿 app id 及金鑰。


接著一樣放一顆 fb 登入的按鈕


寫 js
//應用程式編號,進入 https://developers.facebook.com/apps/ 即可看到
        let FB_appID = "";

        //FB Login 官方文件:https://developers.facebook.com/docs/facebook-login/web

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

        window.fbAsyncInit = function () {
            FB.init({
                appId: FB_appID,//FB appID
                cookie: true,  // enable cookies to allow the server to access the session
                
                xfbml: true,  // parse social plugins on this page
                version: 'v5.0' // use graph api version
            });

        };

        //使用自己客製化的按鈕來登入
        function FBLogin() {
            
            FB.login(function (response) {
                //debug用
                console.log(response);
                if (response.status === 'connected') {
                    //user登入成功
                    //抓userID
                    let fb_id = response["authResponse"]["userID"];
                    //接著可以對帳號做處理

                   
                } else {
                    // user FB取消授權
                    alert("Facebook帳號無法登入");
                }
            }, { scope: 'public_profile,email' });

        }

完成。

留言

匿名表示…
你有自己試過嗎?你知道這樣根本按按鈕不會有反應嗎?
如果要示範實作麻煩什麼時候用fetch寫清楚點
signIn()有沒有效也請事前檢查清楚
紅色死神寫道…
奇怪勒自己寫不出來怪我
匿名表示…
哈哈哈哈哈