Khả năng tương thích của Content API for Shopping

Bạn có thể sử dụng hướng dẫn này để tích hợp Merchant API với cách triển khai Content API for Shopping hiện tại.

Merchant API cho phép bạn tự động hoá quy trình quản lý liên quan đến tài khoản, sản phẩm và khoảng không quảng cáo trên Merchant Center. Các trường hợp sử dụng Merchant API bao gồm:

  • Quản lý tài khoản tự động
  • Quản lý sản phẩm tự động
  • Quản lý khoảng không quảng cáo tự động
  • Báo cáo tuỳ chỉnh

Các điểm cải tiến so với Content API

Merchant API cải thiện hơn Content API ở những khía cạnh sau:

Bắt đầu

Hãy xem thiết kế Merchant API để biết thông tin chi tiết về Merchant API và các API phụ của API này.

Để bắt đầu sử dụng Merchant API, hãy thay đổi URL yêu cầu của bạn thành định dạng sau:

https://merchantapi.googleapis.com/{SUB_API}/{VERSION}/{RESOURCE_NAME}:{METHOD}

Để biết thêm thông tin, hãy xem hướng dẫn bắt đầu nhanhtài liệu tham khảo về Merchant API.

Hỗ trợ gRPC

Merchant API hỗ trợ gRPC và REST. Bạn có thể sử dụng gRPC cho Merchant API và REST cho Content API for Shopping cùng một lúc.

Thư viện ứng dụng của Merchant API yêu cầu gRPC.

Hãy xem phần sử dụng gRPC để biết thêm thông tin.

Khả năng tương thích

Hướng dẫn này mô tả những thay đổi chung áp dụng cho toàn bộ Merchant API. Hãy xem các hướng dẫn sau đây để biết những thay đổi đối với các tính năng cụ thể:

Merchant API được thiết kế để hoạt động cùng với các tính năng hiện có của Content API for Shopping phiên bản 2.1.

Ví dụ: bạn có thể sử dụng Merchant Inventories API cùng với cách triển khai Content API for Shopping phiên bản 2.1 products hiện có. Bạn có thể sử dụng Content API for Shopping để tải một sản phẩm mới tại cửa hàng địa phương lên (mà bạn bán tại một cửa hàng địa phương), sau đó sử dụng tài nguyên Merchant Inventories API LocalInventory để quản lý thông tin tại cửa hàng cho sản phẩm đó.

Yêu cầu theo lô (Batch)

Merchant API không hỗ trợ phương thức customBatch có trong Content API for Shopping. Thay vào đó, hãy xem phần Gửi nhiều yêu cầu cùng lúc hoặc thực thi các lệnh gọi không đồng bộ.

Mẫu sau đây minh hoạ cách chèn dữ liệu đầu vào về sản phẩm.

Java

import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutureCallback;
import com.google.api.core.ApiFutures;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.shopping.merchant.products.v1beta.Attributes;
import com.google.shopping.merchant.products.v1beta.InsertProductInputRequest;
import com.google.shopping.merchant.products.v1beta.ProductInput;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceClient;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceSettings;
import com.google.shopping.merchant.products.v1beta.Shipping;
import com.google.shopping.type.Channel.ChannelEnum;
import com.google.shopping.type.Price;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to insert a product input */
public class InsertProductInputAsyncSample {

  private static String getParent(String accountId) {
    return String.format("accounts/%s", accountId);
  }

  private static String generateRandomString() {
    String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    StringBuilder sb = new StringBuilder(8);
    for (int i = 0; i < 8; i++) {
      sb.append(characters.charAt(random.nextInt(characters.length())));
    }
    return sb.toString();
  }

  private static ProductInput createRandomProduct() {
    Price price = Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode("USD").build();

    Shipping shipping =
        Shipping.newBuilder().setPrice(price).setCountry("GB").setService("1st class post").build();

    Shipping shipping2 =
        Shipping.newBuilder().setPrice(price).setCountry("FR").setService("1st class post").build();

    Attributes attributes =
        Attributes.newBuilder()
            .setTitle("A Tale of Two Cities")
            .setDescription("A classic novel about the French Revolution")
            .setLink("https://exampleWebsite.com/tale-of-two-cities.html")
            .setImageLink("https://exampleWebsite.com/tale-of-two-cities.jpg")
            .setAvailability("in stock")
            .setCondition("new")
            .setGoogleProductCategory("Media > Books")
            .setGtin(0, "9780007350896")
            .addShipping(shipping)
            .addShipping(shipping2)
            .build();

    return ProductInput.newBuilder()
        .setChannel(ChannelEnum.ONLINE)
        .setContentLanguage("en")
        .setFeedLabel("CH")
        .setOfferId(generateRandomString())
        .setAttributes(attributes)
        .build();
  }

