HOME NEWS HOW-TO OPINION CULTURE ABOUT

Add Google+ Sign-In in 6 Easy Steps

Although many of the advantages of Google+ Sign In are for users, one of the best is that it's dead-simple to implement for developers - so much so that we at Google Plus Daily had it working on the day it was released. Here we'll walk through how to add Google+ Sign In to your website in just six easy steps:

Note: This guide will cover implementing client-side Google+ Sign In on a website using Javascript. However, the process for other languages, Android and iOS, is fairly similar, and all information can be found at https://developers.google.com/+/

1. Get API Access

Before doing anything, you'll need to get access to the Google+ API. To do this, head over to https://code.google.com/apis/console/. Select "Create" from the pull down menu and type a new project name, like "Awesome Google+ App."
Next, click on “Services” and select “Google+ API.” If you’re working on a Hangout App or using other Google APIs, select those too.
The last step here is to create an OAuth 2.0 Client. Select "API Access," then "Create OAuth 2.0 Client." Here you'll want to enter a Product Name and upload a Logo. Then Select "Web Application," then "More Options." Delete the sample under "Authorized Redirect URIs" and enter your web address under "Authorized JavaScript Origins."
Back on the API Access page you can grab your Client ID and Client Secret - write these down, because we'll be using them a lot!

2. Authentication: Adding a Sign-In Button

In order for users to sign in to your site, you’ll need a button for them to do so. Luckily, this process involves little more than some code copy and paste.

First add the Google+ Javascript right before your </body> tag. Google recommends doing this asynchronously for the sake of performance:
    <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:plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
    </script>
Next, you'll need to add the button itself. Here's the button code we're using here on GPD:
<button class="g-signin"
        data-scope="https://www.googleapis.com/auth/plus.login"
        data-clientid="YOUR_CLIENT_ID"
        data-callback="onSignInCallback"
        data-theme="dark"
        data-cookiepolicy="single_host_origin"
        data-requestvisibleactions="http://schemas.google.com/AddActivity"
        data-width="wide">
    </button>
There are a couple of things to note here. First, this can by a button, span, or div (we used a button). Regardless of which, the class must be "g-signin". CLIENTID is your client ID from Step 1. The data-requestvisibleactions attribute comes into play in step 5 when we go over app activities. If you're curious about some of the other button attributes, there's more information here.
We're almost there, but we need two more snippets of Javascript. One will handle Sign-Ins, the other Sign-Outs.

For Sign In, you'll want to somehow hide the button. After that you may want to display the user's name and profile picture in its place, we'll get to that in step 3.
function signinCallback(authResult) {
  if (authResult['access_token']) {
    // Successfully authorized
    document.getElementById('signinButton').setAttribute('style', 'display: none');

  } else if (authResult['error']) {
    // There was an error.
    // Possible error codes:
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatially log in the user
    // console.log('There was an error: ' + authResult['error']);
  }
}
Equally important is the code that allows users to disconnect your app if they so desire. You can use an onclick attribute on a "Disconnect" link to call this function:
<script type="text/javascript">
function disconnectUser(access_token) {
  var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' +
      access_token;

  // Perform an asynchronous GET request.
  $.ajax({
    type: 'GET',
    url: revokeUrl,
    async: false,
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(nullResponse) {
      // Do something now that user is disconnected
      // The response is always undefined.
    },
    error: function(e) {
      // Handle the error
      // console.log(e);
      // You could point users to manually disconnect if unsuccessful
      // https://plus.google.com/apps
    }
  });
}
// Could trigger the disconnect on a button click
$('#revokeButton').click(disconnectUser);
</script>
If you want to style your button, that's great - Google has some great information on what you can do and how to do it.

3. Using Account Details

Once a user has signed in, you'll want to be able to integrate various details from their account. In my opinion, the best way to get a feel for what kind of information you can get is by playing around with the Javascript Quickstart files provided by Google here, but here's a quick overview:

Note: Thanks to Googler +Ian Barber for pointing out that before using either of these code snippets, you must load the gapi code:
gapi.client.load('plus','v1', function(){ 
// once we get this call back, gapi.client.plus.* will exist
});

Profile Information

