Обзор API источников данных о продавцах

На этой странице показано, как программно создавать и обновлять источники данных, включая автоматизированные источники данных, которые позволяют вставлять продукты.

API контента для покупок позволяет создавать первичные источники данных. С API источников данных торговцев вы также можете создавать следующие типы источников данных:

API контента для покупок позволяет управлять источниками данных только с помощью файлового ввода. API торговца позволяет управлять источниками данных как с помощью файлового ввода, так и с помощью API-ввода.

Дополнительную информацию о сравнении с Content API for Shopping см. в разделе Миграция управления источниками данных .

Используя API источников торговых данных, вы можете сделать следующее:

  • Создайте первичный источник данных с определенными feedLabel и contentLanguage .
  • Создайте источник данных, в котором не установлены поля feedLabel и contentLanguage . Используя этот тип источника данных, вы можете нацелить свои продукты на несколько стран, поскольку вы можете вставлять продукты с различными комбинациями feedLabel и contentLanguage в один источник данных.
  • Создайте дополнительный источник данных для связи с существующим основным источником данных.
  • Настройте расписание для источника данных файла.
  • Зарегистрируйте свою учетную запись для автоматического управления источниками данных.
  • Управление источниками данных API.
  • Управляйте правилом источников данных по умолчанию, используя основные источники данных о продуктах.
  • Настройте destinations (также известные как методы маркетинга) для источников данных о продуктах.
  • Используйте другие типы источников данных, например, рекламные акции.
  • Создайте первичный источник данных с определенными feedLabel и contentLanguage .
  • Создайте источник данных, в котором не установлены поля feedLabel и contentLanguage . Используя этот тип источника данных, вы можете нацелить свои продукты на несколько стран, поскольку вы можете вставлять продукты с различными комбинациями feedLabel и contentLanguage в один источник данных.
  • Создайте дополнительный источник данных для связи с существующим основным источником данных.
  • Настройте расписание для источника данных файла.
  • Зарегистрируйте свою учетную запись для автоматического управления источниками данных.
  • Управление источниками данных API.
  • Управляйте правилом источников данных по умолчанию, используя основные источники данных о продуктах.
  • Настройте destinations (также известные как методы маркетинга) для источников данных о продуктах.
  • Используйте другие типы источников данных, например, рекламные акции.

Дополнительную информацию о каналах источников данных см. в разделе Обзор каналов и источников данных .

Первичные источники данных — это основные источники данных для вашего инвентаря Merchant Center. Вы можете добавлять или удалять продукты только с помощью первичного источника данных. Если каждый продукт, который вы добавляете в первичный источник данных, соответствует требованиям Merchant Center и требованиям соответствия, вам не нужно будет создавать дополнительные источники данных.

Чтобы создать первичный источник данных с определенными feedLabel и contentLanguage , задайте поля feedLabel и contentLanguage в конфигурации, специфичной для типа. Для получения дополнительной информации об этих полях см. PrimaryProductDataSource .

Следующий пример запроса демонстрирует, как создать основной источник данных о продукте:

Более подробную информацию об этих полях см. в разделе PrimaryProductDataSource .

Следующий пример запроса демонстрирует, как создать основной источник данных о продукте:

POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources

{
  "displayName": "{DISPLAY_NAME}",
  "primaryProductDataSource": {
    "contentLanguage": "{CONTENT_LANGUAGE}",
    "feedLabel": "{FEED_LABEL}",
    "countries": [
      "{COUNTRY}"
    ],
    "channel": "ONLINE_PRODUCTS"
  }
}

Заменить следующее:

  • {ACCOUNT_ID} : уникальный идентификатор вашей учетной записи Merchant Center.
  • {DISPLAY_NAME} : отображаемое имя источника данных.
  • {CONTENT_LANGUAGE} : двухбуквенный код языка ISO 639-1 для продуктов в источнике данных.
  • {FEED_LABEL} : метка фида источника данных.
  • {COUNTRY} : код территории CLDR целевой страны продуктов, которые будут загружены с использованием источника данных.

После успешного выполнения запроса вы увидите следующий ответ:

{
  "name": "accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}",
  "dataSourceId": "{DATASOURCE_ID}",
  "displayName": "{DISPLAY_NAME}",
  "primaryProductDataSource": {
    "channel": "ONLINE_PRODUCTS",
    "feedLabel": "{FEED_LABEL}",
    "contentLanguage": "{CONTENT_LANGUAGE}",
    "countries": [
      "{COUNTRY}"
    ],
    "destinations": [
      {
        "id": "SHOPPING_ADS",
        "state": "ENABLED"
      },
      {
        "id": "FREE_LISTINGS",
        "state": "ENABLED"
      }
    ]
    "defaultRule": {
      "takeFromDataSources": [
        {
          "self": true
        }
      ]
    }
  },
  "input": "API"
}

Поле destinations непустое, поскольку для источника данных включены места назначения по умолчанию.

Дополнительную информацию о создании источника данных см. в методе accounts.dataSources.create .

Чтобы просмотреть недавно созданный источник данных, используйте метод accounts.dataSources.get или accounts.dataSources.list .

В следующем примере показано, как можно создать основной источник данных о продукте для комбинации GB и en feedLabel и contentLanguage .

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.CreateDataSourceRequest;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.PrimaryProductDataSource;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to create a primary product datasource for all `feedLabel` and
 * `contentLanguage` combinations. Note that rules functionality is limited for wildcard feeds.
 */
public class CreatePrimaryProductDataSourceWildCardSample {

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

  public static String createDataSource(Config config, String displayName) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String parent = getParent(config.getAccountId().toString());

    // The type of data that this datasource will receive.
    PrimaryProductDataSource primaryProductDataSource =
        PrimaryProductDataSource.newBuilder()
            // Channel can be "ONLINE_PRODUCTS" or "LOCAL_PRODUCTS" or "PRODUCTS" .
            // While accepted, datasources with channel "products" representing unified products
            // currently cannot be used with the Products bundle.
            .setChannel(PrimaryProductDataSource.Channel.ONLINE_PRODUCTS)
            .addCountries("GB")
            .build();

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      CreateDataSourceRequest request =
          CreateDataSourceRequest.newBuilder()
              .setParent(parent)
              .setDataSource(
                  DataSource.newBuilder()
                      .setDisplayName(displayName)
                      .setPrimaryProductDataSource(primaryProductDataSource)
                      .build())
              .build();

      System.out.println("Sending Create PrimaryProduct DataSource request");
      DataSource response = dataSourcesServiceClient.createDataSource(request);
      System.out.println("Created DataSource Name below");
      System.out.println(response.getName());
      return response.getName();
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      // Null is necessary to satisfy the compiler as we're not returning a String on failure.
      return null;
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The displayed datasource name in the Merchant Center UI.
    String displayName = "Primary Product Data Wildcard";

    createDataSource(config, displayName);
  }
}

Создайте основной источник данных, который поможет охватить несколько стран

Чтобы создать основной фид, который поможет вам охватить несколько стран, настройте источник данных с помощью PrimaryProductDataSource и не задавайте поля feedLabel и contentLanguage .

Используя API контента для покупок, для вас создается только один источник данных API. Используя API источников данных торговца, вы можете иметь несколько источников данных API, некоторые из которых могут быть без установленных полей feedLabel и contentLanguage .

Только источники данных с API input могут быть без установленных полей feedLabel и contentLanguage . Этот тип источников данных не поддерживается для file inputs.

Создайте дополнительный источник данных и свяжите его с основным источником данных.

Дополнительные источники данных используются только для обновления данных о продуктах, которые уже существуют в одном или нескольких основных источниках данных. У вас может быть несколько дополнительных источников данных, и каждый из них может дополнять данные в любом количестве основных источников данных.

Вы можете использовать дополнительные источники данных для частичного обновления данных о продуктах, добавив уникальный идентификатор источника данных в качестве параметра запроса при вызове методов accounts.productInputs.insert и accounts.productInputs.delete . Вы можете использовать только дополнительные источники данных для обновления существующих продуктов.

Чтобы создать дополнительный источник данных, настройте свой источник данных с помощью SupplementalProductDataSource , а затем свяжите его, обновив поле defaultRule в вашем основном источнике данных.

В дополнительных источниках данных файлов должны быть установлены поля feedLabel и contentLanguage . В дополнительных источниках данных API поля feedLabel и contentLanguage всегда должны быть не установлены.