  public static void asyncInsertProductInput(Config config, String dataSource) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    ProductInputsServiceSettings productInputsServiceSettings =
        ProductInputsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates parent to identify where to insert the product.
    String parent = getParent(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (ProductInputsServiceClient productInputsServiceClient =
        ProductInputsServiceClient.create(productInputsServiceSettings)) {

      // Creates five insert product input requests with random product IDs.
      List<InsertProductInputRequest> requests = new ArrayList<>(5);
      for (int i = 0; i < 5; i++) {
        InsertProductInputRequest request =
            InsertProductInputRequest.newBuilder()
                .setParent(parent)
                // You can only insert products into datasource types of Input "API" and "FILE", and
                // of Type "Primary" or "Supplemental."
                // This field takes the `name` field of the datasource.
                .setDataSource(dataSource)
                // If this product is already owned by another datasource, when re-inserting, the
                // new datasource will take ownership of the product.
                .setProductInput(createRandomProduct())
                .build();

        requests.add(request);
      }

      System.out.println("Sending insert product input requests");
      List<ApiFuture<ProductInput>> futures =
          requests.stream()
              .map(
                  request ->
                      productInputsServiceClient.insertProductInputCallable().futureCall(request))
              .collect(Collectors.toList());

      // Creates callback to handle the responses when all are ready.
      ApiFuture<List<ProductInput>> responses = ApiFutures.allAsList(futures);
      ApiFutures.addCallback(
          responses,
          new ApiFutureCallback<List<ProductInput>>() {
            @Override
            public void onSuccess(List<ProductInput> results) {
              System.out.println("Inserted products below");
              System.out.println(results);
            }

            @Override
            public void onFailure(Throwable throwable) {
              System.out.println(throwable);
            }
          },
          MoreExecutors.directExecutor());

    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // Identifies the data source that will own the product input.
    String dataSource = "accounts/" + config.getAccountId() + "/dataSources/{datasourceId}";

    asyncInsertProductInput(config, dataSource);
  }
}

Nếu bạn sử dụng customBatch trong Content API và cần tính năng này cho Merchant API, hãy cho chúng tôi biết lý do trong phản hồi.

Giá trị nhận dạng

Để phù hợp với nguyên tắc cải thiện API của Google, chúng tôi đã thực hiện một số thay đổi đối với giá trị nhận dạng cho các tài nguyên Merchant API.

tên thay thế mã nhận dạng

Tất cả tài nguyên Merchant API đều sử dụng trường name làm giá trị nhận dạng duy nhất.

Dưới đây là ví dụ về cách sử dụng trường name trong lệnh gọi:

POST https://merchantapi.googleapis.com/inventories/v1beta/{PARENT}/regionalInventories:insert

Trường name mới này được trả về dưới dạng giá trị nhận dạng tài nguyên cho tất cả lệnh gọi đọc và ghi trong Merchant API.

Ví dụ: triển khai phương thức getName() để truy xuất name từ một tài nguyên và lưu trữ kết quả dưới dạng biến thay vì tự tạo name từ mã nhận dạng người bán và tài nguyên.

trường mẹ cho tài nguyên con

Trong Merchant API, tất cả tài nguyên con đều có trường parent. Bạn có thể sử dụng trường parent để chỉ định name của tài nguyên cần chèn thành phần con, thay vì truyền toàn bộ tài nguyên mẹ. Bạn cũng có thể sử dụng trường parent với các phương thức list để liệt kê các tài nguyên con của parent đó.

Ví dụ: để liệt kê kho hàng tại địa phương cho một sản phẩm cụ thể, hãy chỉ định name của sản phẩm trong trường parent cho phương thức list. Trong trường hợp này, product đã cho là parent của các tài nguyên LocalInventory được trả về.

Loại

Dưới đây là một số loại phổ biến được chia sẻ trên các API phụ của Merchant API.

Giá

Sau đây là những thay đổi đối với Price trong gói Merchant Common:

Content API Merchant API
Trường số tiền value:string amountMicros:int64
Trường đơn vị tiền tệ currency:string currencyCode:string

Số tiền Price hiện được ghi lại bằng micro, trong đó 1 triệu micro tương đương với đơn vị tiêu chuẩn của đơn vị tiền tệ.

Trong Content API for Shopping, Price là một số thập phân ở dạng chuỗi.

Tên trường số tiền đã thay đổi từ value thành amountMicros

Tên trường đơn vị tiền tệ đã thay đổi từ currency thành currencyCode. Định dạng vẫn là ISO 4217.