Google Wallet Instant Buy APIs

Notice
To get production access, sign up using the Instant Buy interest form. Then, integrate Instant Buy with your Android, mobile web, or web app as described in these pages.

Google Sign-In for Instant Buy

You can improve the purchase and registration flow for your users by using Google+ Sign-In. With Google+ Sign-In, you can get the user's basic profile information and use this information to reduce the steps a user must take to create an account and buy from you.

Contents

Google+ Sign-In in your payment flow

To add Google+ Sign-In in your payment flow, you'll display a "Sign in with Google" button on your login page. If the user is already signed into a Google account on their device, then a single click on this button signs the user into your app with no need to enter a username or password.

As shown below in a mobile web app, the first time a user signs into your app with this button, they'll need to approve the scopes you're requesting. As long as the user doesn't explicitly revoke access, you won't be required to display the permissions screen again.

1

Per the Instant Buy UI Branding Requirements, the sign-in button should be above the fold as shown.

2

In the case of first-time authorization of your app, the button click first opens a permissions dialog that allows the user to approve the requested scopes.

Users can sign in with Google and avoid filling out any registration or checkout information. Additionally, Google+ Sign can simplify your account creation flows. Approved Google+ profile access gives you most of the data you're likely to need to create user accounts, and you can easily prompt users for any additional information that you need.

Adding a sign-in button

To implement Google+ Sign-In, you'll need to add a Google sign-in button to your app. The steps to add a button are different for Android and web apps, though the key to both procedures is to add the basic Google profile scope as well as the specific Wallet scope, https://www.googleapis.com/auth/paymentssandbox.make_payments or https://www.googleapis.com/auth/payments.make_payments.

Android

For Android Instant Buy integrations, you'll need to activate the Google+ API for your app in the Google Developers Console and add a "Sign in with Google" button to your app.

Activate the Google+ API

To activate an API for your project, do the following:

  1. Go to the Google Developers Console.
  2. Select a project.
  3. In the sidebar on the left, select APIs & auth.
  4. In the displayed list of available APIs, find the one you want to activate, and set its status to ON.

Add the Google+ Sign-In button to your app

  1. Add the SignInButton in your application's layout:

    <com.google.android.gms.common.SignInButton
        android:id="@+id/sign_in_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
  2. Initialize mPlusClient with the requested visible activities in your Activity.onCreate handler.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPlusClient = new PlusClient.Builder(this, this, this)
            .setScopes(Scopes.PLUS_PROFILE, "profile", "https://www.googleapis.com/auth/paymentssandbox.make_payments")
            .build();
    }
    
  3. In the Android activity, register your button's OnClickListener to sign in the user when clicked:

    findViewById(R.id.sign_in_button).setOnClickListener(this);
    
  4. After the user has clicked the sign-in button, you should start to resolve any connection errors held in mConnectionResult. Possible connection errors include prompting the user to select an account, and granting access to your app.

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.sign_in_button && !mPlusClient.isConnected()) {
            if (mConnectionResult == null) {
                mConnectionProgressDialog.show();
            } else {
                try {
                    mConnectionResult.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
                } catch (SendIntentException e) {
                    // Try connecting again.
                    mConnectionResult = null;
                    mPlusClient.connect();
                }
            }
        }
    }
    
  5. When the user has successfully signed in, your onConnected handler will be called. At this point, you are able to retrieve the user’s account name or make authenticated requests.

    @Override
    public void onConnected(Bundle connectionHint) {
        mConnectionProgressDialog.dismiss();
        Toast.makeText(this, "User is connected!", Toast.LENGTH_LONG).show();
    }
    

For more information about Google+ Sign-in on Android, see the Google+ API documentation.

Mobile Web

When your users sign in with Google, your app gets an access token, which you can use to make calls to the Google+ APIs on behalf of your user while the user is active on your site.

