Google Login with Javascript API

The PHP version of this tutorial is located at Login with Google using PHP.

In this tutorial Login with Google functionality is implemented through Javascript. A user can login with his Google account, and your application can get details such as name, id, gender, picture & email.

Google provides a Javascript SDK to make API calls. Any API call that can be done with PHP can also be done through Javascript.

I must say, implementing Google API calls with Javascript is far more simpler than implementing it through PHP.

Demo

You can download sample codes with instructions towards the end of the tutorial.

Setting a Google Application

Before using the Google Javascript SDK, you need to create a Google API Key and Google Application Client ID

  1. Go to Google API Console
  2. If you have not created a project, create a project by clicking "Select a project" (at the top), and then clicking on the "+" button in the lightbox. In the next screen enter your project name, and agree with T&C.
  3. After the project is created, select the created project from the top dropdown.
  4. Click the Library tab on the left. Search for "Google+ API" and enable it.
  5. Now click on Credentials tab on the left. In the next screen click on "OAuth consent screen". Fill out the mandatory fields. Save it.
  6. Now click on the "Credentials" tab (just beside "OAuth consent screen"). In the screen, click on "Create credentials". Choose "API key" as the type.
  7. After the API key is created you can restrict it to your own website domain
  8. Now that we have an API key, we need a Google application Client ID. Once again click on the "Credentials" tab. In the screen, click on "Create credentials". Choose "OAuth Client ID" as the type.
  9. In the next screen fill out the name. The Application type should be "Web application"
  10. Add your website domain in the section Authorised JavaScript origins (same url as one entered while creating API key). You can even add a localhost url if you want.
  11. You can leave out Authorised redirect URIs as blank. Click on the Create button.
  12. On success you will get the App Client ID. Save it as it will be required later.

Anatomy of Google Javascript API Calls

Before proceeding forward it is better you see the Promise based anatomy of a Google Javascript API call.

some_api_call( { parameter: some_parameter }).then(
	function(success) {
		
	},
	function(error) {
		
	}
);

Google Javascript API calls are Promise (like) based. Javascript Promises are just like callbacks, but instead of writing it somewhere else in the code it is written there itself using a then. In simple words it means after the API call is executed then do the following.

2 parameters are passed to the Google API Promise. The first parameter is a callback function for success - it will be executed if the API call is successful. The second parameter is a callback function for error - it will be executed if the API call fails.

Step 1 - Initialize the Google Javascript SDK

The first thing to do it to include the Google Javascript SDK in your webpage.

<script async defer src="https://apis.google.com/js/api.js" onload="this.onload=function(){};HandleGoogleApiLibrary()" onreadystatechange="if (this.readyState === 'complete') this.onload()"></script>

Note that this is asynchronous, and a function HandleGoogleApiLibrary will be called once the script is loaded. You can name any function as per your choice, only thing is that it should be present in the code.

The function HandleGoogleApiLibrary initializes the Google Javascript SDK :

// Called when Google Javascript API Javascript is loaded
function HandleGoogleApiLibrary() {
	// Load "client" & "auth2" libraries
	gapi.load('client:auth2',  {
		callback: function() {
			// Initialize client & auth libraries
			gapi.client.init({
		    	apiKey: 'YOUR_GOOGLE_API_KEY',
		    	clientId: 'YOUR_GOOGLE_API_CLIENT_ID',
		    	scope: 'https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/plus.me'
			}).then(
				function(success) {
			  		// Libraries are initialized successfully
		  			// You can now make API calls
				}, 
				function(error) {
					// Error occurred
					// console.log(error) to find the reason
			  	}
			);
		},
		onerror: function() {
			// Failed to load libraries
		}
	});
}

For user login and getting profile information we need 3 Google scopes - https://www.googleapis.com/auth/userinfo.profile, https://www.googleapis.com/auth/userinfo.email & https://www.googleapis.com/auth/plus.me.

Remember, this process is same for all Google APIs. So if you trying to get the list of user's calendars, you would just include the scope for Google Calendar https://www.googleapis.com/auth/calendar.

Step 2 - Implement the Login API

After the Javascript SDK is initialized, you can start making API calls. The first one is the login API call. This API will be typically be executed when the user clicks on the button like "Login with Google" in your application. This API call would open a Google login popup where user can enter his credentials, and give authorization to your application.

Always call this API on a click event, otherwise browser will block the login popup.

// Call login API on a click event
$("#google-login-button").on('click', function() {
	// API call for Google login
	gapi.auth2.getAuthInstance().signIn().then(
		function(success) {
			// Login API call is successful	
		},
		function(error) {
			// Error occurred
			// console.log(error) to find the reason
		}
	);
});

Step 3 - Get User Information with API

After the user has been logged-in, you can fetch his profile information with an API call.

// API call to get user profile information
gapi.client.request({ path: 'https://www.googleapis.com/plus/v1/people/me' }).then(
	function(success) {
		// API call is successful

		var user_info = JSON.parse(success.body);

		// user profile information
		console.log(user_info);
	},
	function(error) {
		// Error occurred
		// console.log(error) to find the reason
	}
);

In Short

Make sure you doing the below sequentially :

  1. Add the Google Javascript SDK
  2. Initialize the library with your API keys
  3. Make the login API call (on a click event)
  4. Get the profile information

Download Codes with Instructions

Download

I'm available for freelancing
If you've liked this article, you'll probably like my code too.

From short code snippets to complete web applications, I code in Javascript & PHP
Low Prices from $20, Fast Delivery Time
Login with Google using PHP
I'm available for freelancing
If you've liked this article, you'll probably like my code too.

From short code snippets to complete web applications, I code in Javascript & PHP
Low Prices from $20, Fast Delivery Time