В следующем примере показано, как можно создать дополнительный источник данных о продукте для комбинации en и GB contentLanguage и feedLabel .

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.CreateDataSourceRequest;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.FileInput;
import com.google.shopping.merchant.datasources.v1beta.SupplementalProductDataSource;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to create a File Supplemental product datasource for the "en" and
 * "GB" `feedLabel` and `contentLanguage` combination. This supplemental feed is eligible to be
 * linked to both a wildcard primary feed and/or a primary feed with the same `feedLabel` and
 * `contentLanguage` combination.
 */
public class CreateFileSupplementalProductDataSourceSample {

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

  private static FileInput setFileInput() {
    // If FetchSettings are not set, then this will be an `UPLOAD` file type
    // that you must manually upload via the Merchant Center UI.
    return FileInput.newBuilder()
        // FileName is required for `UPLOAD` fileInput type.
        .setFileName("British T-shirts Supplemental Data")
        .build();
  }

  public static String createDataSource(Config config, String displayName, FileInput fileInput)
      throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String parent = getParent(config.getAccountId().toString());

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      CreateDataSourceRequest request =
          CreateDataSourceRequest.newBuilder()
              .setParent(parent)
              .setDataSource(
                  DataSource.newBuilder()
                      .setDisplayName(displayName)
                      .setSupplementalProductDataSource(
                          SupplementalProductDataSource.newBuilder()
                              .setContentLanguage("en")
                              .setFeedLabel("GB")
                              .build())
                      .setFileInput(fileInput)
                      .build())
              .build();

      System.out.println("Sending create SupplementalProduct DataSource request");
      DataSource response = dataSourcesServiceClient.createDataSource(request);
      System.out.println("Created DataSource Name below");
      System.out.println(response.getName());
      return response.getName();
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      // Null is necessary to satisfy the compiler as we're not returning a String on failure.
      return null;
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The displayed datasource name in the Merchant Center UI.
    String displayName = "British File Supplemental Product Data";

    // The file input data that this datasource will receive.
    FileInput fileInput = setFileInput();

    createDataSource(config, displayName, fileInput);
  }
}

Чтобы создать дополнительный источник данных, который работает для всех комбинаций feedLabel и contentLanguage , запустите следующий пример.

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.CreateDataSourceRequest;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.SupplementalProductDataSource;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to create a Supplemental product datasource all `feedLabel` and
 * `contentLanguage` combinations. This works only for API supplemental feeds.
 */
public class CreateSupplementalProductDataSourceWildCardSample {

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

  public static String createDataSource(Config config, String displayName) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String parent = getParent(config.getAccountId().toString());

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      CreateDataSourceRequest request =
          CreateDataSourceRequest.newBuilder()
              .setParent(parent)
              .setDataSource(
                  DataSource.newBuilder()
                      .setDisplayName(displayName)
                      .setSupplementalProductDataSource(
                          SupplementalProductDataSource.newBuilder().build())
                      .build())
              .build();

      System.out.println("Sending create SupplementalProduct DataSource request");
      DataSource response = dataSourcesServiceClient.createDataSource(request);
      System.out.println("Created DataSource Name below");
      System.out.println(response.getName());
      return response.getName();
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      return null; // Necessary to satisfy the compiler as we're not returning a
      // String on failure.
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The displayed datasource name in the Merchant Center UI.
    String displayName = "Supplemental API Product Data Wildcard";

    createDataSource(config, displayName);
  }
}

Настройте расписание для вашего источника данных файла

Чтобы настроить расписание для вашего файла, настройте свой источник данных как файловый источник данных с помощью поля FileInput , а затем настройте fetchsettings с помощью поля FileInput.FetchSettings .

Удалить источник данных

Чтобы удалить существующий источник данных из вашей учетной записи, используйте метод accounts.dataSources.delete .

В следующем примере показано, как можно использовать пакет DeleteDataSourceRequest для удаления источника данных.

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.DataSourceName;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.DeleteDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to delete a datasource. */
public class DeleteDataSourceSample {