Adding a Google+ Sign-In button to your page requires you to:

  1. Create a client ID and client secret.
  2. Include the Google+ script on your page.
  3. Add the button to your page.
  4. Handle the sign in with a JavaScript callback.

Step 1: Create a client ID and client secret

To create a client ID and client secret, create a Google APIs Console project, enable the Google+ API, create an OAuth 2.0 client ID, and register your JavaScript origins:

To register a new application, do the following:

  1. Go to the Google Developers Console.
  2. Select a project, or create a new one.
  3. In the sidebar on the left, select APIs & auth. In the displayed list of APIs, make sure the Google Wallet Instant Buy status is set to ON.
  4. In the sidebar on the left, select Registered apps.
  5. At the top of the page, select Register App.
  6. Fill out the form and select Register.

Register the origins where your app is allowed to access the Google APIs. The origin is the unique combination of protocol, hostname, and port. You can enter multiple origins to allow for your app to run on different protocols, domains or subdomains. Wildcards are not allowed.

  1. Expand the OAuth 2.0 Client ID section.
  2. In the Web origin field, enter your origin:
    http://localhost:8080
    
    Press ENTER to save your origin. You can then click the + symbol to add additional origins.
  3. Note or copy the client ID and client secret that your app will need to use to access the APIs.

Step 2: Include the Google+ script on your page

Just before your </body> tag, include the following script:

    <!-- Place this asynchronous JavaScript just before your </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:plusone.js';
       var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
     })();
    </script>

The above example follows the best practice of using asynchronous loading of the JavaScript file for improved performance.

Step 3: Choose your OAuth scopes

The Google+ Sign-In button allows you to specify a list of scopes that designate the data and APIs that your app will be able to access on behalf of an authorized user. Specify the scope value in your scope attribute in the next step.

When specifying scopes, be aware that your app can request additional scopes anytime after your app's initial scopes have been granted. It is common to request these additional scopes at the point just prior to when your app requires them. This practice presents users with simpler and less overwhelming consent screens.

Next, you will add the sign-in button to your app.

Step 4: Add a Google+ Sign-In button to your page

The following example demonstrates adding an HTML tag that is transformed into the Google+ Sign-In button when the API loads. In your code, replace CLIENT_ID with the value that you created earlier:

<span id="signinButton">
  <span
    class="g-signin"
    data-callback="signinCallback"
    data-clientid="CLIENT_ID"
    data-cookiepolicy="single_host_origin"
    data-scope="email profile https://www.googleapis.com/auth/paymentssandbox.make_payments">
  </span>
</span>

The data-scope attribute indicates what kind of access to a user's data your app requires. See the button attributes for more information on customizing the button.

When the user clicks the button, they are prompted to authorize the app to access to this data. The callback function signinCallback will handle the result of the authorization. You will next implement the callback function.

When specifying scopes, be aware that your app can request additional scopes anytime after your app's initial scopes have been granted. It is common to request these additional scopes at the point just prior to when your app requires them. This practice presents users with simpler and less overwhelming consent screens.

Next, you must add the callback function to listen for the result of the sign-in flow.

Step 5: Handle the sign-in

Your callback function is a JavaScript function written by you that is triggered after the sign-in button is loaded. The function is passed an object that represents the authorization result.

When sign-in is successful, the authorization object will contain an access token in the access_token field. If the user is not signed-in you can inspect the error field to determine the cause.

Callback example:

function signinCallback(authResult) {
  if (authResult['status']['signed_in']) {
    // Update the app to reflect a signed in user
    // Hide the sign-in button now that the user is authorized, for example:
    document.getElementById('signinButton').setAttribute('style', 'display: none');
  } else {
    // Update the app to reflect a signed out user
    // Possible error values:
    //   "user_signed_out" - User is signed-out
    //   "access_denied" - User denied access to your app
    //   "immediate_failed" - Could not automatically log in the user
    console.log('Sign-in state: ' + authResult['error']);
  }
}

