자바스크립트 빠른 시작

빠른 시작에서는 Google Workspace API

Google Workspace 빠른 시작에서는 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 세부 정보를 확인하세요. 따라서 자체 앱에 클라이언트 라이브러리를 사용합니다. 이 빠른 시작에서는 테스트에 적합한 간소화된 인증 접근 방식 환경입니다 프로덕션 환경의 경우 인증 및 승인 이전 액세스 사용자 인증 정보 선택 선택할 수 있습니다.

리셀러 API에 요청하는 자바스크립트 웹 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google 리셀러 도메인 인스턴스
  • 완전히 체결된 Google Workspace 파트너 계약입니다.

환경 설정

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 리셀러 API를 사용 설정합니다.

    API 사용 설정

새 Google Cloud 프로젝트를 사용하여 이 빠른 시작을 완료하는 경우 본인을 테스트 사용자로 추가합니다. 이미 계정을 이 단계를 완료한 경우에는 다음 섹션으로 건너뛰세요.

  1. Google Cloud 콘솔에서 메뉴 로 이동합니다. > API 및 서비스 > OAuth 동의 화면.

    OAuth 동의 화면으로 이동

  2. 사용자 유형으로 내부를 선택한 다음 만들기를 클릭합니다.
  3. 앱 등록 양식을 작성한 다음 저장하고 계속하기를 클릭합니다.
  4. 지금은 범위 추가를 건너뛰고 저장 후 계속을 클릭할 수 있습니다. 나중에 외부에서 사용하기 위해 앱을 만들 때 Google Workspace 조직에서 사용하는 경우 사용자 유형외부로 변경한 다음 앱에 필요한 승인 범위를 추가합니다.

  5. 앱 등록 요약을 검토합니다. 변경하려면 수정을 클릭합니다. 앱이 등록이 확인되면 대시보드로 돌아가기를 클릭합니다.

웹 애플리케이션의 사용자 인증 정보 승인

최종 사용자를 인증하고 앱의 사용자 데이터에 액세스하려면 다음을 수행해야 합니다. 하나 이상의 OAuth 2.0 클라이언트 ID를 만듭니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 웹 애플리케이션을 클릭합니다.
  4. 이름 필드에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 앱과 관련된 승인된 URI를 추가합니다. <ph type="x-smartling-placeholder">
      </ph>
    • 클라이언트 측 앱 (JavaScript): 승인된 자바스크립트 원본에서 URI 추가를 클릭합니다. 그런 다음 브라우저 요청에 사용할 URI를 입력합니다. 애플리케이션에서 OAuth 2.0 서버로 API 요청을 보낼 수 있는 도메인을 식별합니다.
    • 서버 측 앱 (자바, Python 등): 승인된 리디렉션 URI에서 URI 추가를 클릭합니다. 그런 다음 OAuth 2.0 서버가 응답을 보낼 수 있는 엔드포인트 URI를 입력합니다.
  6. 만들기를 클릭합니다. OAuth 클라이언트 생성 화면이 표시되고 새 클라이언트 ID와 클라이언트 비밀번호가 표시됩니다.

    클라이언트 ID를 기록해 둡니다. 클라이언트 비밀번호는 웹 애플리케이션에 사용되지 않습니다.

  7. 확인을 클릭합니다. 새로 생성된 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.

이 빠른 시작의 후반부에서 필요하므로 이 사용자 인증 정보를 기록해 둡니다.

API 키 만들기

  1. Google Cloud 콘솔에서 메뉴 로 이동합니다. &gt; API 및 서비스 &gt; 사용자 인증 정보를 선택합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 &gt;를 클릭합니다. API 키.
  3. 새 API 키가 표시됩니다.
    • 복사 를 클릭합니다. 앱 코드에 사용할 API 키를 복사하세요. 또한 API 키는 'API 키'에서 찾을 수 있습니다. 섹션으로 이동합니다.
    • 키 제한을 클릭하여 고급 설정을 업데이트하고 사용을 제한합니다. 확인할 수 있습니다 자세한 내용은 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. 작업 디렉터리에 http-server 패키지를 설치합니다.

    npm install http-server
    
  2. 작업 디렉터리에서 웹 서버를 시작합니다.

    npx http-server -p 8000
    
  1. 브라우저에서 http://localhost:8000으로 이동합니다.
  2. 액세스를 승인하라는 메시지가 표시됩니다. <ph type="x-smartling-placeholder">
      </ph>
    1. 아직 Google 계정에 로그인하지 않은 경우 메시지가 표시되면 로그인합니다. 만약 여러 계정에 로그인한 경우 승인에 사용할 계정 1개를 선택하세요.
    2. 수락을 클릭합니다.

JavaScript 애플리케이션이 실행되고 reseller API를 호출합니다.

다음 단계