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

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

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

สร้างแอปพลิเคชันบรรทัดคำสั่ง Java ที่ส่งคำขอไปยัง Google Chat API

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

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

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

  • บัญชี Google Workspace ของธุรกิจหรือ Enterprise ที่มีสิทธิ์ใช้งาน Google Chat

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

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

เปิดใช้ 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. คลิกสร้าง หน้าจอที่สร้างไคลเอ็นต์ OAuth จะปรากฏขึ้น ซึ่งจะแสดงรหัสไคลเอ็นต์ใหม่และรหัสลับไคลเอ็นต์ของคุณ
  6. คลิกตกลง ข้อมูลเข้าสู่ระบบที่สร้างขึ้นใหม่จะปรากฏในส่วนรหัสไคลเอ็นต์ OAuth 2.0
  7. บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json และย้าย ไฟล์ลงในไดเรกทอรีที่ใช้งานอยู่

กำหนดค่าแอป Google Chat

หากต้องการเรียกใช้ Google Chat API คุณต้องกำหนดค่า แอป Google Chat Google Chat สำหรับคำขอการเขียนใดๆ ระบุแหล่งที่มาของแอป Google Chat ใน UI โดยใช้ ข้อมูลต่อไปนี้

  1. ในคอนโซล Google Cloud ให้ไปที่หน้าการกำหนดค่า Chat API แล้วดำเนินการดังนี้

    ไปที่หน้าการกำหนดค่า Chat API

  2. ในส่วนข้อมูลการสมัคร ให้ป้อนข้อมูลต่อไปนี้

    1. ในช่องชื่อแอป ให้ป้อน Chat API quickstart app
    2. ในช่อง URL รูปโปรไฟล์ ให้ป้อน https://developers.google.com/chat/images/quickstart-app-avatar.png
    3. ในช่องคำอธิบาย ให้ป้อน Quickstart for calling the Chat API
  3. ในส่วนฟีเจอร์แบบอินเทอร์แอกทีฟ ให้คลิกเปิดใช้ฟีเจอร์แบบอินเทอร์แอกทีฟ สลับไปที่ตำแหน่งปิดเพื่อปิดใช้งานคุณลักษณะแบบอินเทอร์แอกทีฟสำหรับ แอป Chat

  4. คลิกบันทึก

