How to Create a Google Plus Login for Your Website

In this day and age, many internet users are tired of having to go through the laborious process of filling in forms to gain access to websites they often frequent. Likewise signing up to a new website or service can be time consuming and problematic. A much quicker way to sign into a website is via an existing user account from a site like Google, Facebook or Twitter. This makes it easier for website owners and with a single click users gain access into a chosen site. So, just how easy is it to integrate a Google sign-in button into a website? Turns out, with a liberal dash of JavaScript, very easy! Here’s how it’s done…

First Steps

Before we start, jump to the Google Developers website, here. Keep this page bookmarked in case you want to expand upon what we cover. In this example, we’re going to get the user’s name and email address – typically what a website needs in order to grant user access – but you may want to delve deeper into Google’s API and extract more data from your users.

All you’ll need to complete this walk-through is a server so, if you have one we can begin. Firstly, create a HTML file and reference jQuery in the page just before the closing body tag, either locally or from a CDN. If you’re using a CDN (recommended) grab the link from here. I also use a CDN to grab Bootstrap’s style sheet – you don’t need to do this – but if you want to, grab the link from here and pop it in your document’s head.

Now we have to register our sign-in app with Google so jump to: https://developers.google.com/+/web/signin/#step_1_create_a_client_id_and_client_secret and follow steps one to four. By the time you’ve finished you’ll have an:

Creating the Sign-in Button

Ok, so now we’re ready to get started. First let’s create the Google+ sign in button. Copy the following CSS into your document head:

<style>
#gSignInWrapper {
    width:165px;
    float:left
}
#customBtn {
    display: inline-block;
    background: #dd4b39;
    color: white;
    width: 165px;
    border-radius: 5px;
    white-space: nowrap;
    cursor:pointer
}
#customBtn:hover {
    background: #e74b37;
    cursor: hand;
}
span.label {
    font-weight: bold;
}
span.icon {
    background: url('https://google-developers.appspot.com/+/images/branding/btn_red_32.png') transparent 5px 50% no-repeat;
    display: inline-block;
    vertical-align: middle;
    width: 35px;
    height: 35px;
    border-right: #bb3f30 1px solid;
}
span.buttonText {
    display: inline-block;
    vertical-align: middle;
    padding-left: 7px;
    font-size: 14px;
    font-weight: bold;
    font-family: 'Roboto',arial,sans-serif;
}
#revokeButton {
    display:none
}
</style>

Now copy this HTML into your document’s body:

<p id="name">User:</p>

<p id="email">Email:</p>

<div id="gSignInWrapper"><span class="label">Sign in with:</span>
<div class="customGPlusSignIn" id="customBtn"><span class="buttonText">Login Google+</span></div>
</div>

<button class="btn btn-classic" id="revokeButton">Revoke</button>

That’s all the HTML and CSS we’ll need! Once this is done we need to use some JavaScript to render the Google Plus button, so copy the following into your document body, beneath the jQuery script:

<script>
function googlePlus() {

	var po = document.createElement( 'script' );
	po.type = 'text/javascript'; 
	po.async = true;
	po.src = 'https://apis.google.com/js/client:plusone.js?onload=render';
	var s = document.getElementsByTagName( 'script' )[0];
	s.parentNode.insertBefore( po, s );

}

function render() {

	gapi.signin.render( 'customBtn', {
		//'callback': 'signinCallback',
		'clientid': 'YOURPROJECTNUMBER.apps.googleusercontent.com',
		'cookiepolicy': 'single_host_origin',
		'requestvisibleactions': 'http://schemas.google.com/AddActivity',
		'scope': 'https://www.googleapis.com/auth/userinfo.email'
	});

}
</script>

