管理各种数据源类型

Merchant API 支持多种类型的数据源和输入方法,可根据您的业务需求提供与商品相关的信息。数据源可以包含不同类型的数据:

  • 产品
  • inventory
  • promotion
  • 回看录像

您可以使用多种方法配置数据源,包括:

您可以通过数据源子 API 管理某些数据源类型(例如商品或促销活动),并结合使用多种受支持的输入方法(API、文件上传或文件提取)。例如,主要商品数据源可以是以下任一类型:

  • API Feed
  • 已提取的文件 Feed
  • 已上传的文件 Feed
  • 自动 Feed

本指南提供了有关如何管理数据源的示例,这些数据源包含各种类型的数据和输入方法。

特殊注意事项

请注意,某些数据源类型存在以下特殊注意事项。

  • 只读数据源:某些数据源类型通过“数据源”子 API 只能进行读取。这意味着,您可以使用此 API 列出这些资源并查看其详细信息,但无法创建、更新或删除这些资源。其中包括:
    • 直接在 Merchant Center 界面中管理商品的数据源(输入类型为 UI)。
    • 自动 Feed(输入类型 AUTOFEED)。虽然自动 Feed 本身在“数据源”子 API 中是只读的,但您可以使用“账号”子 API 中的 autofeedSettings 方法为账号启用或停用自动 Feed 功能。如需了解详情,请参阅配置自动进纸设置部分。
  • Feed 规则:数据源子 API 主要支持用于将补充数据源与主要数据源相关联的默认 Feed 规则。此 API 不直接支持创建和管理复杂的自定义规则。您可以在默认规则中管理补充数据源的顺序,以指定主要来源和补充来源的属性的组合顺序。

设置具有预定文件提取功能的本地商品目录数据源

您可以创建本地商品目录数据源,该数据源会按预定时间表自动从指定网址提取文件。如需为区域性商品目录创建类似的数据源,请将请求正文中的 localInventoryDataSource 字段替换为 regionalInventoryDataSource

如需创建数据源,请使用 dataSources.create 方法,并提供配置了 fetchSettingsfileInput 对象。

POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources
{
  "displayName": "My Scheduled Local Inventory Feed",
  "localInventoryDataSource": {
    "feedLabel": "US_Stores",
    "contentLanguage": "en"
  },
  "fileInput": {
    "fetchSettings": {
      "enabled": true,
      "timeOfDay": {
        "hours": 23
      },
      "timeZone": "America/New_York",
      "frequency": "FREQUENCY_DAILY",
      "fetchUri": "https://www.example.com/inventory/local_inventory_feed.csv"
    }
  }
}

如果请求成功,则会返回创建的 DataSource 资源。

{
  "name": "accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}",
  "dataSourceId": "{DATASOURCE_ID}",
  "displayName": "My Scheduled Local Inventory Feed",
  "localInventoryDataSource": {
    "feedLabel": "US_Stores",
    "contentLanguage": "en"
  },
  "input": "FILE",
  "fileInput": {
    "fetchSettings": {
      "enabled": true,
      "timeOfDay": {
        "hours": 23
      },
      "timeZone": "America/New_York",
      "frequency": "FREQUENCY_DAILY",
      "fetchUri": "https://www.example.com/inventory/local_inventory_feed.csv"
    },
    "fileInputType": "FETCH"
  }
}

以下代码示例展示了如何创建具有预定提取功能的本地商品目录数据源。