  public static void deleteDataSource(Config config, String dataSourceId) throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    String name =
        DataSourceName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setDatasource(dataSourceId)
            .build()
            .toString();

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {
      DeleteDataSourceRequest request = DeleteDataSourceRequest.newBuilder().setName(name).build();

      System.out.println("Sending deleteDataSource request");
      // Delete works for any datasource type.
      // If Type "Supplemental", delete will only work if it's not linked to any primary feed.
      // If a link exists and the Type is "Supplemental", you will need to remove the supplemental
      // feed from the default and/or custom rule(s) of any primary feed(s) that references it. Then
      // retry the delete.

      dataSourcesServiceClient.deleteDataSource(request); // No response returned on success.
      System.out.println(
          "Delete successful, note that it may take a few minutes for the delete to update in"
              + " the system.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID automatically assigned to the datasource after creation by Google.
    String dataSourceId = "1111111111"; // Replace with your datasource ID.

    deleteDataSource(config, dataSourceId);
  }
}

Получить источник данных

Чтобы получить файл, настроенный в источнике данных, используйте метод accounts.dataSources.fetch . Этот метод выполняет немедленную выборку данных в источнике данных из вашей учетной записи. Этот метод работает только с источниками данных с установленным входным файлом.

Получить источник данных

Чтобы получить конфигурацию источника данных для вашей учетной записи, используйте метод accounts.dataSources.get .

В следующем примере показано, как можно использовать пакет GetDataSourceRequest для получения определенного источника данных для заданной учетной записи Merchant Center.

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourceName;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.GetDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to get a specific datasource for a given Merchant Center account. */
public class GetDataSourceSample {

  public static DataSource getDataSource(Config config, String dataSourceId) throws Exception {

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

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

    // Creates datasource name to identify datasource.
    String name =
        DataSourceName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setDatasource(dataSourceId)
            .build()
            .toString();

    // Calls the API and catches and prints any network failures/errors.
    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      // The name has the format: accounts/{account}/datasources/{datasource}
      GetDataSourceRequest request = GetDataSourceRequest.newBuilder().setName(name).build();

      System.out.println("Sending GET DataSource request:");
      DataSource response = dataSourcesServiceClient.getDataSource(request);

      System.out.println("Retrieved DataSource below");
      System.out.println(response);
      return response;
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      return null; // Necessary to satisfy the compiler as we're not returning a
      // DataSource on failure.
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // An ID assigned to a datasource by Google.
    String datasourceId = "1111111111"; // Replace with your datasource ID.

    getDataSource(config, datasourceId);
  }
}

Список источников данных

Чтобы вывести список конфигураций источников данных для вашей учетной записи, используйте метод accounts.dataSources.list .

В следующем примере показано, как можно использовать пакет ListDataSourceRequest для вывода списка всех источников данных для заданной учетной записи Merchant Center.

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient.ListDataSourcesPagedResponse;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.ListDataSourcesRequest;
import java.util.ArrayList;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to list all the datasources for a given Merchant Center account */
public class ListDataSourcesSample {

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

  public static ArrayList<DataSource> listDataSources(Config config) throws Exception {

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

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

    // Creates parent to identify the account from which to list all the datasources.
    String parent = getParent(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      // The parent has the format: accounts/{account}
      ListDataSourcesRequest request =
          ListDataSourcesRequest.newBuilder().setParent(parent).build();

      System.out.println("Sending list datasources request:");
      ListDataSourcesPagedResponse response = dataSourcesServiceClient.listDataSources(request);

      int count = 0;
      ArrayList<DataSource> dataSources = new ArrayList<DataSource>();
      ArrayList<DataSource> justPrimaryDataSources = new ArrayList<DataSource>();

      // Iterates over all rows in all pages and prints the datasource in each row.
      // Automatically uses the `nextPageToken` if returned to fetch all pages of data.
      for (DataSource element : response.iterateAll()) {
        System.out.println(element);
        count++;
        dataSources.add(element);
        // The below lines show how to filter datasources based on type.
        // `element.hasSupplementalProductDataSource()` would give you supplemental
        // datasources, etc.
        if (element.hasPrimaryProductDataSource()) {
          justPrimaryDataSources.add(element);
        }
      }
      System.out.print("The following count of elements were returned: ");
      System.out.println(count);
      return dataSources;
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      return null; // Necessary to satisfy the compiler as we're not returning an
      // ArrayList<DataSource> on failure.
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    listDataSources(config);
  }
}

Источник данных исправления

Чтобы обновить конфигурацию существующего источника данных, используйте метод accounts.dataSources.patch .

Чтобы обновить отображаемое имя существующего источника данных, выполните следующий запрос PATCH .

PATCH https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}?updateMask=displayName

{
  "displayName": "New display name"
}

Возвращается следующий ответ JSON. Запрос обновляет только displayName источника данных, а все остальные поля остаются без изменений.

{
  "name": "accounts/ACCOUNT_ID/dataSources/DATASOURCE_ID",
  "dataSourceId": "DATASOURCE_ID",
  "displayName": "New display name",
  "primaryProductDataSource": {
    "channel": "ONLINE_PRODUCTS",
    "feedLabel": "IN",
    "contentLanguage": "en",
    "defaultRule": {
      "takeFromDataSources": [
        {
          "self": true
        }
      ]
    },
    "destinations": [
      {
        "destination": "FREE_LISTINGS",
        "state": "ENABLED"
      }
    ]
  },
  "input": "API"
}

Следующий пример демонстрирует, как можно использовать пакет UpdateDataSourceRequest для обновления источника данных. Он также демонстрирует, как обновить первичный источник данных, чтобы добавить дополнительные источники данных к его правилу по умолчанию.

Ява