There’s a couple of things to note from this. Firstly, the “onload=render” GET variable from the script created in the googlePlus() function defines what is called when the script loads (gapi.signin.render). This function renders the button and takes two arguments – the first is the ID of the Google Plus button, the second is an object containing data from your app / project. You need to replace the clientid value – “YOURPROJECTNUMBER” – with the number given to you in the dashboard of the developer console (just go back to https://code.google.com/apis/console/ if you didn’t make a note of it). Finally, notice how the “scope” attribute is making a request for the user’s info, specifically the email.

Once all the above has been added to your HTML, upload it to your server and open the page. You should see something similar to this (obviously you can style this further later):

the google plus login button

Handling the Sign-in

Ok, back to the JavaScript you just added. The object passed into the render function has the “callback” key / attribute commented out. Uncomment that so we have a function to be called when a user signs in to our app (change the name of it to whatever you like.) Now let’s add this callback to our script. Add the following to the script:

function signinCallback( authResult ) {

	if ( authResult[ 'access_token'] ) {

		gapi.auth.setToken( authResult );
		gapi.client.load( 'plus', 'v1', function() {
			getName();
		});

        getEmail();    
		$( '#revokeButton' ).show().data( 'loggedInWith', 'g+' ).text( 'Revoke G+' );
		$( '#gSignInWrapper' ).css( 'display', 'none' );
	} 
	else if ( authResult[ 'error' ] ) {
		console.log( 'Sign-in state: ' + authResult[ 'error' ] );
	}

}

A few things to note from this function – firstly, it’s passed an “authResult” object which holds the details of the authorisation. If it contains an access token property then the app is authorised, the token is registered with the app and we can access the user’s name and their email address by making a call to Google’s API (which we’ll come to in a minute). Once signed in, we don’t need the login button any more so we can hide it and show the “revoke access” button – as required in the Google’s Terms and Conditions.

You’ll notice that we’ve added a data attribute – “loggedInWith” and then “g+” as the value – to the revoke button. This is so we can use the button to handle other revoke access options, from Facebook or Twitter for example. We can test the data value to see which vendor a user signed in with, and then provide the appropriate method to revoke the app’s permissions.

Revoking App Permission

Ok, nearly done. Let’s now create the function to handle the revoke action. Copy the following beneath what we have so far in our script:

function disconnectUser( access_token ) {

	var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + access_token;

	$.ajax({
		type: 'GET',
		url: revokeUrl,
		async: false,
		contentType: "application/json",
		dataType: 'jsonp',
		success: function ( nullResponse ) {
			$( '#revokeButton' ).hide();
			$( '#gSignInWrapper' ).show();
			alert( 'This app has had its G+ access revoked' );
		},
		error: function ( e ) {
			console.log( e );
		}
	});

}

From this you can see that we pass in the user’s access token and append it to the URL in the AJAX call. In the “success” callback function we’ve added an alert and shown / hidden the Google Plus login button and revoke button respectively. You can perform whatever actions you want here.

Getting the User’s Name and Email Address

So the final thing to do is add the functions to retrieve the user’s name and email address and add the handler for when the revoke button is used. Copy the following to the bottom of your script:

function getName() {

	var request = gapi.client.plus.people.get( { 'userId': 'me' } );
	request.execute( function ( resp ) {
		var username = String( resp.displayName ).split( ' ' );
		$( '#name' ).text( 'User: ' + username[0] + ' ' + username[1] );
	});	

}

function getEmail(){

	gapi.client.load( 'oauth2', 'v2', function() {
		var request = gapi.client.oauth2.userinfo.get();
		request.execute( function ( resp ) {	

			if ( resp[ 'email' ] ) {
				$( '#email' ).text( 'Email ' + resp[ 'email' ] );
			}

		});
	});

}

$( '#revokeButton' ).click( function() {

	if( $( this ).data( 'loggedInWith' ) === 'g+' ) {		
		disconnectUser( gapi.auth.getToken().access_token );		
	}

	$( '#name' ).text( 'Name: ' );
	$( '#email' ).text( 'Email: ' );

});

In the “getName” function we make a request to get the user’s name from Google’s API and create a variable to hold the user’s name. We’ve used the split method to separate first name and last – if you don’t need the two separated then you can remove that bit of code and just grab the username in its entirety. The “getEmail” function is similar, as it makes a call to the API and returns an email address. Both of these functions update the page with these respective details. Finally the revoke button handler checks to see if the user has logged in with Google Plus and calls the disconnect user function, passing in the user’s access token. And that’s it, users can now sign into your website with Google Plus.

Upon clicking the sign in button the user will receive a prompt:

google plus app authorize window

Once the app has been authorized the user will see this (but obviously with their details, not mine!):

upon successfully signing in

Hopefully you found this blog useful – feel free to let us know how you get on with the above by tweeting us at @DigitalandWise. For more information about our development services please ring the office on 0161 946 3851. Happy coding!

By 2018, 42.4% of world’s population will be plugged into the internet, with around 3.6 bn people able to access it at least once a month.
RT : What is a ? It attaches rich photos, videos and media experiences to Tweets. http:/…