Java

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.LocalInventoryDataSource;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create a local inventory datasource */
public class CreateFileLocalInventoryDataSourceSample {

  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 Local Inventory 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());

    // As LocalInventoryDataSources are a type of file feed, therefore wildcards are not available.
    // LocalInventoryDataSources can only be created for a specific `feedLabel` and
    // `contentLanguage` combination.
    LocalInventoryDataSource localInventoryDataSource =
        LocalInventoryDataSource.newBuilder().setContentLanguage("en").setFeedLabel("GB").build();

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

      CreateDataSourceRequest request =
          CreateDataSourceRequest.newBuilder()
              .setParent(parent)
              .setDataSource(
                  DataSource.newBuilder()
                      .setDisplayName(displayName)
                      .setLocalInventoryDataSource(localInventoryDataSource)
                      .setFileInput(fileInput)
                      .build())
              .build();

      System.out.println("Sending Create Local Inventory DataSource request");
      DataSource response = dataSourcesServiceClient.createDataSource(request);
      System.out.println("Inserted 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 displayed datasource name in the Merchant Center UI.
    String displayName = "British Local Inventory File";

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

    createDataSource(config, displayName, fileInput);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\DataSources\V1beta\Client\DataSourcesServiceClient;
use Google\Shopping\Merchant\DataSources\V1beta\CreateDataSourceRequest;
use Google\Shopping\Merchant\DataSources\V1beta\DataSource;
use Google\Shopping\Merchant\DataSources\V1beta\FileInput;
use Google\Shopping\Merchant\DataSources\V1beta\LocalInventoryDataSource;

/**
 * This class demonstrates how to create a local inventory datasource with a 
 * file input.
 */
class CreateFileLocalInventoryDataSourceSample
{

    private static function getFileInput(): FileInput
    {
        // If FetchSettings is not set, then this will be an `UPLOAD` file type
        // that you must manually upload via the Merchant Center UI.
        return (new FileInput())
            // FileName is required for `UPLOAD` fileInput type.
            ->setFileName('British T-shirts Local Inventory Data');
    }

    public function createDataSource(string $merchantId, string $displayName, FileInput $fileInput): void
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $dataSourcesServiceClient = new DataSourcesServiceClient($options);

        $parent = sprintf('accounts/%s', $merchantId);

        // As LocalInventoryDataSources are a type of file feed, therefore wildcards are not available.
        // LocalInventoryDataSources can only be created for a specific `feedLabel` and
        // `contentLanguage` combination.
        $localInventoryDataSource =
            (new LocalInventoryDataSource())
                ->setContentLanguage('en')
                ->setFeedLabel('GB');

        try {
            // Prepare the request message.
            $request = (new CreateDataSourceRequest())
                ->setParent($parent)
                ->setDataSource(
                    (new DataSource())
                        ->setDisplayName($displayName)
                        ->setLocalInventoryDataSource($localInventoryDataSource)
                        ->setFileInput($fileInput)
                );

            print('Sending Create Local Inventory DataSource request' . PHP_EOL);
            $response = $dataSourcesServiceClient->createDataSource($request);
            print('Inserted DataSource Name below' . PHP_EOL);
            print($response->getName() . PHP_EOL);
        } catch (ApiException $ex) {
            printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
        }
    }

    // Helper to execute the sample.
    function callSample(): void
    {
        $config = Config::generateConfig();
        // The Merchant Center Account ID.
        $merchantId = $config['accountId'];

        // The displayed datasource name in the Merchant Center UI.
        $displayName = 'British Primary Inventory File';

        $fileInput = self::getFileInput();

        $this->createDataSource($merchantId, $displayName, $fileInput);
    }

}

$sample = new CreateFileLocalInventoryDataSourceSample();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_datasources_v1beta import CreateDataSourceRequest
from google.shopping.merchant_datasources_v1beta import DataSource
from google.shopping.merchant_datasources_v1beta import DataSourcesServiceClient
from google.shopping.merchant_datasources_v1beta import FileInput
from google.shopping.merchant_datasources_v1beta import LocalInventoryDataSource

_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"


