คู่มือเริ่มต้นใช้งาน Java

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

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

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

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

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

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

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

ตั้งค่าสภาพแวดล้อมให้พร้อมเพื่อทำตามคู่มือเริ่มต้นใช้งานอย่างรวดเร็วนี้

เปิดใช้ API

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

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

  1. ในคอนโซล Google API ให้ไปที่เมนู > แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google > การสร้างแบรนด์.

    ไปที่การสร้างแบรนด์

  2. หากกำหนดค่าแพลตฟอร์มการตรวจสอบสิทธิ์ของ Google ไว้แล้ว คุณสามารถกำหนดค่าการตั้งค่าหน้าจอขอคำยินยอม OAuth ต่อไปนี้ใน การสร้างแบรนด์, กลุ่มเป้าหมาย และ การเข้าถึงข้อมูล หากเห็นข้อความว่า แพลตฟอร์มการตรวจสอบสิทธิ์ของ Google ยังไม่ได้กำหนดค่า ให้คลิก เริ่มต้นใช้งาน
    1. ในส่วนข้อมูลแอป ในชื่อแอป ให้ป้อนชื่อแอป
    2. ในส่วนอีเมลสนับสนุนสำหรับผู้ใช้ ให้เลือกอีเมลสนับสนุนที่ผู้ใช้สามารถติดต่อคุณได้หากมีคำถามเกี่ยวกับความยินยอม
    3. คลิกถัดไป
    4. ในส่วนกลุ่มเป้าหมาย ให้เลือกภายใน
    5. คลิกถัดไป
    6. ในส่วนข้อมูลติดต่อ ให้ป้อนอีเมล ที่คุณจะได้รับการแจ้งเตือนเกี่ยวกับการเปลี่ยนแปลงในโปรเจ็กต์
    7. คลิกถัดไป
    8. ในส่วนเสร็จสิ้น ให้อ่านนโยบายข้อมูลผู้ใช้สำหรับบริการ Google API และหากยอมรับ ให้เลือกฉันยอมรับบริการ Google API: นโยบายข้อมูลผู้ใช้
    9. คลิกต่อไป
    10. คลิกสร้าง
  3. ตอนนี้คุณสามารถข้ามการเพิ่มขอบเขตได้ ในอนาคต เมื่อสร้างแอปเพื่อใช้ภายนอกองค์กร Google Workspace คุณต้องเปลี่ยนประเภทผู้ใช้ เป็นภายนอก จากนั้น เพิ่มขอบเขตการให้สิทธิ์ที่แอปต้องใช้ ดูข้อมูลเพิ่มเติมได้ในคู่มือฉบับเต็มเกี่ยวกับ การกำหนดค่าหน้าจอขอคำยินยอม OAuth

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

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

    ไปที่ไคลเอ็นต์

  2. คลิกสร้างไคลเอ็นต์
  3. คลิกประเภทแอปพลิเคชัน > แอปบนเดสก์ท็อป
  4. ในช่องชื่อ ให้พิมพ์ชื่อข้อมูลเข้าสู่ระบบ ชื่อนี้จะแสดงในคอนโซล Google Cloud เท่านั้น
  5. คลิกสร้าง

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

  6. บันทึกไฟล์ JSON ที่ดาวน์โหลดเป็น credentials.json แล้วย้ายไฟล์ไปยังไดเรกทอรีงาน

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

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

  1. ในคอนโซล Google API ให้ไปที่หน้าการกำหนดค่า ของ 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. ในไดเรกทอรี src/main/resources/ ให้คัดลอกไฟล์ credentials.json ที่คุณดาวน์โหลดไว้ก่อนหน้านี้

  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

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

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