เตรียมพื้นที่ทำงาน

  1. ในไดเรกทอรีการทำงาน ให้สร้างโครงสร้างโปรเจ็กต์ใหม่:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources 
    
  2. คัดลอกไฟล์ credentials.json ในไดเรกทอรี src/main/resources/ ที่คุณดาวน์โหลดไว้ก่อนหน้านี้

  3. เปิดไฟล์ build.gradle เริ่มต้นและแทนที่เนื้อหาด้วย รหัสต่อไปนี้:

    chat/quickstart/build.gradle
    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'ChatQuickstart'
    sourceCompatibility = 11
    targetCompatibility = 11
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        implementation 'com.google.auth:google-auth-library-oauth2-http:1.23.0'
        implementation 'com.google.api-client:google-api-client:1.33.0'
        implementation 'com.google.api.grpc:proto-google-cloud-chat-v1:0.8.0'
        implementation 'com.google.api:gax:2.48.1'
        implementation 'com.google.cloud:google-cloud-chat:0.1.0'
        implementation 'com.google.oauth-client:google-oauth-client-jetty:1.34.1'
    }
    

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

  1. ในไดเรกทอรี src/main/java/ ให้สร้างไฟล์ Java ใหม่ด้วยชื่อที่ ตรงกับค่า mainClassName ในไฟล์ build.gradle ของคุณ

  2. ใส่โค้ดต่อไปนี้ในไฟล์ Java ใหม่

    chat/quickstart/src/main/java/ChatQuickstart.java
    import com.google.api.client.auth.oauth2.Credential;
    import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
    import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
    import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
    import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
    import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.gson.GsonFactory;
    import com.google.api.client.util.store.FileDataStoreFactory;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.Credentials;
    import com.google.auth.oauth2.AccessToken;
    import com.google.auth.oauth2.UserCredentials;
    import com.google.chat.v1.ChatServiceClient;
    import com.google.chat.v1.ChatServiceSettings;
    import com.google.chat.v1.ListSpacesRequest;
    import com.google.chat.v1.Space;
    import com.google.protobuf.util.JsonFormat;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.Collections;
    import java.util.Date;
    import java.util.List;
    
    /* class to demonstrate use of Google Chat API spaces list API */
    public class ChatQuickstart {
      /** Directory to store authorization tokens for this application. */
      private static final String TOKENS_DIRECTORY_PATH = "tokens";
    
      /**
       * Global instance of the scopes required by this quickstart. If modifying these scopes, delete
       * your previously saved tokens/ folder.
       */
      private static final List<String> SCOPES =
          Collections.singletonList("https://www.googleapis.com/auth/chat.spaces.readonly");
    
      /** Global instance of the JSON factory. */
      private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();
    
      private static final String CREDENTIALS_FILE_PATH = "/credentials.json";
    
      /**
       * Run the OAuth2 flow for local/installed app.
       *
       * @return An authorized Credential object.
       * @throws IOException If the credentials.json file cannot be found.
       */
      private static Credentials getCredentials() throws Exception {
        // Load client secrets.
        InputStream credentialsFileInputStream =
            ChatQuickstart.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (credentialsFileInputStream == null) {
          throw new FileNotFoundException("Credentials file resource not found.");
        }
        GoogleClientSecrets clientSecrets =
            GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(credentialsFileInputStream));
    
        // Set up authorization code flow.
        GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
                // Set these two options to generate refresh token alongside access token.
                .setDataStoreFactory(new FileDataStoreFactory(new File(TOKENS_DIRECTORY_PATH)))
                .setAccessType("offline")
                .build();
    
        // Authorize.
        Credential credential =
            new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
    
        // Build and return an authorized Credential object
        AccessToken accessToken =
            new AccessToken(
                credential.getAccessToken(),
                new Date(
                    // put the actual expiry date of access token here
                    System.currentTimeMillis()));
        return UserCredentials.newBuilder()
            .setAccessToken(accessToken)
            .setRefreshToken(credential.getRefreshToken())
            .setClientId(clientSecrets.getInstalled().getClientId())
            .setClientSecret(clientSecrets.getInstalled().getClientSecret())
            .build();
      }
    
      public static void main(String... args) throws Exception {
        // Override default service settings to supply user credentials.
        Credentials credentials = getCredentials();
    
        // Create the ChatServiceSettings with the credentials
        ChatServiceSettings chatServiceSettings =
            ChatServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
                .build();
    
        try (ChatServiceClient chatServiceClient = ChatServiceClient.create(chatServiceSettings)) {
          ListSpacesRequest request =
              ListSpacesRequest.newBuilder()
                  // Filter spaces by space type (SPACE or GROUP_CHAT or
                  // DIRECT_MESSAGE).
                  .setFilter("spaceType = \"SPACE\"")
                  .build();
    
          // Iterate over results and resolve additional pages automatically.
          for (Space response : chatServiceClient.listSpaces(request).iterateAll()) {
            System.out.println(JsonFormat.printer().print(response));
          }
        }
      }
    }

เรียกใช้ตัวอย่าง

  1. เรียกใช้ตัวอย่าง

    gradle run
    
  1. ครั้งแรกที่คุณเรียกใช้ตัวอย่าง ระบบจะแสดงข้อความให้คุณให้สิทธิ์เข้าถึง
    1. หากยังไม่ได้ลงชื่อเข้าใช้บัญชี Google ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง ถ้า คุณลงชื่อเข้าใช้หลายบัญชีอยู่ ให้เลือกบัญชีเดียวที่จะใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

    แอปพลิเคชัน Java จะเรียกใช้และเรียก Google Chat API

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

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