def create_file_local_inventory_data_source():
  """Creates a `DataSource` resource."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = DataSourcesServiceClient(credentials=credentials)

  # If FetchSettings are not set, then this will be an `UPLOAD` file type
  # that you must manually upload via the Merchant Center UI or via SFTP.
  file_input = FileInput()
  file_input.file_name = "British T-shirts Local Inventory Data.txt"

  # Creates a SupplementalProductDataSource.
  local_inventory_datasource = LocalInventoryDataSource()
  # As LocalInventoryDataSources are a type of file feed, wildcards are not
  # available. LocalInventoryDataSources can only be created for a specific
  # `feedLabel` and `contentLanguage` combination.
  local_inventory_datasource.content_language = "en"
  local_inventory_datasource.feed_label = "GB"

  # Creates a DataSource and populates its attributes.
  data_source = DataSource()
  data_source.display_name = "Example Local Inventory DataSource"
  data_source.local_inventory_data_source = local_inventory_datasource
  data_source.file_input = file_input

  # Creates the request.
  request = CreateDataSourceRequest(parent=_PARENT, data_source=data_source)

  # Makes the request and catches and prints any error messages.
  try:
    response = client.create_data_source(request=request)
    print(f"DataSource successfully created: {response}")
  except RuntimeError as e:
    print("DataSource creation failed")
    print(e)


if __name__ == "__main__":
  create_file_local_inventory_data_source()

cURL

curl -X POST \
"https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources" \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
      "displayName": "My Scheduled Local Inventory Feed",
      "localInventoryDataSource": {
        "feedLabel": "US_Stores",
        "contentLanguage": "en"
      },
      "fileInput": {
        "fetchSettings": {
          "enabled": true,
          "timeOfDay": {
            "hours": 23
          },
          "timeZone": "America/New_York",
          "frequency": "FREQUENCY_DAILY",
          "fetchUri": "https://www.example.com/inventory/local_inventory_feed.csv"
        }
      }
    }'

使用 API 建立促销活动数据源

通过促销活动数据源,您可以提交商品的促销优惠。您可以为促销活动创建基于 API 的数据源,这样一来,您就可以直接发送促销活动数据,而无需管理文件。

使用 dataSources.create 方法并指定 promotionDataSource。对于 API Feed,请省略 fileInput 字段。

POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources
{
  "displayName": "My API Promotions Source",
  "promotionDataSource": {
    "targetCountry": "US",
    "contentLanguage": "en"
  }
}

如果请求成功,则会返回新创建的 DataSource 资源。

{
  "name": "accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}",
  "dataSourceId": "{DATASOURCE_ID}",
  "displayName": "My API Promotions Source",
  "promotionDataSource": {
    "targetCountry": "US",
    "contentLanguage": "en"
  },
  "input": "API"
}

以下代码示例展示了如何创建基于 API 的促销活动数据源。

Java

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.PromotionDataSource;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create a promotion datasource. */
public class CreatePromotionDataSourceSample {

  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)
                      // Wildcards are not available for PromotionDataSources. PromotionDataSources
                      // can only be created for a specific `targetCountry` and `contentLanguage`
                      // combination.
                      .setPromotionDataSource(
                          PromotionDataSource.newBuilder()
                              .setContentLanguage("en")
                              .setTargetCountry("GB")
                              .build())
                      .build())
              .build();

      System.out.println("Sending Create Promotion DataSource request");
      DataSource response = dataSourcesServiceClient.createDataSource(request);
      System.out.println("Inserted 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 displayed datasource name in the Merchant Center UI.
    String displayName = "British Promotions";

    createDataSource(config, displayName);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\DataSources\V1beta\Client\DataSourcesServiceClient;
use Google\Shopping\Merchant\DataSources\V1beta\CreateDataSourceRequest;
use Google\Shopping\Merchant\DataSources\V1beta\DataSource;
use Google\Shopping\Merchant\DataSources\V1beta\PromotionDataSource;

/**
 * This class demonstrates how to create a promotion datasource.
 */

class CreatePromotionDataSource
{
    /**
     * Creates a new PromotionDataSource.
     *
     * @param int    $merchantId The Merchant Center account ID.
     * @param string $displayName The displayed datasource name in the Merchant Center UI.
     * @return string The name of the newly created PromotionDataSource.
     */
    function createPromotionDataSourceSample(int $merchantId, string $displayName): string
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $dataSourcesServiceClient = new DataSourcesServiceClient($options);

        $parent = sprintf('accounts/%s', $merchantId);

        // Creates the data source.
        $dataSource = (new DataSource())
            ->setDisplayName($displayName)
            ->setPromotionDataSource(
                (new PromotionDataSource())
                    ->setContentLanguage('en')
                    ->setTargetCountry('GB')
            );

        // Creates the request.
        $request = (new CreateDataSourceRequest())
            ->setParent($parent)
            ->setDataSource($dataSource);

        // Sends the request to the API.
        try {
            print('Sending Create Promotion DataSource request' . PHP_EOL);
            $response = $dataSourcesServiceClient->createDataSource($request);
            print('Inserted DataSource Name below' . PHP_EOL);
            print($response->getName() . PHP_EOL);
            return $response->getName();
        } catch (ApiException $ex) {
            printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
            return '';
        }
    }

    // Helper to execute the sample.
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // The Merchant Center Account ID.
        $merchantId = $config['accountId'];

        // The displayed datasource name in the Merchant Center UI.
        $displayName = 'British Promotions';

        $this->createPromotionDataSourceSample($merchantId, $displayName);
    }
}

$sample = new CreatePromotionDataSource();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_datasources_v1beta

_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"


def create_promotion_data_source():
  """Creates a `DataSource` resource."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = merchant_datasources_v1beta.DataSourcesServiceClient(
      credentials=credentials
  )

  # Creates a PromotionDataSource.
  # Wildcards are not available for PromotionDataSources. PromotionDataSources
  # can only be created for a specific `targetCountry` and `contentLanguage`
  # combination.
  promotion_datasource = merchant_datasources_v1beta.PromotionDataSource()
  promotion_datasource.target_country = "CH"
  promotion_datasource.content_language = "fr"

  # Creates a DataSource and populates its attributes.
  data_source = merchant_datasources_v1beta.DataSource()
  data_source.display_name = "Example DataSource"
  data_source.promotion_data_source = promotion_datasource

  # Creates the request.
  request = merchant_datasources_v1beta.CreateDataSourceRequest(
      parent=_PARENT, data_source=data_source
  )

  # Makes the request and catches and prints any error messages.
  try:
    response = client.create_data_source(request=request)
    print(f"DataSource successfully created: {response}")
  except RuntimeError as e:
    print("DataSource creation failed")
    print(e)


