Hướng dẫn nhanh về Java dành cho đại lý

Hãy làm theo các bước trong hướng dẫn bắt đầu nhanh này. Sau khoảng 10 phút, bạn sẽ có một ứng dụng dòng lệnh Java đơn giản để thực hiện các yêu cầu API người bán lại đăng ký thiết lập tự động.

Điều kiện tiên quyết

Để chạy tính năng khởi động nhanh này, bạn cần:

  • Tài khoản Google là thành viên của tài khoản đại lý đăng ký thiết lập tự động. Nếu bạn chưa tham gia, hãy làm theo các bước trong phần Bắt đầu trong Hướng dẫn về cổng đại lý.
  • Java 1.7 trở lên.
  • Gradle 2.3 trở lên.
  • Quyền truy cập vào Internet và trình duyệt web.

Bước 1: Bật API thiết lập tự động

  1. Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, rồi nhấp vào Chuyển đến thông tin xác thực.
  2. Đặt Dữ liệu bạn sẽ truy cập? thành Dữ liệu ứng dụng.
  3. Nhấp vào Tiếp theo. Bạn sẽ được nhắc tạo tài khoản dịch vụ.
  4. Đặt tên mô tả cho Tên tài khoản dịch vụ.
  5. Hãy lưu ý đến mã tài khoản dịch vụ (có vẻ như giống một địa chỉ email) vì sau này bạn sẽ dùng nó.
  6. Đặt Vai trò thành Tài khoản dịch vụ > Người dùng tài khoản dịch vụ.
  7. Nhấp vào Xong để hoàn tất việc tạo tài khoản dịch vụ.
  8. Nhấp vào địa chỉ email cho tài khoản dịch vụ mà bạn đã tạo.
  9. Nhấp vào **Khoá**.
  10. Nhấp vào **Thêm khoá**, rồi nhấp vào **Tạo khoá mới**.
  11. Đối với **Loại khoá**, hãy chọn **JSON**.
  12. Nhấp vào Tạo rồi tải khoá riêng tư xuống máy tính của bạn.
  13. Nhấp vào **Đóng**.
  14. Di chuyển tệp vào thư mục đang hoạt động của bạn và đổi tên tệp đó service_account_key.json.
  1. Mở cổng thiết lập tự động. Bạn có thể cần đăng nhập.
  2. Nhấp vào Tài khoản dịch vụ.
  3. Nhấp vào Liên kết tài khoản dịch vụ.
  4. Đặt Địa chỉ email thành địa chỉ của tài khoản dịch vụ mà bạn đã tạo.
  5. Nhấp vào Link dịch tài khoản để liên kết tài khoản dịch vụ với tài khoản thiết lập tự động.

Bước 3: Chuẩn bị dự án

Làm theo các bước bên dưới để thiết lập dự án Gradle của bạn:

  1. Chạy lệnh sau để tạo một dự án mới trong thư mục đang hoạt động:

    gradle init --type basic
    mkdir -p src/main/java src/main/resources
    
  2. Sao chép tệp service_account_key.json mà bạn đã tải xuống ở Bước 1 vào thư mục src/main/resources/ mà bạn đã tạo ở trên.

  3. Mở tệp build.gradle mặc định và thay thế nội dung của tệp bằng mã sau:

    apply plugin: 'java'
    apply plugin: 'application'
    
    mainClassName = 'ResellerQuickstart'
    sourceCompatibility = 1.7
    targetCompatibility = 1.7
    version = '1.0'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
        compile 'com.google.api-client:google-api-client:1.30.11'
        compile 'com.google.apis:google-api-services-androiddeviceprovisioning:+'
        compile 'com.google.oauth-client:google-oauth-client-jetty:+'
    }
    

Bước 4: Thiết lập mẫu

