JavaScript クイックスタート

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して認証と認可フローの詳細の一部を処理します。独自のアプリにはクライアント ライブラリを使用することをおすすめします。サンプルアプリを実行するには、各クイックスタートで認証と認可を有効にする必要があります。Google Workspace API の認証と認可に不慣れな場合は、認証と認可の概要をご覧ください。

Reseller API にリクエストを行う JavaScript ウェブ アプリケーションを作成する。

目標

  • 環境を設定する。
  • サンプルを設定します。
  • サンプルを実行します。

Prerequisites

  • Google 販売パートナー ドメイン インスタンス。
  • 完全に締結された Google Workspace パートナー契約。

環境をセットアップする

このクイックスタートを完了するには、環境を設定します。

API の有効化

Google API を使用するには、Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。
  • Google Cloud コンソールで Reseller API を有効にします。

    API の有効化

ウェブ アプリケーションの認証情報を承認する

エンドユーザーとして認証し、アプリ内のユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで 1 つのアプリを識別するために使用されます。アプリを複数のプラットフォームで実行する場合は、プラットフォームごとに個別のクライアント ID を作成する必要があります。
  1. Google Cloud コンソールで、メニュー > [API とサービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [ウェブ アプリケーション] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. アプリに関連する承認済み URI を追加します。
    • クライアントサイド アプリ(JavaScript) - [承認済みの JavaScript 生成元] で [URI を追加] をクリックします。次に、ブラウザ リクエストに使用する URI を入力します。これにより、アプリケーションが OAuth 2.0 サーバーに API リクエストを送信できるドメインを識別します。
    • サーバーサイド アプリ(Java、Python など) - [承認済みのリダイレクト URI] の下にある [URI を追加] をクリックします。次に、OAuth 2.0 サーバーがレスポンスを送信できるエンドポイント URI を入力します。
  6. [作成] をクリックします。OAuth クライアント作成画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。

    クライアント ID をメモします。クライアント シークレットはウェブ アプリケーションでは使用されません。

  7. [OK] をクリックします。新しく作成された認証情報は、[OAuth 2.0 クライアント ID] に表示されます。
  8. (省略可)JavaScript クイックスタートの前提条件として認証情報を作成する場合は、API キーを生成する必要もあります。

これらの認証情報はクイックスタートの後半で必要になるため、メモしておきます。

サンプルのセットアップ

  1. 作業ディレクトリに index.html という名前のファイルを作成します。
  2. index.html ファイルに次のサンプルコードを貼り付けます。

    adminSDK/reseller/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Workspace Reseller API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Google WOrkspace Reseller API Quickstart</p>
    
        <!--Add buttons to initiate auth sequence and sign out-->
        <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
        <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
    
        <pre id="content" style="white-space: pre-wrap;"></pre>
    
        <script type="text/javascript">
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): Set to client ID and API key from the Developer Console
          const CLIENT_ID = '<YOUR_CLIENT_ID>';
          const API_KEY = '<YOUR_API_KEY>';
    
          // Discovery doc URL for APIs used by the quickstart
          const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/reseller/v1/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/apps.order';
    
          let tokenClient;
          let gapiInited = false;
          let gisInited = false;
    
          document.getElementById('authorize_button').style.visibility = 'hidden';
          document.getElementById('signout_button').style.visibility = 'hidden';
    
          /**
           * Callback after api.js is loaded.
           */
          function gapiLoaded() {
            gapi.load('client', initializeGapiClient);
          }
    
          /**
           * Callback after the API client is loaded. Loads the
           * discovery doc to initialize the API.
           */
          async function initializeGapiClient() {
            await gapi.client.init({
              apiKey: API_KEY,
              discoveryDocs: [DISCOVERY_DOC],
            });
            gapiInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Callback after Google Identity Services are loaded.
           */
          function gisLoaded() {
            tokenClient = google.accounts.oauth2.initTokenClient({
              client_id: CLIENT_ID,
              scope: SCOPES,
              callback: '', // defined later
            });
            gisInited = true;
            maybeEnableButtons();
          }
    
          /**
           * Enables user interaction after all libraries are loaded.
           */
          function maybeEnableButtons() {
            if (gapiInited && gisInited) {
              document.getElementById('authorize_button').style.visibility = 'visible';
            }
          }
    
          /**
           *  Sign in the user upon button click.
           */
          function handleAuthClick() {
            tokenClient.callback = async (resp) => {
              if (resp.error !== undefined) {
                throw (resp);
              }
              document.getElementById('signout_button').style.visibility = 'visible';
              document.getElementById('authorize_button').innerText = 'Refresh';
              await listSubscriptions();
            };
    
            if (gapi.client.getToken() === null) {
              // Prompt the user to select a Google Account and ask for consent to share their data
              // when establishing a new session.
              tokenClient.requestAccessToken({prompt: 'consent'});
            } else {
              // Skip display of account chooser and consent dialog for an existing session.
              tokenClient.requestAccessToken({prompt: ''});
            }
          }
    
          /**
           *  Sign out the user upon button click.
           */
          function handleSignoutClick() {
            const token = gapi.client.getToken();
            if (token !== null) {
              google.accounts.oauth2.revoke(token.access_token);
              gapi.client.setToken('');
              document.getElementById('content').innerText = '';
              document.getElementById('authorize_button').innerText = 'Authorize';
              document.getElementById('signout_button').style.visibility = 'hidden';
            }
          }
    
          /**
           * Print first ten subscriptions.
           */
          async function listSubscriptions() {
            let response;
            try {
              response = await gapi.client.reseller.subscriptions.list({
                'maxResults': 10,
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
    
            const subscriptions = response.result.subscriptions;
            if (!subscriptions || subscriptions.length == 0) {
              document.getElementById('content').innerText = 'No subscriptions found.';
              return;
            }
            // Flatten to string to display
            const output = subscriptions.reduce(
                (str, subscription) => {
                  const customer = subscription.customerId;
                  const sku = subscription.skuId;
                  const plan = subscription.plan.planName;
                  return `${str}${customer} (${sku},${plan})\n`;
                },
                'Subscriptions:\n');
            document.getElementById('content').innerText = output;
          }
        </script>
        <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
        <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
      </body>
    </html>

    以下を置き換えます。

サンプルの実行

  1. 作業ディレクトリでウェブサーバーを起動します。

    Python 2.x

    python -m SimpleHTTPServer 8000
    

    Python 3.x

    python3 -m http.server 8000
    
  2. ブラウザで http://localhost:8000 に移動します。

  3. サンプルを初めて実行すると、アクセスを承認するように求められます。

    1. まだ Google アカウントにログインしていない場合は、ログインするように求められます。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択してください。
    2. [同意する] をクリックします。
    3. ブラウザからコードをコピーして、コマンドライン プロンプトに貼り付け、Enter を押します。

    認可情報はファイル システムに保存されているため、次回サンプルコードを実行するときに、承認を求めるプロンプトは表示されません。

Reseller API にリクエストを送信する最初の JavaScript アプリケーションが正常に作成されました。

次のステップ