if __name__ == "__main__":
  create_promotion_data_source()

cURL

curl -X POST \
"https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources" \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
      "displayName": "My API Promotions Source",
      "promotionDataSource": {
        "targetCountry": "US",
        "contentLanguage": "en"
      }
    }'

为文件上传创建商品评价数据源

您可以使用商品评价数据源提交客户对您商品的评价。 您可以将数据源配置为接受手动上传的产品评价文件。

使用 dataSources.create 方法,指定 productReviewDataSource,并添加包含指定 fileNamefileInput

POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources
{
  "displayName": "My Product Reviews Upload Feed",
  "productReviewDataSource": {},
  "fileInput": {
    "fileName": "product_reviews.xml"
  }
}

如果请求成功,则会返回新创建的 DataSource 资源。

{
  "name": "accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}",
  "dataSourceId": "{DATASOURCE_ID}",
  "displayName": "My Product Reviews Upload Feed",
  "productReviewDataSource": {},
  "input": "FILE",
  "fileInput": {
    "fileName": "product_reviews.xml",
    "fileInputType": "UPLOAD"
  }
}

如需为商家评价创建数据源,您可以使用类似的请求,只需将 productReviewDataSource 对象替换为空的 merchantReviewDataSource 对象即可。

以下代码示例展示了如何为手动文件上传创建商品评价数据源。

Java

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.ProductReviewDataSource;
import java.io.IOException;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create a product review data source. */
public class CreateProductReviewsDataSourceSample {

  private static void createProductReviewsDataSource(String accountId) throws IOException {

    GoogleCredentials credential = new Authenticator().authenticate();

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

    try (DataSourcesServiceClient dataSourcesServiceClient =
        DataSourcesServiceClient.create(dataSourcesServiceSettings)) {
      CreateDataSourceRequest request =
          CreateDataSourceRequest.newBuilder()
              .setParent(String.format("accounts/%s", accountId))
              .setDataSource(
                  DataSource.newBuilder()
                      .setDisplayName("Product Reviews Data Source")
                      .setProductReviewDataSource(ProductReviewDataSource.newBuilder().build())
                      .build())
              .build();

      System.out.println("Creating product reviews data source...");
      DataSource dataSource = dataSourcesServiceClient.createDataSource(request);
      System.out.println(
          String.format("Datasource created successfully: %s", dataSource.getName()));
    } catch (Exception e) {
      System.out.println(e);
      System.exit(1);
    }
  }

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

cURL

curl -X POST \
"https://merchantapi.googleapis.com/datasources/v1beta/accounts/{ACCOUNT_ID}/dataSources" \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
      "displayName": "My Product Reviews Upload Feed",
      "productReviewDataSource": {},
      "fileInput": {
        "fileName": "product_reviews.xml"
      }
    }'

配置自动 Feed 设置

自动 Feed 会根据您网站的内容自动创建商品数据。 虽然在数据源子 API 中,自动 Feed 数据源本身是只读的,但您可以使用账号子 API 中的 autofeedSettings.update 方法为账号启用或停用自动 Feed 功能。

此示例通过自动 Feed 为账号启用商品抓取功能。

PATCH https://merchantapi.googleapis.com/accounts/v1beta/accounts/{ACCOUNT_ID}/autofeedSettings?updateMask=enableProducts
{
  "name": "accounts/{ACCOUNT_ID}/autofeedSettings",
  "enableProducts": true
}

如果请求成功,则会返回更新后的 AutofeedSettings 资源。

{
  "name": "accounts/{ACCOUNT_ID}/autofeedSettings",
  "enableProducts": true,
  "eligible": true
}

以下代码示例展示了如何为账号启用自动 Feed 设置。

Java

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1beta.AutofeedSettings;
import com.google.shopping.merchant.accounts.v1beta.AutofeedSettingsName;
import com.google.shopping.merchant.accounts.v1beta.AutofeedSettingsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AutofeedSettingsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.UpdateAutofeedSettingsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to update AutofeedSettings to be enabled. */
public class UpdateAutofeedSettingsSample {

