Đăng nhập với Google+ API

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

Tạo chức năng đăng nhập với tài khoản mạng xã hội sẽ giúp trang bạn thân thiện hơn, trong khi thời buổi hiện nay hầu như mọi người ai cũng có tài khoản của Google, Facebook,… thì việc có thêm chức năng đăng nhập với Google hay Facebook đối với các trang cho đăng ký thành viên là điều nên làm.

Google Plus banner

Google cung cấp cho các bạn rất nhiều API hữu ích, nếu biết tận dụng nó trong khâu thiết kế web thì công việc của bạn sẽ trở nên dễ dàng hơn. Trong bài này mình sẽ hướng dẫn cho các bạn cách tạo chức năng đăng nhập với Google thông qua Google Plus API.

Để thực hiện được việc này thì bạn phải đăng ký APP với Google và bên trong APP này bạn phải bật Google+ API. Nếu bạn chưa biết cách tạo thì bạn truy cập vào trang Google API Projects để tạo mới nhé.

Sau khi tạo xong project rồi thì bạn tạo các thứ liên quan trong đó như API Key, Client ID,… Tiếp đến bạn xem đoạn code hướng dẫn tạo nút đăng nhập đơn giản do Google cung cấp:

<html>
<head>
	<title>Demo: Getting an email address using the Google+ Sign-in button</title>
	<!-- Include the API client and Google+ client. -->
	<script src = "https://plus.google.com/js/client:platform.js" async defer></script>
</head>
<body>
	<!-- Container with the Sign-In button. -->
	<div id="gConnect" class="button">
		<button class="g-signin"
			data-scope="email"
			data-clientid="841077041629.apps.googleusercontent.com"
			data-callback="onSignInCallback"
			data-theme="dark"
			data-cookiepolicy="single_host_origin">
		</button>
		<!-- Textarea for outputting data -->
		<div id="response" class="hide">
			<textarea id="responseContainer" style="width:100%; height:150px"></textarea>
		</div>
	</div>
</body>
<script>
	/**
	* Handler for the signin callback triggered after the user selects an account.
	*/
	function onSignInCallback(resp) {
		gapi.client.load('plus', 'v1', apiClientLoaded);
	}
	/**
	* Sets up an API call after the Google API client loads.
	*/
	function apiClientLoaded() {
		gapi.client.plus.people.get({userId: 'me'}).execute(handleEmailResponse);
	}
	/**
	* Response callback for when the API client receives a response.
	*
	* @param resp The API response object with the user email and profile information.
	*/
	function handleEmailResponse(resp) {
		var primaryEmail;
		for (var i=0; i < resp.emails.length; i++) {
			if (resp.emails[i].type === 'account') primaryEmail = resp.emails[i].value;
		}
		document.getElementById('responseContainer').value = 'Primary email: ' +
		primaryEmail + '\n\nFull Response:\n' + JSON.stringify(resp);
	}
</script>
</html>

Với ví dụ bên trên, bạn cần thay đổi thông tin clientid của bạn trong nút button nhé. Bạn xử lý thông tin trả về thông qua hàm handleEmailResponse.

Nếu bạn muốn tạo một nút bất kỳ sau đó xử lý sự kiện click chuột của người dùng thay vì sử dụng nút do Google tạo ra thì bạn tiếp tục làm như sau:

