Google Sign-In integration into your website

Google Sign-In integration into your website.

Google Sign-In integration into your website using below steps and code.

  • Before you can integrate Google Sign-In into your website, you need to create a project at Google Console, keep client ID and add in the Google sign-in API.

Create the project:

  • Now, enter your project name and make sure your project names must be between 4 and 30 characters and may only contain letters, numbers, spaces, and hyphens.
  • Once done the previous step next

Configure your OAuth client:

  • Specify the product name and it will be shown on the projects list.

Configure your OAuth client:

  • Here select the “Web browser” client type and specify the origin URI of your website.
  • After project creation is done.
  • Please keep of the client ID and Client secret key that was created or you can download Clinet Configuratoin file.
  • You will need the client ID to complete the next steps.
  • (For only server-side implementation you need Client secret key.)

Google API Console project:

  • Click on the “Credentials” tab and see your project details like Client ID, Client secret etc and also you can update app name etc and here you can update Authorized JavaScript origins, Authorized redirect URIs etc.
  • You are all set! You are ready to start development using below code steps:
  • Follow the below coding steps to integrate Google Sign-In into your website project.

STEP 1:

  • Include the Google Platform Library JS on your website page and copy below HTML code and paste it.
<script src="https://apis.google.com/js/platform.js?onload=onLoadGoogleCallback" async defer></script>

STEP 2:

  • Add a Google Sign-In button on your website page and copy below HTML code and paste it and
    For your information here is a element ID googleSignInBtn is attachClickHandler in onLoadGoogleCallback() method as below in step 3.
<a href="javascript:void(0);" id="googleSignInBtn">
	<img src="https://i1.wp.com/www.superwebsolution.com/wp-content/uploads/2020/05/Google-Sign-In-8.png" />
</a>

STEP 3:

  • Once clicked on Google Sign-In Button this function will be called onLoadGoogleCallback() and an open popup with a Google login page.
  • Here, in the below onLoadGoogleCallback() method you need to add your Google client ID.
<script type="text/javascript">
	function onLoadGoogleCallback(){
		try{
			gapi.load('auth2', function() {
				auth2 = gapi.auth2.init({
					client_id: '{ADD_YOUR_CLIENT_ID_HERE}.apps.googleusercontent.com', // HERE ADD YOUR GOOGLE CLIENT ID
					cookiepolicy: 'single_host_origin',
					scope: 'profile email' // HERE YOU CAN ADD MORE SCOPE
				});

				auth2.attachClickHandler(element, {}, function(googleUser) {
					$("#googleSignInBtn").addClass("btnLoading");
					var profile = googleUser.getBasicProfile();
					var socialData = {"name": profile.getName(), "email": profile.getEmail(), "id": profile.getId(), "imgUrl": profile.getImageUrl()};
					$.ajax({
						type: "POST",
						url: "authenticate.php", // HERE ADD YOUR SERVER SIDE FILE PATH AND SAVE USER DATA IN YOUR DATABASE.
						data: {"data-type": "social-auth", "data": socialData},
						success: function(responseJson) {
							try{
								if(responseJson.status == true){
									window.location.href = site_url+'profile/'+responseJson.res.user.user_id+'/'; // After Saved redirect to user profile page on your web page.
								} else {
									$("#googleSignInBtn").removeClass("btnLoading");
								}
							}catch(e){
								console.info("Error: onLoadGoogleCallback api try failed! "+e);
							}
						},
						error: function(xhr) {
							$("#googleSignInBtn").removeClass("btnLoading");
							console.info("Error: Google:social-auth api error!");
						}
					});
				}, function(error) {
					console.log('Google Sign-in error', error);
				});
			});
			element = document.getElementById('googleSignInBtn');
		}catch(e){
			console.info("Error: onLoadGoogleCallback try failed! "+e);
		}
	}
</script>
  • Once we got Google Sign-In success response this function will be called googleUser.getBasicProfile(); and get the logged-in user to Google login details example name, email, picture, etc which you will add in the scope.
    and you need to save logged-in user detail in your local database using the $.ajax() method.
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.

STEP 4:

  • Here, just an example of PHP server-side file (authenticate.php) code to save logged-in user detail in the local database and also you can write your logic according to your requirements.
<?php 
// First, connect to your database using your DB connection code and write your own logic as per your requirements...

$response = [];

if( isset($_POST['data-type']) && $_POST['data-type'] == "social-auth" && isset($_POST['data']) && $_POST['data'] != "" ) {
	// HERE are POST parameters example. Update below code and save in your local database using your DB SQL query etc.
	$_POST['data']['name']; 
	$_POST['data']['email']; 
	$_POST['data']['imgUrl']; 
	$_POST['data']['id'];
	
	// Once all done send SUCCESS response to ajax call...
	$response['status'] = true;
} else {
	// Here you can send FAILED response to ajax call like validation failed, unable to save in DB etc...
	$response['status'] = false;
}

header("Content-type: application/json; charset=utf-8");
echo json_encode($response);
die();
?>

STEP 6:

Simple code for Logout from Google Sign-In.

<a href="javascript:void(0);" onclick="javascript:GuserSignOut();">Logout</a>
<script type="text/javascript">
	function GuserSignOut() {
    var auth2 = gapi.auth2.getAuthInstance();
    auth2.signOut().then(function () {
      console.log('Google Sign-In user signed out successfully.');
    });
  }
</script>

Congratulations, you have added Google Sign-In to your website!

Any query? Please share your thoughts in the comments below. Glad to help you!
Thanks!
 
Was this page helpful? Do not forget to share this post!

Leave a Reply

Your email address will not be published. Required fields are marked *