מדריך למתחילים ב-Java

מדריכים למתחילים מסבירים איך להגדיר ולהפעיל אפליקציה שמתקשרת Google Workspace API.

המדריכים למתחילים של Google Workspace משתמשים בספריות הלקוח של ה-API כדי לטפל פרטים על תהליך האימות וההרשאה. מומלץ להשתמש בספריות הלקוח עבור האפליקציות שלכם. המדריך למתחילים הזה משתמש גישת אימות פשוטה שמתאימה לבדיקות הסביבה. בסביבת ייצור, מומלץ ללמוד על אימות והרשאה לפני בחירת פרטי הכניסה שמתאימים לאפליקציה שלכם.

יוצרים אפליקציית שורת הפקודה Java ששולחת בקשות ל-Google Chat API.

מטרות

  • מגדירים את הסביבה.
  • הגדרת הדוגמה.
  • מריצים את הדוגמה.

דרישות מוקדמות

הגדרת הסביבה

כדי להשלים את המדריך למתחילים הזה, עליכם להגדיר את הסביבה.

הפעלת ה-API

לפני שמשתמשים ב-Google APIs, צריך להפעיל אותם בפרויקט ב-Google Cloud. אפשר להפעיל ממשק API אחד או יותר בפרויקט אחד ב-Google Cloud.

אם אתם משתמשים בפרויקט חדש ב-Google Cloud כדי להשלים את המדריך למתחילים הזה, צריך להגדיר במסך ההסכמה ל-OAuth ולהוסיף את עצמכם כמשתמש/ת בדיקה. אם כבר סיימתם את השלב הזה בפרויקט שלכם ב-Cloud, דלגו לחלק הבא.

  1. במסוף Google Cloud, נכנסים לתפריט > ממשקי API ו- Services (שירותים) > מסך ההסכמה של OAuth.

    מעבר למסך ההסכמה ל-OAuth

  2. בקטע סוג המשתמש, בוחרים באפשרות פנימי ולוחצים על יצירה.
  3. ממלאים את טופס הרישום של האפליקציה ולוחצים על שמירה והמשך.
  4. בשלב הזה אפשר לדלג על הוספת היקפי הרשאות וללחוץ על שמירה והמשך. בעתיד, כשתיצרו אפליקציה לשימוש מחוץ ל- בארגון ב-Google Workspace, צריך לשנות את סוג המשתמש לחיצוני, ואז: להוסיף את היקפי ההרשאות שנדרשים לאפליקציה.

  5. מעיינים בסיכום של רישום האפליקציה. כדי לבצע שינויים, לוחצים על עריכה. אם האפליקציה נראה שהרישום תקין, לוחצים על חזרה למרכז הבקרה.

אישור פרטי כניסה לאפליקציה בשולחן העבודה

כדי לאמת משתמשי קצה ולגשת לנתוני המשתמשים באפליקציה: ליצור מזהה לקוח אחד או יותר של OAuth 2.0. מזהה לקוח משמש לזיהוי אפליקציה יחידה לשרתי OAuth של Google. אם האפליקציה שלכם פועלת בכמה פלטפורמות, צריך ליצור מזהה לקוח נפרד לכל פלטפורמה.
  1. במסוף Google Cloud, נכנסים לתפריט > APIs & שירותים > פרטי כניסה.

    כניסה לדף Credentials

  2. לוחצים על יצירת פרטי כניסה > מזהה לקוח OAuth.
  3. לוחצים על סוג אפליקציה > אפליקציית מחשב.
  4. בשדה Name, מקלידים שם לפרטי הכניסה. השם הזה מוצג רק במסוף Google Cloud.
  5. לוחצים על יצירה. יופיע המסך שנוצר על ידי לקוח OAuth ומוצג בו מזהה הלקוח החדש וסוד הלקוח שלכם.
  6. לוחצים על אישור. פרטי הכניסה החדשים שנוצרו יופיעו בקטע מזהי לקוחות OAuth 2.0.
  7. שומרים את קובץ ה-JSON שהורדתם בתור credentials.json ומעבירים את לספריית העבודה.

איך מגדירים את אפליקציית Google Chat

כדי לשלוח קריאה ל-Google Chat API, צריך להגדיר אפליקציית Google Chat. Google Chat – לכל בקשה לכתיבה שמשייך את אפליקציית Google Chat בממשק המשתמש באמצעות את הפרטים הבאים.

  1. נכנסים לדף Configuration במסוף Google Cloud:

    לדף ההגדרה של Chat API

  2. בקטע Application info (פרטי האפליקציה), מזינים את הפרטים הבאים:

    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 ומבצעת קריאה אליו.

    פרטי ההרשאות מאוחסנים במערכת הקבצים, לכן בפעם הבאה שמריצים את הדוגמה לא תופיע בקשה להרשאה.

השלבים הבאים