    import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.datasources.v1beta.DataSource;
import com.google.shopping.merchant.datasources.v1beta.DataSourceName;
import com.google.shopping.merchant.datasources.v1beta.DataSourceReference;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceClient;
import com.google.shopping.merchant.datasources.v1beta.DataSourcesServiceSettings;
import com.google.shopping.merchant.datasources.v1beta.PrimaryProductDataSource;
import com.google.shopping.merchant.datasources.v1beta.PrimaryProductDataSource.DefaultRule;
import com.google.shopping.merchant.datasources.v1beta.UpdateDataSourceRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/**
 * This class demonstrates how to update a datasource to change its name in the MC UI. It also
 * demonstrates how to update a primary datasource to add supplemental datasources to its default
 * rule (https://support.google.com/merchants/answer/7450276).
 */
public class UpdateDataSourceSample {

  public static String updateDataSource(Config config, String displayName, String dataSourceId)
      throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates datasource name to identify datasource.
    String name =
        DataSourceName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .setDatasource(dataSourceId)
            .build()
            .toString();

    DataSource dataSource =
        DataSource.newBuilder()
            // Update the datasource to have the new display name
            .setDisplayName(displayName)
            .setName(name)
            .build();

    FieldMask fieldMask = FieldMask.newBuilder().addPaths("display_name").build();

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      UpdateDataSourceRequest request =
          UpdateDataSourceRequest.newBuilder()
              .setDataSource(dataSource)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending Update DataSource request");
      DataSource response = dataSourcesServiceClient.updateDataSource(request);
      System.out.println("Updated DataSource Name below");
      System.out.println(response.getName());
      return response.getName();
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      return null;
    }
  }

  public String updateDataSource(
      Config config,
      String primaryDataSourceName,
      String firstSupplementalDataSourceName,
      String secondSupplementalDataSourceName)
      throws Exception {
    GoogleCredentials credential = new Authenticator().authenticate();

    DataSourcesServiceSettings dataSourcesServiceSettings =
        DataSourcesServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Setting self to 'true' refers to the primary datasource itself.
    DataSourceReference dataSourceReferenceSelf =
        DataSourceReference.newBuilder().setSelf(true).build();
    DataSourceReference firstSupplementalDataSourceReference =
        DataSourceReference.newBuilder()
            .setSupplementalDataSourceName(firstSupplementalDataSourceName)
            .build();
    DataSourceReference secondSupplementalDataSourceReference =
        DataSourceReference.newBuilder()
            .setSupplementalDataSourceName(secondSupplementalDataSourceName)
            .build();

    // The attributes will first be taken from the primary DataSource.
    // Then the first supplemental DataSource if the attribute is not in the primary DataSource
    // And finally the second supplemental DataSource if not in the first two DataSources.
    // Note that CustomRules could change the behavior of how updates are applied.
    DefaultRule defaultRule =
        DefaultRule.newBuilder()
            .addTakeFromDataSources(dataSourceReferenceSelf)
            .addTakeFromDataSources(firstSupplementalDataSourceReference)
            .addTakeFromDataSources(secondSupplementalDataSourceReference)
            .build();

    // The type of data that this datasource will receive.
    PrimaryProductDataSource primaryProductDataSource =
        PrimaryProductDataSource.newBuilder().setDefaultRule(defaultRule).build();

    DataSource dataSource =
        DataSource.newBuilder()
            // Update the primary datasource to have the default rule datasources in the correct
            // order.
            .setPrimaryProductDataSource(primaryProductDataSource)
            .setName(primaryDataSourceName)
            .build();

    // The '.' signifies a nested field.
    FieldMask fieldMask =
        FieldMask.newBuilder().addPaths("primary_product_data_source.default_rule").build();

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {

      UpdateDataSourceRequest request =
          UpdateDataSourceRequest.newBuilder()
              .setDataSource(dataSource)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending Update DataSource request");
      DataSource response = dataSourcesServiceClient.updateDataSource(request);
      System.out.println("Updated DataSource Name below");
      System.out.println(response.getName());
      return response.getName();
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
      return null;
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The updated displayed datasource name in the Merchant Center UI.
    String displayName = "Great Britain Primary Product Data";

    // The ID of the datasource to update
    String dataSourceId = "11111111"; // Replace with your datasource ID.

    updateDataSource(config, displayName, dataSourceId);
  }
}

