VIDEO
01. Tạo ứng dụng trên Google Developer Console - Truy cập vào Client Page [Google Developer Console ].
- Tạo một dự án mới và kích hoạt dịch vụ "Google Sign-In ".
- Tạo OAuth 2.0 Client ID và cung cấp URL chuyển hướng sau khi xác thực .
02. Thêm thư viện Google API vào trang web của bạn - Thêm thư viện Google API vào trang HTML của bạn:
< script src = "https://apis.google.com/js/platform.js" async defer ></ script >
< meta name ="google-signin-client_id" content ="YOUR_CLIENT_ID.apps.googleusercontent.com" >
03. Tạo button để đăng nhập với Google - Thêm một button vào trang web của bạn:
< div class ="g-signin2" data-onsuccess ="onSignIn" ></ div >
04. Xử lý thông tin đăng nhập trong JavaScript - Thêm đoạn mã JavaScript để xử lý sự kiện đăng nhập thành công :
function onSignIn ( googleUser ) {
var profile = googleUser . getBasicProfile ();
console . log ( 'ID: ' + profile . getId ()); // Do not send to your backend! Use an ID token instead.
console . log ( 'Name: ' + profile . getName ());
console . log ( 'Image URL: ' + profile . getImageUrl ());
console . log ( 'Email: ' + profile . getEmail ()); // This is null if the 'email' scope is not present.
}
05. Đăng xuất - Thêm nút đăng xuất và xử lý sự kiện đăng xuất:
< a href ="#" onclick =" signOut ();" > Sign out</ a >
< script >
function signOut () {
var auth2 = gapi . auth2 . getAuthInstance ();
auth2 . signOut (). then ( function () {
console . log ( 'User signed out.' );
});
}
</ script >
Bạn có thể tìm thêm tài liệu chi tiết tại [hướng dẫn của Google ]
Ví dụ toàn bộ mã nguồn trong 01 file html:
p/S: trang web chứa đoạn mã này + trang redirect -> Google bắt buộc
01 - Phải là https
02 - Tên miền cả 02 trang phải matching (trùng khớp cùng 01 tên miền)
03 - K có dấu / kết thúc link
-> xem ví dụ mình đã chèn trong thực tế ở đây (mình chèn dưới chữ By AI Copilot )
<! DOCTYPE html >
< html lang ="vi" >
< head >
< meta charset ="UTF-8" >
< meta name ="viewport" content ="width=device-width, initial-scale=1.0" >
< title > Tích hợp Google Login</ title >
< script src = "https://accounts.google.com/gsi/client" async defer ></ script >
< script >
function handleCredentialResponse ( response ) {
console . log ( "Encoded JWT ID token: " + response . credential );
// Ở đây bạn có thể xử lý thông tin đăng nhập của người dùng
}
window . onload = function () {
google . accounts . id . initialize ({
client_id : "880462642610-6vunc8op20uajgltq5gfbn23fuba8vtl.apps.googleusercontent.com" ,
callback : handleCredentialResponse
});
google . accounts . id . renderButton (
document . getElementById ( "buttonDiv" ),
{ theme : "outline" , size : "large" } // Tùy chọn nút đăng nhập
);
google . accounts . id . prompt (); // Hiển thị prompt tự động ở góc phải
console. log ( document . getElementById ( "buttonDiv" ))
}
</ script >
</ head >
< body >
< h3 > Tích hợp Google Login vào trang web</ h3 >
< div id ="buttonDiv" ></ div >
</ body >
</ html >
Không có nhận xét nào:
Đăng nhận xét