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

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

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

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

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

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

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

  • บัญชี Google Workspace สำหรับธุรกิจหรือองค์กรที่มีสิทธิ์เข้าถึง Google Chat

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

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

เปิดใช้ API

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

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

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

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

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

    ไปที่ลูกค้า

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

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

  6. บันทึกไฟล์ 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. ในไดเรกทอรี 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 ให้ลงชื่อเข้าใช้เมื่อได้รับข้อความแจ้ง หาก คุณลงชื่อเข้าใช้หลายบัญชี ให้เลือก 1 บัญชีเพื่อใช้สำหรับการให้สิทธิ์
    2. คลิกยอมรับ

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

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

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