Here is a tutorial on how to add Google login to your website:
1. Go to the Google Cloud Console.
2. Click the project drop-down and select or create the project that you want to use for the Google login feature.
3. Click the hamburger menu and select APIs & Services > Credentials.
4. On the Credentials page, click Create credentials > OAuth client ID.
5. Select Web application as the application type.
6. In the Authorized JavaScript origins field, enter the URL of your website.
7. In the Authorized redirect URIs field, enter the URL of the page on your website where you want to handle the response from the Google login.
8. Click Create.
9.On the OAuth client window that appears, note the client ID and client secret. You will need these in the next step.
10.Add the following script to the head of your login page:
<script src="https://apis.google.com/js/api.js"></script>
<script>
function onSuccess(googleUser) {
// Get the Google user profile data
var profile = googleUser.getBasicProfile();
// Get the ID token
var id_token = googleUser.getAuthResponse().id_token;
// Send the token to your server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'YOUR_SERVER_URL');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + id_token);
}
function onFailure(error) {
console.log(error);
}
function renderButton() {
gapi.signin2.render('my-signin2', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
</script>
11.Add a div element to your login page where you want the Google login button to appear:
<div id="my-signin2"></div>
12.Add the following script to the head of your login page, after the script you added in step 10:
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'YOUR_CLIENT_ID.apps.googleusercontent.com',
});
renderButton();
});
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=start" async defer></script>
13 .Replace YOUR_CLIENT_ID with the client ID that you obtained in step 9.
14 .Replace YOUR_SERVER_URL with the URL of your server-side script that will handle the login request.
15 .Your Google login feature is now ready to use. When a user clicks the login button, they
0 Comments