Управление правилами источника данных

Первичные источники данных о продуктах позволяют управлять правилом по умолчанию для источников данных. Правило по умолчанию — это правило, которое применяется ко всем атрибутам в вашем источнике данных. Правило по умолчанию можно задать при создании источника данных или путем обновления существующего источника данных через поле правила по умолчанию.

Дополнительную информацию о настройке правил см. в разделе Настройка правил для источников данных о продуктах .

Следующий пример конфигурации гарантирует, что все атрибуты сначала берутся из источника данных с уникальным идентификатором 1001 Затем отсутствующие атрибуты добавляются из основного источника данных. В конечном итоге оставшиеся атрибуты будут взяты из дополнительного источника данных с уникальным идентификатором 1002 , если они еще не предоставлены в каком-либо другом источнике данных. Если один и тот же атрибут предоставляется в нескольких источниках данных, выбирается значение выше в списке.

defaultRule {
 takeFromDataSources: [
   '1001', // Supplemental product data source
   'self', //  Self reference to the primary data source
   '1002' // Supplemental product data source
 ]
}

Автоматическое управление источниками данных

Автоматизированные источники данных облегчают отправку данных о ваших продуктах в Google. Эти источники данных гарантируют, что самая актуальная информация о соответствующих продуктах с вашего веб-сайта попадет в Google.

Чтобы зарегистрировать свою учетную запись для автоматического управления источниками данных, вам необходимо выполнить следующие действия:

После того, как ваша учетная запись будет готова к регистрации, выполните следующие действия:

  1. Включите настройки автоподачи, чтобы автоматически создать источник данных. Примечание: в запросе на обновление поле Name должно быть пустым. В update_mask field перечислите поля, которые вы хотите изменить (например, enableProducts ). Затем в теле укажите фактическое значение (например, enableProducts=false ).

    PATCH https://merchantapi.googleapis.com/accounts/v1beta/accounts/{ACCOUNT_ID}/autofeedSettings?updateMask={UPDATE_MASK}
    
    {
      "enableProducts": {ENABLE_PRODUCTS}
    }
    

    Заменить следующее:

    • {ACCOUNT_ID} : уникальный идентификатор вашей учетной записи Merchant Center.
    • {UPDATE_MASK} : список полей, которые вы хотите изменить.
    • {ENABLE_PRODUCTS} : следует ли включить автоматическое управление продуктами.
  2. Используйте метод accounts.autofeedSettings.updateAutofeedSettings для включения автоматического управления источниками данных. Включение автоматического управления источниками данных позволяет Google автоматически добавлять продукты из вашего интернет-магазина и гарантировать, что они всегда будут актуальны на платформах Google.

Получить статус загрузки файла

Чтобы получить статус источника данных с помощью файла, выборки или электронной таблицы, можно вызвать метод GET службы accounts.dataSources.fileUploads . Чтобы получить результат последнего извлечения источника данных, вычисленный асинхронно по завершении обработки источника данных, используйте идентификатор имени latest .

GET https://merchantapi.googleapis.com/accounts/v1beta/{ACCOUNT_ID}/datasources/{DATASOURCE_ID}/fileUploads/latest

Статус загрузки файла может содержать подробную информацию о ваших продуктах, включая любые потенциальные проблемы.

Обратите внимание, что статус загрузки файла может отсутствовать, если файл никогда не был загружен. Статус загрузки файла может находиться в состоянии обработки, если запрос был сделан вскоре после загрузки файла.