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

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

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

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

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

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

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

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

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

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

เปิดใช้ API

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

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

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

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

  2. หากกําหนดค่า แล้ว คุณจะกําหนดการตั้งค่าหน้าจอขอความยินยอม OAuth ต่อไปนี้ได้ในการสร้างแบรนด์ กลุ่มเป้าหมาย และการเข้าถึงข้อมูล หากเห็นข้อความว่า not configured yet ให้คลิกเริ่มต้นใช้งาน
    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. ป้อน https://developers.google.com/chat/images/quickstart-app-avatar.png ในช่อง Avatar URL
    3. ป้อน Quickstart for calling the Chat API ในช่องคำอธิบาย
  3. ในส่วนฟีเจอร์แบบอินเทอร์แอกทีฟ ให้คลิกปุ่มเปิด/ปิดเปิดใช้ฟีเจอร์แบบอินเทอร์แอกทีฟเป็นปิดเพื่อปิดใช้ฟีเจอร์แบบอินเทอร์แอกทีฟสำหรับแอปแชท

  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

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

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