Đăng nhập với Facebook JavaScript SDK

Cập nhật lần cuối vào

Hôm qua mình đã đăng bài viết hướng dẫn đăng nhập với Google+ API, tiếp theo trong loạt các bài viết này thì mình sẽ giới thiệu với các bạn cách đăng nhập vào web của bạn bằng tài khoản Facebook. Mạng xã hội Facebook được rất nhiều người sử dụng, do vậy nếu trang web của bạn cho phép kết nối với tài khoản Facebook là điều tuyệt vời, người dùng không cần phải đăng ký tài khoản mới mà chỉ cần đăng nhập với Facebook là có thể sử dụng chức năng trên trang của bạn.

Đăng nhập vào web với Facebook JavaScript SDK

Cũng giống như bao trang mạng xã hội lớn khác, Facebook cũng hỗ trợ API cho phép bạn đăng nhập vào bất kỳ trang web nào thông qua tài khoản Facebook. Bạn có thể tìm hiểu thêm thông tin trên trang chủ của Facebook Developers.

Trước khi thực hiện hướng dẫn này thì bạn phải tạo APP Facebook của bạn. Nếu bạn đã có APP rồi thì bạn có thể vào trình quản lý APP Facebook để cài đặt hoặc là tạo một APP mới tùy theo công việc của bạn.

<!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.5' // use graph api version 2.5
			});
			// 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>

Đoạn code ví dụ mẫu bên trên là của Facebook, bạn có thể dựa theo đoạn code này để tùy biến đăng nhập với tài khoản Facebook.

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

Bên trong nội dung của nút đăng nhập này sẽ có thông tin scope và hàm xử lý sự kiện onlogin. Scope là những thông tin quyền mà bạn cần được biết khi người dùng kết nối vào trang của bạn.

Xem thêm: Permissions Reference – Facebook Login

Bên trên là những gì cơ bản nhất để bạn tạo chức năng đăng nhập với Facebook. Nếu bạn muốn tạo nút đăng nhập tùy chỉnh thì bạn có thể tham khảo đoạn code bên dưới:

function hocwp_facebook_login_button() {
    ?>
    <button type="button" data-action="login-facebook" onclick="hocwp_facebook_login();" class="btn-facebook btn-social-login btn btn-large">
        <svg class="flicon-facebook flip-icon" viewBox="0 0 256 448" height="448" width="256" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" version="1.1">
            <path d="M239.75 3v66h-39.25q-21.5 0-29 9t-7.5 27v47.25h73.25l-9.75 74h-63.5v189.75h-76.5v-189.75h-63.75v-74h63.75v-54.5q0-46.5 26-72.125t69.25-25.625q36.75 0 57 3z"/>
        </svg>
        <span><?php hocwp_text('Đăng nhập bằng Facebook', __('Login with Facebook', 'hocwp')); ?></span>
    </button>
    <?php
}

function hocwp_facebook_login_script($args = array()) {
    if(is_user_logged_in()) {
        return;
    }
    $lang = hocwp_get_language();
    $language = hocwp_get_value_by_key($args, 'language');
    if(empty($language) && 'vi' === $lang) {
        $language = 'vi_VN';
    }
    $app_id = hocwp_get_wpseo_social_facebook_app_id();
    if(empty($app_id)) {
        _e('Please set your Facebook APP ID first.', 'hocwp');
        return;
    }
    ?>
    <script type="text/javascript">
        window.hocwp = window.hocwp || {};
        function hocwp_facebook_login_status_callback(response) {
            if(response.status === 'connected') {
                hocwp_facebook_login_connected_callback();
            } else if(response.status === 'not_authorized') {

            } else {

            }
        }
        function hocwp_facebook_login() {
            FB.login(function(response) {
                hocwp_facebook_login_status_callback(response);
            }, { scope: 'email,public_profile,user_friends' });
        }
        window.fbAsyncInit = function() {
            FB.init({
                appId: '<?php echo $app_id; ?>',
                cookie: true,
                xfbml: true,
                version: 'v<?php echo HOCWP_FACEBOOK_GRAPH_API_VERSION; ?>'
            });
        };
        if(typeof FB === 'undefined') {
            (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/<?php echo $language; ?>/sdk.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        }
        function hocwp_facebook_login_connected_callback() {
            FB.api('/me', {fields: 'id,name,first_name,last_name,picture,verified,email'}, function(response) {
                (function($) {
                    $.ajax({
                        type: 'POST',
                        dataType: 'json',
                        url: hocwp.ajax_url,
                        data: {
                            action: 'hocwp_social_login_facebook',
                            data: JSON.stringify(response)
                        },
                        success: function(response){
                            var href = window.location.href;
                            if($.trim(response.redirect_to)) {
                                href = response.redirect_to;
                            }
                            if(response.logged_in) {
                                window.location.href = href;
                            }
                        }
                    });
                })(jQuery);
            });
        }
    </script>
    <?php
}

Đoạn code bên trên có 2 hàm để tạo button và hàm xuất mã javascript xử lý sự kiện. Bên trong nội dung của code bên mình có sử dụng những hàm riêng, do vậy bạn chỉ áp dụng để khảo chứ không thể sao chép về là chạy ngay được. Hy vọng qua bài viết này có thể giúp ích được bạn trong khâu tạo đăng nhập với Facebook. Chúc bạn thành công.

Theo dõi
Thông báo của
guest

4 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận
Thanh Le
7 năm trước

Cảm ơn chia sẻ của Cường. Với độ phủ của Facebook như hiện nay thì việc thêm Form đăng nhập bằng tài khoản Facebook sẽ lôi kéo thêm được một lượng kha khá người dùng ngại đăng ký theo cách thông thường :P.

Giấy phép vệ sinh an toàn thực phẩm

Kiểu này cũng hay, nhưng mà mình làm hoài ko lấy dc live long token nhỉ. nên ko set dc time cho user giử đăng nhập theo thời gian tùy chỉnh. DÙng php thấy ổn hơn

Thiên
Thiên
7 năm trước

tạo cái khung văn bản chưa code thế kia làm sao ad