คู่มือเริ่มใช้งาน JavaScript ฉบับย่อ

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

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

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

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

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

สิ่งที่ต้องดำเนินการก่อน

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

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

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

เปิดใช้ API

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

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

ในการตรวจสอบสิทธิ์ในฐานะผู้ใช้ปลายทางและเข้าถึงข้อมูลผู้ใช้ในแอปของคุณ คุณต้องสร้างรหัสไคลเอ็นต์ 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 ให้วางโค้ดตัวอย่างต่อไปนี้

    gmail/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Gmail API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Gmail 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/gmail/v1/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/gmail.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 listLabels();
            };
    
            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 all Labels in the authorized user's inbox. If no labels
           * are found an appropriate message is printed.
           */
          async function listLabels() {
            let response;
            try {
              response = await gapi.client.gmail.users.labels.list({
                'userId': 'me',
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
            const labels = response.result.labels;
            if (!labels || labels.length == 0) {
              document.getElementById('content').innerText = 'No labels found.';
              return;
            }
            // Flatten to string to display
            const output = labels.reduce(
                (str, label) => `${str}${label.name}\n`,
                'Labels:\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
    
  3. ในเบราว์เซอร์ ให้ไปที่ http://localhost:8000

  4. ครั้งแรกที่เรียกใช้ตัวอย่าง ระบบจะแจ้งให้คุณให้สิทธิ์เข้าถึง

    1. หากคุณยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ของคุณ ระบบจะแจ้งให้คุณลงชื่อเข้าใช้ หากลงชื่อเข้าใช้หลายบัญชี ให้เลือกบัญชีที่จะใช้เพื่อให้สิทธิ์
    2. คลิกยอมรับ
    3. คัดลอกโค้ดจากเบราว์เซอร์ วางลงในพรอมท์บรรทัดคําสั่ง และกด Enter

    ข้อมูลการให้สิทธิ์จะจัดเก็บไว้ในระบบไฟล์ ดังนั้น เมื่อคุณเรียกใช้โค้ดตัวอย่างครั้งต่อไป จึงไม่ได้รับแจ้งให้ให้สิทธิ์

คุณได้สร้างแอปพลิเคชัน JavaScript แรกที่ส่งคําขอไปยัง Gmail API เรียบร้อยแล้ว

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