To access profile info, use the people.get API Method. So in Javascript we could get a profile picture and user name to a div with id="profile" like this:
profile: function(){
   var user = gapi.client.plus.people.get( {'userId' : 'me'} );   user.execute(function(profile)){
      $('#profile').append(
            $('<p><img src=\"' + profile.image.url + '\"></p>')      );
      $('#profile').append(
            $('<p>Hello ' + profile.displayName + '</p>')
      ); 
   });
}

Circle Information

You can access the people that a user has in circles and has chosen to share with you using the people.list method. However, there's no way to access the names of these circles. Here's an example, which shows all of the profile pictures of the people the user has in circles.
people: function() {
      var request = gapi.client.plus.people.list({
        'userId': 'me',
        'collection': 'visible'
      });
      request.execute(function(people) {
        for (var personIndex in people.items) {
          person = people.items[personIndex];
          $('#visiblePeople').append('<img src="' + 
          person.image.url + '">');
        }
      });
    }

4. Interactive Posts

One of the coolest features of Google+ Sign-In that no other network offers is Interactive Posts. Basically, they allow users to share post with a particular Call To Action button. So if it's a music streaming service, you get a listen button, if it's an ecommerce site, a buy button, etc. There are over 100 button types, so there's probably one that works for you. Here's the code for a basic button (though you could also use a <div> or <span>):
<button
  class="g-interactivepost"
  data-contenturl="https://plus.google.com/pages/"
  data-clientid="CLIENTID.apps.googleusercontent.com"
  data-cookiepolicy="single_host_origin"
  data-prefilltext="Engage your users today, create a Google+ page for your business."
  data-calltoactionlabel="CREATE"
  data-calltoactionurl="http://plus.google.com/pages/create">
  Share this post</button>
Each of the attributes is important here, so here's what they do:

  • data-contenturl is the url of the content that the user is sharing (probably the page the button is on).
  • data-clientid is your client id followed by .aps.googleusercontent.com
  • data-cookiepolicy should be "single_host_origin", unless you are using a specific URI here.
  • data-prefilltext is the text that will appear in the user's post. If you don't put anything, text will be added automatically from the contenturl, but this gives you some control.
  • data-calltoactionlabel allows us to select a button type. See the full list here: https://developers.google.com/+/features/call-to-action-labels
  • data-calltoactionurl is the URL you want to link to if the user presses the interactive button. So if it's a music streaming site and the calltoactionlabel is "LISTEN", this link should start playing the song that is being shared.
If you're also developing for mobile, you should look here for more information about deep-linking.

5. App Activities

Remember Google+ History? It's back, but in a slightly different way. Apps can create "activities" that users can access and share from their profiles. These are private to the user until they choose to share them, and are useful for things like listening activity, significant milestones, or (in GPD's case) tracking what article's you've read. While the Google+ Developer site only lists How-Tos for Android and iOS, the "moments" API from the History Developer Preview is still working for websites. Here's the code we're using to create App activities when someone reads an article:
function moment(){
 var postUrl = THE_PAGE_URL;
 var payload={
    'type': 'https://schemas.google.com/AddActivity',
    'target': {'url':postUrl}
 };
 
    var moment  = {
     'type':'http://schemas.google.com/AddActivity',
     'target':{
      'url':postUrl
    }
  };
 
 var args = {
  'path': '/plus/v1/people/me/moments/vault',
  'method': 'POST',
  'body': JSON.stringify(payload),
  'callback': function(response) {
   console.log(response);
  }
    };
 gapi.client.request(args);
}
Calling this function will create a moment in the user's history, which will appear like this:

6. Over-the-air App Installs

Have an Android app and a web app? It's easy to encourage users who sign in on their computers to install the app directly to their Android phones.
Luckily this process is two quick steps. First, obtain a client ID for your Android app the same way that we did for our website (but within the same project). Once you have the Client ID, all you have to do is add the following attribute to your sign-in button:
data-apppackagename = "YOUR_ANDROID_APP_PACKAGE"
Upon signing in, users will be given the option to install your Android app over the air to their devices. For more info, see the Google developers site.

And that's it!

Now your site is rocking the latest and greatest in social sign-in. To learn more about Google+ Sign In and watch a live demo, check out today's Google Developers Live session.

Did this guide work for you? Run into trouble somewhere? Let us know in the comments and we'll be sure to help you out!