This example checks if the user is signed in to your website. The access token is automatically passed to the gapi.auth.setToken method, which enables you to make subsequent REST API calls.

Sign-in button attributes

Key Value Default Required Description
class string g-signin Required Required for rending the button in HTML. Omit if using gapi.signin.render()
data-clientid string Required Your OAuth 2.0 client ID that you obtained from the API Console.
data-cookiepolicy
  • uri
  • single_host_origin
  • none
Required

Directs the sign-in button to store user and session information in a session cookie and HTML5 session storage on the user's client for the purpose of minimizing HTTP traffic and distinguishing between multiple Google accounts a user might be signed into. We call these two means of storage the client storage.

When a page containing a sign-in button is loaded, the user's sign-in state can quickly be accessed from this client storage rather than from Google servers, reducing the latency for button loading. In addition, the cookie can allow a user who is signed in to multiple Google accounts (say, work and personal) to select which account to use with your website. The cookie and session storage are deleted once the user ends their browsing session.

The value of the data-cookiepolicy attribute determines the scope of URIs that can access the cookie. Choose this value based on the website's domain name to set the cookie's scope. Then the cookie can be accessed by all sign-in buttons within that scope. You should use a policy that is as broad as necessary for your site because that reduces the number of cookies that your site writes to the user's client. There should ideally be only one cookie for each distinct domain suffix you are allowed to write cookies for (for example, one cookie each for example.com and example.co.uk).

Available values - Three values of data-cookiepolicy are allowed: a uri, single_host_origin, and none. The most versatile setting you can pass is the uri value that most broadly matches the structure of your website.

