JavaScript Quickstart

Complete the steps described in the rest of this page to create a simple JavaScript web application that makes requests to the Google Workspace Reseller API.

Prerequisites

To run this quickstart, you need the following prerequisites:

  • Python 2.4 or greater (to provide a web server)
  • A Google Cloud Platform project with the API enabled. To create a project and enable an API, refer to Create a project and enable the API
  • Authorization credentials for a desktop application. To learn how to create credentials for a desktop application, refer to Create credentials.

  • A Google Reseller domain instance.
  • A fully executed Google Workspace partner agreement.

Step 1: Set up the sample

To set up the sample:

  1. In your working directory, create a file named index.html.
  2. Include the following code in index.html:

    adminSDK/reseller/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>G Suite Reseller API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>G Suite Reseller API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" style="display: none;">Authorize</button>
        <button id="signout_button" style="display: none;">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          // Client ID and API key from the Developer Console
          var CLIENT_ID = '<YOUR_CLIENT_ID>';
          var API_KEY = '<YOUR_API_KEY>';
    
          // Array of API discovery doc URLs for APIs used by the quickstart
          var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/reseller/v1/rest"];
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          var SCOPES = 'https://www.googleapis.com/auth/apps.order';
    
          var authorizeButton = document.getElementById('authorize_button');
          var signoutButton = document.getElementById('signout_button');
    
          /**
           *  On load, called to load the auth2 library and API client library.
           */
          function handleClientLoad() {
            gapi.load('client:auth2', initClient);
          }
    
          /**
           *  Initializes the API client library and sets up sign-in state
           *  listeners.
           */
          function initClient() {
            gapi.client.init({
              apiKey: API_KEY,
              clientId: CLIENT_ID,
              discoveryDocs: DISCOVERY_DOCS,
              scope: SCOPES
            }).then(function () {
              // Listen for sign-in state changes.
              gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
    
              // Handle the initial sign-in state.
              updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
              authorizeButton.onclick = handleAuthClick;
              signoutButton.onclick = handleSignoutClick;
            }, function(error) {
              appendPre(JSON.stringify(error, null, 2));
            });
          }
    
          /**
           *  Called when the signed in status changes, to update the UI
           *  appropriately. After a sign-in, the API is called.
           */
          function updateSigninStatus(isSignedIn) {
            if (isSignedIn) {
              authorizeButton.style.display = 'none';
              signoutButton.style.display = 'block';
              listSubscriptions();
            } else {
              authorizeButton.style.display = 'block';
              signoutButton.style.display = 'none';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick(event) {
            gapi.auth2.getAuthInstance().signIn();
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick(event) {
            gapi.auth2.getAuthInstance().signOut();
          }
    
          /**
           * Append a pre element to the body containing the given message
           * as its text node. Used to display the results of the API call.
           *
           * @param {string} message Text to be placed in pre element.
           */
          function appendPre(message) {
            var pre = document.getElementById('content');
            var textContent = document.createTextNode(message + '\n');
            pre.appendChild(textContent);
          }
    
          /**
           * Print first ten subscriptions.
           */
          function listSubscriptions() {
            gapi.client.reseller.subscriptions.list({
              'maxResults': 10
            }).then(function(response) {
              var subscriptions = response.result.subscriptions;
              appendPre('Subscriptions:');
    
              if (subscriptions && subscriptions.length > 0) {
                for (i = 0; i < subscriptions.length; i++) {
                  var subscription = subscriptions[i];
                  appendPre("- " + subscription.customerId + "("
                    + subscription.skuId + ", " + subscription.plan.planName + ")");
                }
              } else {
                appendPre('No subscriptions found.');
              }
            });
          }
    
        </script>
    
        <script async defer src="https://apis.google.com/js/api.js"
          onload="this.onload=function(){};handleClientLoad()"
          onreadystatechange="if (this.readyState === 'complete') this.onload()">
        </script>
      </body>
    </html>

  3. In the code, replace <YOUR_CLIENT_ID> with the client ID you created as a Prerequisite for this quickstart.

  4. In the code, replace <YOUR_API_KEY> with the API key you created as a Prerequisite for this quickstart.

Step 2: Run the sample

To run the sample:

  1. Start the web server using the following command from your working directory:

Python 2.x

python -m SimpleHTTPServer 8000

Python 3.x

python -m http.server 8000
  1. In your browser, navigate to http://localhost:8000.

  2. (optional). If this is your first time running the sample, the sample opens an OAuth consent screen prompting you to authorize the app to access your data on your behalf:

    1. If you are not already signed in to your Google account, you are prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for authorization.

    2. Click Accept. The app is authorized to access your data.

  3. The sample executes.

If you have problems, refer to the Troubleshoot the sample section.

Troubleshoot the sample

This section describes some common issues that you can encounter while attempting to run this quickstart.

Error: origin_mismatch

This error occurs during the authorization flow if the host and port used to serve the web page doesn't match an allowed JavaScript origin on your Google Developers Console project. Make sure you set an authorized JavaScript origin and that the URL in your browser matches the origin's URL.

idpiframe_initialization_failed: Failed to read the 'localStorage' property from 'Window'

This error occurs when 3rd party cookies and data storage aren't enabled in your browser. These options are required by the Google Sign-in library. For further information, refer to 3rd party cookies and data storage.

idpiframe_initialization_failed: Not a valid origin for the client

This error occurs when the domain registered as a Prerequisite doesn't match the domain being used to host the web page. Ensure that the origin you registered as a Prerequisite matches the URL in the browser.

This app isn't verified

If the OAuth consent screen displays the warning "This app isn't verified," your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to {Project Name} (unsafe).

Further reading

For further information on the APIs used in this quickstart, refer to the Google API Client Library for JavaScript section of GitHub.