  public static void updateAutofeedSettings(Config config) throws Exception {

    GoogleCredentials credential = new Authenticator().authenticate();

    AutofeedSettingsServiceSettings autofeedSettingsServiceSettings =
        AutofeedSettingsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Creates AutofeedSettings name to identify AutofeedSettings.
    String name =
        AutofeedSettingsName.newBuilder()
            .setAccount(config.getAccountId().toString())
            .build()
            .toString();

    // Create AutofeedSettings with the updated fields.
    AutofeedSettings autofeedSettings = AutofeedSettings.newBuilder().setName(name).build();

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

    try (AutofeedSettingsServiceClient autofeedSettingsServiceClient =
        AutofeedSettingsServiceClient.create(autofeedSettingsServiceSettings)) {

      UpdateAutofeedSettingsRequest request =
          UpdateAutofeedSettingsRequest.newBuilder()
              .setAutofeedSettings(autofeedSettings)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending Update AutofeedSettings request");
      AutofeedSettings response = autofeedSettingsServiceClient.updateAutofeedSettings(request);
      System.out.println("Updated AutofeedSettings Name below");
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

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

    updateAutofeedSettings(config);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1beta\AutofeedSettings;
use Google\Shopping\Merchant\Accounts\V1beta\Client\AutofeedSettingsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\UpdateAutofeedSettingsRequest;

/**
 * This class demonstrates how to update AutofeedSettings to be enabled.
 */
class UpdateAutofeedSettingsSample
{

    /**
     * Update AutofeedSettings to be enabled.
     *
     * @param array $config The configuration data for authentication and account ID.
     * @return void
     */
    public static function updateAutofeedSettingsSample(array $config): void
    {
        // Get OAuth credentials.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Create options for the client.
        $options = ['credentials' => $credentials];

        // Create a client.
        $autofeedSettingsServiceClient = new AutofeedSettingsServiceClient($options);

        // Create the AutofeedSettings name.
        $name = "accounts/" . $config['accountId'] . "/autofeedSettings";

        // Create AutofeedSettings object.
        $autofeedSettings = (new AutofeedSettings())
            ->setName($name);

        // Create FieldMask.
        $fieldMask = (new FieldMask())
            ->setPaths(["*"]);

        // Call the API.
        try {
            // Prepare the request.
            $request = (new UpdateAutofeedSettingsRequest())
                ->setAutofeedSettings($autofeedSettings)
                ->setUpdateMask($fieldMask);

            print "Sending Update AutofeedSettings request\n";
            $response = $autofeedSettingsServiceClient->updateAutofeedSettings($request);
            print "Updated AutofeedSettings Name below\n";
            print $response->getName() . "\n";
        } catch (ApiException $e) {
            print $e->getMessage();
        }
    }

    /**
     * Helper to execute the sample.
     *
     * @return void
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();

        self::updateAutofeedSettingsSample($config);
    }
}

// Run the script
$sample = new UpdateAutofeedSettingsSample();
$sample->callSample();

Python

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.protobuf import field_mask_pb2
from google.shopping.merchant_accounts_v1beta import AutofeedSettings
from google.shopping.merchant_accounts_v1beta import AutofeedSettingsServiceClient
from google.shopping.merchant_accounts_v1beta import UpdateAutofeedSettingsRequest

_ACCOUNT = configuration.Configuration().read_merchant_info()


def update_autofeed_settings():
  """Updates the AutofeedSettings of a Merchant Center account."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = AutofeedSettingsServiceClient(credentials=credentials)

  # Creates name to identify the AutofeedSettings.
  name = "accounts/" + _ACCOUNT + "/autofeedSettings"

  # Create AutofeedSettings with the updated fields.
  autofeed_settings = AutofeedSettings(name=name, enable_products=False)

  # Create the field mask.
  field_mask = field_mask_pb2.FieldMask(paths=["enable_products"])

  # Creates the request.
  request = UpdateAutofeedSettingsRequest(
      autofeed_settings=autofeed_settings, update_mask=field_mask
  )

  # Makes the request and catches and prints any error messages.
  try:
    response = client.update_autofeed_settings(request=request)
    print("Updated AutofeedSettings Name below")
    print(response.name)
  except RuntimeError as e:
    print("Update AutofeedSettings request failed")
    print(e)


if __name__ == "__main__":
  update_autofeed_settings()

cURL

curl -X PATCH \
"https://merchantapi.googleapis.com/accounts/v1beta/accounts/{ACCOUNT_ID}/autofeedSettings?updateMask=enableProducts" \
-H "Authorization: Bearer <API_TOKEN>" \
-H "Content-Type: application/json" \
-d '{
      "name": "accounts/{ACCOUNT_ID}/autofeedSettings",
      "enableProducts": true
    }'