function hocwp_google_login_button() {
    ?>
    <button type="button" data-action="login-google" onclick="hocwp_google_login();" class="btn-google btn-social-login btn btn-large">
        <svg class="flicon-google flip-icon" viewBox="0 0 30 28" height="448" width="256" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" version="1.1">
            <path d="M 17.471,2c0,0-6.28,0-8.373,0C 5.344,2, 1.811,4.844, 1.811,8.138c0,3.366, 2.559,6.083, 6.378,6.083 c 0.266,0, 0.524-0.005, 0.776-0.024c-0.248,0.475-0.425,1.009-0.425,1.564c0,0.936, 0.503,1.694, 1.14,2.313 c-0.481,0-0.945,0.014-1.452,0.014C 3.579,18.089,0,21.050,0,24.121c0,3.024, 3.923,4.916, 8.573,4.916 c 5.301,0, 8.228-3.008, 8.228-6.032c0-2.425-0.716-3.877-2.928-5.442c-0.757-0.536-2.204-1.839-2.204-2.604 c0-0.897, 0.256-1.34, 1.607-2.395c 1.385-1.082, 2.365-2.603, 2.365-4.372c0-2.106-0.938-4.159-2.699-4.837l 2.655,0 L 17.471,2z M 14.546,22.483c 0.066,0.28, 0.103,0.569, 0.103,0.863c0,2.444-1.575,4.353-6.093,4.353 c-3.214,0-5.535-2.034-5.535-4.478c0-2.395, 2.879-4.389, 6.093-4.354c 0.75,0.008, 1.449,0.129, 2.083,0.334 C 12.942,20.415, 14.193,21.101, 14.546,22.483z M 9.401,13.368c-2.157-0.065-4.207-2.413-4.58-5.246 c-0.372-2.833, 1.074-5.001, 3.231-4.937c 2.157,0.065, 4.207,2.338, 4.58,5.171 C 13.004,11.189, 11.557,13.433, 9.401,13.368zM 26,8L 26,2L 24,2L 24,8L 18,8L 18,10L 24,10L 24,16L 26,16L 26,10L 32,10L 32,8 z"/>
        </svg>
        <span><?php hocwp_text('Đăng nhập bằng Google', __('Login with Google', 'hocwp')); ?></span>
    </button>
    <?php
}

function hocwp_google_login_script($args = array()) {
    if(is_user_logged_in()) {
        return;
    }
    $clientid = hocwp_get_value_by_key($args, 'clientid', hocwp_get_google_client_id());
    if(empty($clientid)) {
        _e('Please set your Google Client ID first.', 'hocwp');
        return;
    }
    ?>
    <script type="text/javascript">
        function hocwp_google_login() {
            var params = {
                clientid: '<?php echo $clientid; ?>',
                cookiepolicy: 'single_host_origin',
                callback: 'hocwp_google_login_on_signin',
                scope: 'email',
                theme: 'dark'
            };
            gapi.auth.signIn(params);
        }
        function hocwp_google_login_on_signin(response) {
            if(response['status']['signed_in'] && !response['_aa']) {
                gapi.client.load('plus', 'v1', hocwp_google_login_client_loaded);
            }
        }
        function hocwp_google_login_client_loaded(response) {
            var request = gapi.client.plus.people.get({userId: 'me'});
            request.execute(function(response) {
                hocwp_google_login_connected_callback(response);
            });
        }
        function hocwp_google_logout() {
            gapi.auth.signOut();
            location.reload();
        }
        function hocwp_google_login_connected_callback(response) {
            (function($) {
                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: hocwp.ajax_url,
                    data: {
                        action: 'hocwp_social_login_google',
                        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
}

Bạn khai báo 2 hàm PHP, một hàm là để hiển thị button, một hàm là để xử lý mã javascript. Bạn cũng có thể gộp lại thành một hàm hoặc xuất trực tiếp ra nơi bạn muốn hiển thị luôn chứ không cần thông qua bất kỳ hàm nào khác. Bên trong đoạn code ví dụ này mình có xử lý AJAX để tạo tài khoản trên WordPress, do vậy đoạn code chỉ mang tính chất tham khảo chứ không phải copy về là chạy được, các bạn cần thay đổi cho phù hợp với dự án của mình nhé. Chúc bạn thành công.

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

1 Comment
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
Giấy phép vệ sinh an toàn thực phẩm

ồ, đang tìm hiểu cái này, cám ơn admin hocwp nhé