Login with Google Plus Javascript API Example

In this tutorial, I have covered how to implement Login with Google plus using Google JavaScript API. Follow the steps to add Login In with Google + functionality to your website.
Login with Google Plus Javascript API Demo

Step 1). You need to get Google Browser API key from https://console.developers.google.com

Follow this : How to get Google API key
Note: You need to enable “Google+ API” in your project. You need to add your domain to Client “Javascript Origins”

Step 2). Add Asynchronous Google client JS to HTML. (before </body> tag)

<script type="text/javascript">
      (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
</script>

After script is loaded, onLoadCallback() callback is called.

Step 3) Add a function onLoadCallback() in JavaScript. In the function set Google API key and load Google + API.

function onLoadCallback()
{
	gapi.client.setApiKey('YOUR_API_KEY'); //set your API KEY
	gapi.client.load('plus', 'v1',function(){});//Load Google + API
}

 

Step 4) Add Login and Logout buttons to your page

<input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />
<div id="profile">User Information</div>

 

Step 5) Implement login(), logout() functions.

function login() 
{
  var myParams = {
    'clientid' : 'YOUR_CLIENT_ID.apps.googleusercontent.com', //You need to set client id
    'cookiepolicy' : 'single_host_origin',
    'callback' : 'loginCallback', //callback function
    'approvalprompt':'force',
    'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
  };
  gapi.auth.signIn(myParams);
}

clientid -> you need to get this from Google Console
callback -> callback function is called when sign in request is done.
approvalprompt -> To show Request approval every time
scope -> Space separated list of oauth scopes

Response from the signIn request in the below format:

{
    "state": "",
    "access_token": "XXXXXXXXXXXXXXXX",
    "token_type": "Bearer",
    "expires_in": "3600",
    "code": "XXXXXXXX",
    "scope": "",
    "id_token": "XXXXXXXXXXXX",
    "authuser": "0",
    "num_sessions": "1",
    "prompt": "consent",
    "session_state": "XXXXXXXXX",
    "client_id": "XXXXXX.apps.googleusercontent.com",
    "g_user_cookie_policy": "single_host_origin",
    "cookie_policy": "single_host_origin",
    "response_type": "code token id_token gsession",
    "issued_at": "1395298062",
    "expires_at": "1395301662",
    "g-oauth-window": {},
    "status": {
        "google_logged_in": true,
        "signed_in": true,
        "method": "PROMPT"
    }
}

Step 6: Add loginCallback() function and check the response whether user is successfully logged in or not

function loginCallback(result)
{
	if(result['status']['signed_in'])
	{ 
		alert("Login Success");
	}	

}

Step 6) Once the login is successful, You can get the user profile and email using the code

var request = gapi.client.plus.people.get(
{
    'userId': 'me'
});
request.execute(function (resp)
{
    var email = '';
    if(resp['emails'])
    {
        for(i = 0; i < resp['emails'].length; i++)
        {
            if(resp['emails'][i]['type'] == 'account')
            {
                email = resp['emails'][i]['value'];
            }
        }
    }

    var str = "Name:" + resp['displayName'] + "<br>";
    str += "Image:" + resp['image']['url'] + "<br>";
    str += "<img src='" + resp['image']['url'] + "' /><br>";

    str += "URL:" + resp['url'] + "<br>";
    str += "Email:" + email + "<br>";
    document.getElementById("profile").innerHTML = str;
});

Response for the gapi.client.plus.people.get() API is:

{
    "id": "gapiRpc",
    "result":
    {
        "kind": "plus#person",
        "etag": "XXXXX",
        "gender": "male",
        "emails": [
        {
            "value": "[email protected]",
            "type": "account"
        }],
        "objectType": "person",
        "id": "118255177648356108079",
        "displayName": "Ravishanker Kusuma",
        "name":
        {
            "familyName": "Kusuma",
            "givenName": "Ravishanker"
        },
        "tagline": "Language Is Not  A Barrier.",
        "aboutMe": "Developer.u003cbr /u003e",
        "url": "https://plus.google.com/+RavishankerKusuma",
        "image":
        {
            "url": "https://lh3.googleusercontent.com/-UJpaKCFBZ2U/AAAAAAAAAAI/AAAAAAAAAHQ/pN0x8us0DtA/photo.jpg?sz=50"
        },

        "isPlusUser": true,
        "language": "en",
        "ageRange":
        {
            "min": 21
        },
        "circledByCount": 219,
        "verified": false,
        "cover":
        {
            "layout": "banner",
            "coverPhoto":
            {
                "url": "https://lh5.googleusercontent.com/-SDKIkp26kNY/UcojL0T3pBI/AAAAAAAABkU/ktL4c0hdtXE/s630-fcrop64=1,200d2f7adf16d084/%25C2%25A9%2BBrian%2BMatiash_20110102-IMG_8104-Edit.jpg",
                "height": 626,
                "width": 940
            },
            "coverInfo":
            {
                "topImageOffset": 0,
                "leftImageOffset": 0
            }
        },
        "domain": "hayageek.com"
    }
}

Step 7). Add logout() function

function logout()
{
	gapi.auth.signOut();
	location.reload();
}

Putting All Together: Login With Google plus JavaScript example code

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button"  value="Login" onclick="login()" />
<input type="button"  value="Logout" onclick="logout()" />

<div id="profile"></div>
<script type="text/javascript">

function logout()
{
	gapi.auth.signOut();
	location.reload();
}
function login() 
{
  var myParams = {
    'clientid' : 'PUTYOUR_CLIENT_ID.apps.googleusercontent.com',
    'cookiepolicy' : 'single_host_origin',
    'callback' : 'loginCallback',
    'approvalprompt':'force',
    'scope' : 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read'
  };
  gapi.auth.signIn(myParams);
}

function loginCallback(result)
{
    if(result['status']['signed_in'])
    {
        var request = gapi.client.plus.people.get(
        {
            'userId': 'me'
        });
        request.execute(function (resp)
        {
            var email = '';
            if(resp['emails'])
            {
                for(i = 0; i < resp['emails'].length; i++)
                {
                    if(resp['emails'][i]['type'] == 'account')
                    {
                        email = resp['emails'][i]['value'];
                    }
                }
            }

            var str = "Name:" + resp['displayName'] + "<br>";
            str += "Image:" + resp['image']['url'] + "<br>";
            str += "<img src='" + resp['image']['url'] + "' /><br>";

            str += "URL:" + resp['url'] + "<br>";
            str += "Email:" + email + "<br>";
            document.getElementById("profile").innerHTML = str;
        });

    }

}
function onLoadCallback()
{
	gapi.client.setApiKey('PUT_YOUR_KEY');
	gapi.client.load('plus', 'v1',function(){});
}

    </script>

<script type="text/javascript">
      (function() {
       var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
       po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
</script>

</body>
</html>

Reference: Google Documentation