การเริ่มต้น JavaScript อย่างรวดเร็ว

การเริ่มต้นอย่างรวดเร็วจะอธิบายวิธีการตั้งค่าและเรียกใช้แอปที่เรียกใช้ Google Workspace API

คู่มือเริ่มใช้งานฉบับย่อของ Google Workspace จะใช้ไลบรารีของไคลเอ็นต์ API ในการจัดการกับ รายละเอียดขั้นตอนการตรวจสอบสิทธิ์และการให้สิทธิ์ เราขอแนะนำว่า คุณใช้ไลบรารีไคลเอ็นต์สำหรับแอปพลิเคชันของคุณเอง การเริ่มต้นอย่างรวดเร็วนี้ใช้ วิธีการตรวจสอบสิทธิ์ที่ง่ายขึ้นซึ่งเหมาะสำหรับการทดสอบ ของคุณ สำหรับสภาพแวดล้อมของการใช้งานจริง เราขอแนะนำให้เรียนรู้เกี่ยวกับ การตรวจสอบสิทธิ์และการให้สิทธิ์ ก่อน การเลือกข้อมูลเข้าสู่ระบบ ที่เหมาะกับแอปของคุณ

สร้างเว็บแอปพลิเคชัน JavaScript ที่ส่งคำขอไปยัง Google Calendar API

วัตถุประสงค์

  • ตั้งค่าสภาพแวดล้อมของคุณ
  • ตั้งค่าตัวอย่าง
  • เรียกใช้ตัวอย่าง

ข้อกำหนดเบื้องต้น

  • บัญชี Google ที่เปิดใช้ Google ปฏิทิน

ตั้งค่าสภาพแวดล้อมของคุณ

ตั้งค่าสภาพแวดล้อมเพื่อให้การเริ่มต้นอย่างรวดเร็วนี้เสร็จสมบูรณ์

เปิดใช้ API

ก่อนใช้ Google APIs คุณต้องเปิดใช้ API เหล่านี้ในโปรเจ็กต์ Google Cloud คุณสามารถเปิด API ได้ตั้งแต่ 1 รายการขึ้นไปในโปรเจ็กต์ Google Cloud เดียว

หากใช้โปรเจ็กต์ Google Cloud ใหม่เพื่อเริ่มต้นใช้งานอย่างรวดเร็วนี้ให้เสร็จสมบูรณ์ ให้กำหนดค่า หน้าจอขอความยินยอม OAuth แล้วเพิ่มตัวคุณเองเป็นผู้ใช้ทดสอบ หากคุณเคยดำเนินการแล้ว ทําตามขั้นตอนนี้สําหรับโปรเจ็กต์ที่อยู่ในระบบคลาวด์เรียบร้อยแล้ว ให้ข้ามไปยังส่วนถัดไป

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และ บริการ > หน้าจอขอความยินยอม OAuth

    ไปที่หน้าจอขอความยินยอม OAuth

  2. เลือกประเภทผู้ใช้เป็นภายใน แล้วคลิกสร้าง
  3. กรอกแบบฟอร์มการลงทะเบียนแอป แล้วคลิกบันทึกและดำเนินการต่อ
  4. ในตอนนี้ คุณสามารถข้ามการเพิ่มขอบเขต แล้วคลิกบันทึกและดำเนินการต่อได้ ในอนาคต เมื่อคุณสร้างแอปสำหรับใช้นอก ในองค์กร Google Workspace คุณต้องเปลี่ยนประเภทผู้ใช้เป็นภายนอก จากนั้น เพิ่มขอบเขตการให้สิทธิ์ที่แอปของคุณต้องการ

  5. ตรวจสอบสรุปการลงทะเบียนแอป หากต้องการเปลี่ยนแปลง ให้คลิกแก้ไข หากแอป การลงทะเบียนถูกต้องแล้ว ให้คลิกกลับไปที่หน้าแดชบอร์ด

ให้สิทธิ์ข้อมูลเข้าสู่ระบบสำหรับเว็บแอปพลิเคชัน

