Ví dụ đăng nhập với Google và lấy thông tin người dùng

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

Đoạn code ví dụ đăng nhập với tài khoản Google thông qua Google OAuth 2.0 trên nền tảng Javascript. Kết nối tài khoản WordPress với tài khoản Google, sử dụng có kèm theo jQuery, mục đích của đoạn code này là để lấy thông tin người dùng từ tài khoản Google của họ, cho phép kết nối và đăng nhập thông qua tài khoản mạng xã hội Google Plus.

Đăng nhập với Google OAuth 2.0 trên Javascript

Chú ý: Nội dung bài viết chỉ mang tính chất tham khảo, phục vụ cho mục đích nội bộ. Bạn cần phải thay đổi và chỉnh sửa lại nhiều chỗ thì mới có thể hoạt động được.

global $hocwp_theme;
$social = isset( $hocwp_theme->options['social'] ) ? $hocwp_theme->options['social'] : '';
if ( ! is_array( $social ) ) {
	$social = array();
}
$api_key   = HT()->get_value_in_array( $social, 'google_api_key' );
$client_id = HT()->get_value_in_array( $social, 'google_client_id' );
if ( ! empty( $api_key ) && ! empty( $client_id ) ) {
	$args = array(
		'load'     => true,
		'callback' => 'hocwp_theme_connect_google'
	);
	HT_Util()->load_google_javascript_sdk( $args );
	?>
	<script>
        var apiKey = "<?php echo $api_key; ?>";
        var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"];
        var clientId = "<?php echo $client_id; ?>";
        var scopes = "profile";
        var authorizeButton = document.getElementById("connect-google");
        var signInParams = {scope: "https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/user.addresses.read https://www.googleapis.com/auth/user.birthday.read https://www.googleapis.com/auth/user.emails.read https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile"};

        function updateSigninStatus(isSignedIn) {
            if (isSignedIn) {
                makeApiCall();
            }
        }

        function handleAuthClick() {
            var connect = parseInt(authorizeButton.getAttribute("data-connect"));
            authorizeButton.className += " disabled";
            console.log(connect);
            if (0 === connect) {
                authorizeButton.innerHTML = authorizeButton.getAttribute("data-loading-text");
                gapi.auth2.getAuthInstance().signIn(signInParams);
            } else {
                (function ($) {
                    var element = $(authorizeButton),
                        container = element.parent(),
                        clone = element.clone();
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: hocwpTheme.ajaxUrl,
                        data: {
                            action: "hocwp_theme_connect_social",
                            type: "google",
                            social_data: '',
                            disconnect: 1,
                            id: ''
                        },
                        success: function (response) {
                            if (response.success) {
                                element = $(clone);
                                element.text(element.attr("data-text"));
                                element.attr("data-connect", 0);
                                container.html(element);
                                authorizeButton = document.getElementById("connect-google");
                                element.on("click", function () {
                                    connect = parseInt(element.attr("data-connect"));
                                    if (0 === connect) {
                                        container = element.parent();
                                        clone = element.clone();
                                        element.addClass("disabled");
                                        element.text(element.attr("data-loading-text"));
                                        gapi.auth2.getAuthInstance().signIn(signInParams).then(function () {
                                            updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
                                        });
                                    } else {
                                        handleAuthClick();
                                    }
                                });
                            }
                        },
                        complete: function () {
                            container.find(element).removeClass("disabled");
                        }
                    });
                })(jQuery);
            }
        }

        function initClient() {
            gapi.client.init({
                apiKey: apiKey,
                discoveryDocs: discoveryDocs,
                clientId: clientId,
                scope: scopes
            }).then(function () {
                gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

                updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

                authorizeButton.onclick = handleAuthClick;
            });
        }

        function makeApiCall() {
            gapi.client.people.people.get({
                resourceName: "people/me",
                personFields: "names,birthdays,genders,addresses,emailAddresses,phoneNumbers,photos"
            }).then(function (response) {
                if (response.status === 200) {
                    var body = JSON.parse(response.body),
                        userID = body.resourceName.replace("people/", "");
                    (function ($) {
                        var element = $(authorizeButton),
                            container = element.parent();
                        $.ajax({
                            type: "POST",
                            dataType: "json",
                            url: hocwpTheme.ajaxUrl,
                            data: {
                                action: "hocwp_theme_connect_social",
                                type: "google",
                                social_data: response.result,
                                disconnect: 0,
                                id: userID
                            },
                            success: function (response) {
                                if (response.success) {
                                    element.text(element.attr("data-disconnect-text"));
                                    element.attr("data-connect", 1);
                                    if (response.data.html) {
                                        container.prepend(response.data.html);
                                    }
                                } else {
                                    element.text(element.attr("data-text"));
                                }
                            },
                            complete: function () {
                                element.removeClass("disabled");
                            }
                        });
                    })(jQuery);
                }
            });
        }

        function hocwp_theme_connect_google() {
            gapi.load("client:auth2", initClient);
        }
	</script>
	<?php
}

Các bài viết hướng dẫn về cách đăng nhập bằng tài khoản Google được chia sẻ rất nhiều trên mạng, bạn cũng có thể xem qua tài liệu hướng dẫn OAuth 2.0 dành cho trang web phiên bản gốc trên trang chủ của Google.

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

0 Comments
Phản hồi nội tuyến
Xem tất cả bình luận