Tạo một tệp có tên là src/main/java/ResellerQuickstart.java rồi sao chép vào mã sau và lưu tệp đó. Chèn mã đối tác đại lý của riêng bạn làm giá trị cho PARTNER_ID (dòng đầu tiên của ứng dụng).

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.androiddeviceprovisioning.v1.AndroidProvisioningPartner;
import com.google.api.services.androiddeviceprovisioning.v1.model.Company;
import com.google.api.services.androiddeviceprovisioning.v1.model.ListCustomersResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

/**
 * This class forms the quickstart introduction to the zero-touch enrollemnt
 * reseller API.
 */
public class ResellerQuickstart {

  // TODO: replace this with your partner reseller ID.
  private static long PARTNER_ID = 11036885;

  // Use a single scope for the all methods in the reseller API.
  private static final List<String> SCOPES =
      Arrays.asList("https://www.googleapis.com/auth/androidworkprovisioning");
  private static final String APP_NAME = "Zero-touch Reseller Java Quickstart";

  // Global shared instances.
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
  private static HttpTransport HTTP_TRANSPORT;

  static {
    try {
      HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    } catch (Throwable t) {
      t.printStackTrace();
      System.exit(1);
    }
  }

  /**
   * Creates a Credential object with the correct OAuth2 authorization
   * for the service account that calls the reseller API. The service
   * endpoint invokes this method when setting up a new service instance.
   * @return an authorized Credential object.
   * @throws IOException
   */
  public static Credential authorize() throws IOException {
      // Load the service account key from the JSON file.
      InputStream in =
          ResellerQuickstart.class.getResourceAsStream("/service_account_key.json");

      // Create the credential scoped to the zero-touch enrollemnt
      // reseller APIs.
      GoogleCredential credential = GoogleCredential
         .fromStream(in)
         .createScoped(SCOPES);
      return credential;
  }

  /**
   * Builds and returns an authorized zero-touch enrollment API client service.
   * Use the service endpoint to call the API methods.
   * @return an authorized client service endpoint
   * @throws IOException
   */
  public static AndroidProvisioningPartner getService() throws IOException {
    Credential credential = authorize();
    return new AndroidProvisioningPartner.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, credential)
        .setApplicationName(APP_NAME)
        .build();
  }

  /**
   * Runs the zero-touch enrollment quickstart app.
   * @throws IOException
   */
  public static void main(String[] args) throws IOException {

    // Create a zero-touch enrollment API service endpoint.
    AndroidProvisioningPartner service = getService();

    // Send an API request to list all our customers.
    AndroidProvisioningPartner.Partners.Customers.List request =
          service.partners().customers().list(PARTNER_ID);
    ListCustomersResponse response = request.execute();

    // Print out the details of each customer.
    if (response.getCustomers() != null) {
      java.util.List<Company> customers = response.getCustomers();
      for (Company customer : customers) {
          System.out.format("Name:%s  ID:%d\n",
                customer.getCompanyName(),
                customer.getCompanyId());
      }
    } else {
      System.out.println("No customers found");
    }
  }
}

Mã nhận dạng đối tác

Các lệnh gọi API thường cần có mã đối tác của đại lý để làm đối số. Để tìm mã đối tác của bạn từ cổng thiết lập tự động, hãy làm theo các bước dưới đây:

  1. Mở cổng. Bạn có thể cần đăng nhập.
  2. Nhấp vào Tài khoản dịch vụ.
  3. Sao chép số mã đối tác từ dòng Mã người bán lại của bạn.

Bước 5: Chạy mẫu

Sử dụng trợ giúp của hệ điều hành để chạy tập lệnh trong tệp. Trên máy tính UNIX và Mac, hãy chạy lệnh bên dưới trong thiết bị đầu cuối của bạn:

gradle -q run

Khắc phục sự cố

Hãy cho chúng tôi biết vấn đề gì trong thời gian khởi động nhanh và chúng tôi sẽ tìm cách khắc phục. Để tìm hiểu cách thiết lập tự động sử dụng tài khoản dịch vụ để uỷ quyền cho các lệnh gọi API, hãy đọc nội dung Uỷ quyền.

Tìm hiểu thêm