ในการตรวจสอบสิทธิ์ผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอป คุณต้องดำเนินการต่อไปนี้ สร้างรหัสไคลเอ็นต์ OAuth 2.0 อย่างน้อย 1 รหัส รหัสไคลเอ็นต์ใช้เพื่อระบุ แอปเดียวไปยังเซิร์ฟเวอร์ OAuth ของ Google หากแอปทำงานบนหลายแพลตฟอร์ม คุณต้องสร้างรหัสไคลเอ็นต์แยกกันสำหรับแต่ละแพลตฟอร์ม
  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และ บริการ > ข้อมูลเข้าสู่ระบบ

    ไปที่ข้อมูลเข้าสู่ระบบ

  2. คลิกสร้างข้อมูลเข้าสู่ระบบ > รหัสไคลเอ็นต์ OAuth
  3. คลิกประเภทแอปพลิเคชัน > เว็บแอปพลิเคชัน
  4. ในช่องชื่อ ให้พิมพ์ชื่อของข้อมูลเข้าสู่ระบบ ชื่อนี้จะแสดงเฉพาะในคอนโซล Google Cloud เท่านั้น
  5. เพิ่ม URI ที่ได้รับอนุญาตที่เกี่ยวข้องกับแอปของคุณ ดังนี้
    • แอปฝั่งไคลเอ็นต์ (JavaScript) - ในส่วนต้นทาง JavaScript ที่ได้รับอนุญาต ให้คลิกเพิ่ม URI จากนั้นป้อน URI เพื่อใช้สำหรับคำขอของเบราว์เซอร์ ค่านี้ระบุโดเมนที่แอปพลิเคชันของคุณสามารถส่งคำขอ API ไปยังเซิร์ฟเวอร์ OAuth 2.0
    • แอปฝั่งเซิร์ฟเวอร์ (Java, Python และอื่นๆ) - คลิกเพิ่ม URI ในส่วน URI การเปลี่ยนเส้นทางที่ได้รับอนุญาต จากนั้นป้อน URI ปลายทางที่เซิร์ฟเวอร์ OAuth 2.0 สามารถส่งการตอบกลับได้
  6. คลิกสร้าง หน้าจอที่สร้างไคลเอ็นต์ OAuth จะปรากฏขึ้น ซึ่งจะแสดงรหัสไคลเอ็นต์ใหม่และรหัสลับไคลเอ็นต์ของคุณ

    จดรหัสไคลเอ็นต์ ทั้งนี้จะไม่มีการใช้รหัสลับไคลเอ็นต์สำหรับเว็บแอปพลิเคชัน

  7. คลิกตกลง ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วนรหัสไคลเอ็นต์ OAuth 2.0

จดข้อมูลเข้าสู่ระบบเหล่านี้ไว้เนื่องจากคุณจำเป็นต้องใช้ในภายหลังในการเริ่มต้นอย่างรวดเร็วนี้

สร้างคีย์ API

  1. ในคอนโซล Google Cloud ให้ไปที่เมนู > API และ บริการ > ข้อมูลเข้าสู่ระบบ

    ไปที่ข้อมูลเข้าสู่ระบบ

  2. คลิกสร้างข้อมูลเข้าสู่ระบบ > คีย์ API
  3. คีย์ API ใหม่จะปรากฏขึ้น
    • คลิกคัดลอก เพื่อคัดลอกคีย์ API เพื่อใช้ในโค้ดของแอป คีย์ API ยังทำหน้าที่เป็น ที่พบใน "คีย์ API" ของข้อมูลเข้าสู่ระบบของโปรเจ็กต์
    • คลิกจำกัดคีย์เพื่ออัปเดตการตั้งค่าขั้นสูงและจำกัดการใช้งาน ของคีย์ API ดูรายละเอียดเพิ่มเติมได้ที่การใช้ข้อจำกัดของคีย์ API

ตั้งค่าตัวอย่าง

  1. สร้างไฟล์ชื่อ index.html ในไดเรกทอรีการทำงาน
  2. ในไฟล์ index.html ให้วางโค้ดตัวอย่างต่อไปนี้

    calendar/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Calendar API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Google Calendar 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/calendar/v3/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
    
          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 listUpcomingEvents();
            };
    
            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 the summary and start datetime/date of the next ten events in
           * the authorized user's calendar. If no events are found an
           * appropriate message is printed.
           */
          async function listUpcomingEvents() {
            let response;
            try {
              const request = {
                'calendarId': 'primary',
                'timeMin': (new Date()).toISOString(),
                'showDeleted': false,
                'singleEvents': true,
                'maxResults': 10,
                'orderBy': 'startTime',
              };
              response = await gapi.client.calendar.events.list(request);
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
    
            const events = response.result.items;
            if (!events || events.length == 0) {
              document.getElementById('content').innerText = 'No events found.';
              return;
            }
            // Flatten to string to display
            const output = events.reduce(
                (str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
                'Events:\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. คุณจะเห็นข้อความแจ้งให้ให้สิทธิ์เข้าถึง
    1. หากยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง ถ้า คุณลงชื่อเข้าใช้หลายบัญชีอยู่ ให้เลือกบัญชีเดียวที่จะใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

แอปพลิเคชัน JavaScript ของคุณเรียกใช้และเรียก API ของ Google ปฏิทิน

ขั้นตอนถัดไป