For help with choosing a value, see Determining a value for cookie policy.

  • uri

    The uri includes the scheme, site-domain and possibly port to be set for your site. The value you provide determines the scope of the cookie. The more general the uri, the broader the scope of the cookie. The first five use cases are examples. Specify uri in one of the following three URI formats:

    • http://site_domain - An http scheme in uri provides the broadest scope—it sets a cookie whose scope includes both http and https domains and all of the site's subdomains. A more specific URI, such as http://mail.example.com, would set a more narrowly scoped cookie that further restricts its scope to only that domain and its subdomains.
    • https://site_domain - An https scheme in uri is similar to but narrower than http—use it for SSL-only sites. This ensures that the cookies will have the "secure" attribute set and hence will not be sent over an un-encrypted connection.
    • scheme://site_domain:port - Using a value that includes a port number. This value restricts the cookie's scope to only that one URI.

    Note: Sites with distinct domain suffixes (such as http://example.com and http://example.co.uk) must have different site_domain values, and therefore must be specified with different data-cookiepolicy markup.

  • single_host_origin

    Use this value if your website has only a single host name and no subdomains (for example, host http://example.com but not http://www.example.com). This string is shorthand for the scheme and host name (and port number if it's not the default for the scheme) of the current page, which then is equivalent to the uri value above.

  • none

    The none value does not set cookies or session storage for the sign-in button and uses a less efficient fallback mechanism for determining user and session information. This value also can prevent a user who is signed in to multiple Google accounts (say, work and personal) from being able to select which account to use with your website.

Note: You can identify client storage entries written by the sign-in button by checking their prefixes: GCSC prefix is used for session cookies and HTML5 session storage, and G_AUTHUSER_ prefix is used for session cookies only.

data-accesstype
  • online
  • offline
online If using the server-side sign-in flow and you want to get a refresh token that you can use to make offline requests, specify this attribute and set the value to offline.
data-apppackagename string

If you have an Android app, you can drive automatic Android downloads from your web sign-in flow. Set this parameter to the package name that you listed in your API Console project. For example: com.google.android.apps.plus.

Automatic Android app installs are limited to free apps in the Google Play store that exceed a quality threshold.

data-approvalprompt
  • auto
  • force
auto

Allows control over when the user is re-prompted for consent. When set to auto, the user only sees the OAuth consent dialog if they have not authorized your application. When set to force, the user is shown the OAuth consent dialog each time that they click the sign-in button.

You should use this parameter when your app needs to acquire a new one-time code because you have lost or discarded your one-time code or refresh tokens. Do not use this parameter to simulate a sign-in and sign-out solution or to disable the immediate authorization check that occurs when the button is rendered or page-level configuration parameters are present. See signing out the user.

data-callback function(authResult)

A function in the global namespace, which is called when the sign-in button is rendered and also called after a sign-in flow completes. When the button is rendered the callback occurs to check whether or not the user previously authorized the app and should be automatically signed in.

This function should hide or remove the sign-in button when the sign in is successful as indicated by the authResult object containing an access token.

This function is passed a single parameter: a JSON object that contains a number of properties. The following example shows the structure of the object and highlights a subset of the properties:

{
  "id_token": A JSON web token (JWT) that contains identity information about the user that is digitally signed by Google,
  "access_token": the access token,
  "expires_in": the validity of the token, in seconds,
  "error": The OAuth2 error type if problems occurred
}
data-height
  • short
  • standard
  • tall
standard

Sets the vertical height of the button.

See also data-width.

data-includegrantedscopes
  • true
  • false
true

If true, all previously granted scopes remain granted in each incremental request, for incremental authorization. The default value true is correct for most use cases; use false only if employing delegated auth, where you pass the bearer token to a less-trusted component with lower programmatic authority.

data-requestvisibleactions A space-delimited list of moment type URIs.

If your app will write moments, list the full URI of the types of moments that you intend to write. For example: http://schemas.google.com/AddActivity.

data-scope A space-delimited list of scope URIs https://www.googleapis.com/auth/plus.login

The OAuth 2.0 scopes for the APIs that you would like to use as a space-delimited list. You can list Google+ scopes and other Google OAuth 2.0 scopes that your application might require. Find more scopes in the OAuth 2.0 Playground.

data-theme
  • light
  • dark
dark

The color theme of the badge. Light renders a white button with red text and icon. Dark renders a red button with white text and icon.

data-width
  • iconOnly
  • standard
  • wide
standard

Controls the width of the button and the button text that appears. The approximate width is calculated for the user's language to fit the corresponding text:

  • iconOnly - Displays the Google+ icon only.
  • standard - Displays the Google+ icon followed by "Sign in"
  • wide - Displays the Google+ icon followed by "Sign in with Google"

See also data-height.

Oauth 2.0 scopes

Scopes define the content that you're requesting access to. These are the OAuth 2.0 scopes that are relevant to Google+ Sign-In for Instant Buy:

Scope Description
https://www.googleapis.com/auth/paymentssandbox.make_payments Read Google Wallet credentials from the sandbox environment.
https://www.googleapis.com/auth/payments.make_payments Read Google Wallet credentials from the production environment.
profile

This is the basic login scope. Like other scopes that conform to the OpenID Connect standard, it can be specified with a short name, "profile" — not in the form of a URI.

This scope does the following:

  • It requests that your app be given access to the authenticated user's basic profile information.
  • It lets you know who the currently authenticated user is by letting you replace a Google+ user ID with "me", which represents the authenticated user, in any call to the Google+ API.
  • It lets your web app access over-the-air Android app installs.
email

Request read-only access to the user's email address. Like other scopes that conform to the OpenID Connect standard, it can be specified with a short name, "email" — not in the form of a URI.

Google+ APIs do not return email addresses. You should send your access token to the tokenInfo endpoint, and the user's email address will be returned along with the rest of the validation information. For more information, see Retrieve an authenticated user's email address

Next Steps

To learn more about single sign-on in the larger context of a sample app using Google Wallet, see the end-to-end tutorials. For a real-world sample app that uses Google+ Sign-In, see the Photo Hunt samples.

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.