Facebook,Google用戶登錄的接入

根據官方的接入文檔,編寫適合自己用的接入代碼

1.Facebook接入

// 加載Facebook JS SDK
(function(d, s, id) {                      // Load the SDK asynchronously
  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'));

//加載完js sdk之後立即初始化
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 webpage.
    version    : 'v5.0'           // 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.
  //});
};

//Facebook的登錄狀態檢測,在這裏可以獲取到FB的登錄結果,可以加入自己的方法
function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
  console.log('FB登錄結果:', 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.
    alert('Not Login Facebook')
  }
}

function testAPI() {                      // Testing Graph API after login.  See statusChangeCallback() for when this call is made.
  console.log('Welcome!  Fetching your information.... ');
  // FB.api 第二個參數可以加入指定對象 {fields: 'id,name,token_for_business'}
  FB.api('/me', function(response) {
    console.log('Successful login for: ' + response.name);
  });
}

//點擊登錄按鈕執行操作
function onFacebookLogin() {
  //調用Facebook的內置登錄方法
  FB.login(function (response) {
    statusChangeCallback(response);
  });
}

// 點擊退出登錄按鈕執行的操作
function onFacebookLogout() {
  FB.logout(function(response) {
    console.log(response);
    console.log("Person is now logged out");
  });
}

2.Google接入

首先要引入js文件

https://apis.google.com/js/api:client.js

var googleUser = {};
var startApp = function () {
    gapi.load('auth2', function () {
        // Retrieve the singleton for the GoogleAuth library and set up the client.
        auth2 = gapi.auth2.init({
            client_id: 'your id', //客戶端ID
            cookiepolicy: 'single_host_origin',
            scope: 'profile' //可以請求除了默認的'profile' and 'email'之外的數據
        });
        //爲登錄按鈕設置ID:customBtn,會自動增加觸發事件
        attachSignin(document.getElementById('customBtn'));
    });
};

function attachSignin(element) {
	//點擊登錄按鈕後就會彈出google登錄
    auth2.attachClickHandler(element, {},
    	//登錄結果返回
        function (googleUser) {
        	console.log(googleUser);
            var profile = auth2.currentUser.get().getBasicProfile();
            var authResponse = auth2.currentUser.get().getAuthResponse();
            console.log('ID: ' + profile.getId());
            console.log('Full Name: ' + profile.getName());
            console.log('Given Name: ' + profile.getGivenName());
            console.log('Family Name: ' + profile.getFamilyName());
            console.log('Image URL: ' + profile.getImageUrl());
            console.log('Email: ' + profile.getEmail());
            console.log('access_token: ' + authResponse.access_token);
            console.log('idToken: ' + authResponse.id_token);
        }, function (error) {
            console.log(JSON.stringify(error, undefined, 2));
        });
}

//註銷
function signOut() {
	var auth2 = gapi.auth2.getAuthInstance();
	auth2.signOut().then(function () {
		alert('用戶註銷成功');
	});
}

//啓動google登錄初始化方法
startApp();

3.Twitter登錄

首先要加載jQuery文件

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
function twitter(){
	$.ajax({
		type: "POST",
		url: "https://api.twitter.com/oauth/authorize",
		data: "oauth_token=Z6eEdO8MOmk394WozF5oKyuAv855l4Mlqo7hhlSLik",
		success: function(msg){
			alert( "Data Saved: " + msg );
		}
	});
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章