Merchant API는 비즈니스 요구사항에 따라 제품 관련 정보를 제공하기 위해 여러 유형의 데이터 소스와 입력 방법을 지원합니다. 데이터 소스에는 다음과 같은 다양한 유형의 데이터가 포함될 수 있습니다.
- 제품
- 인벤토리
- promotion
- 리뷰
다음과 같은 여러 방법을 사용하여 데이터 소스를 구성할 수 있습니다.
- API 호출
- 파일 업로드
- 자동 피드
데이터 소스 하위 API를 통해 관리할 수 있는 일부 데이터 소스 유형 (예: 제품 또는 프로모션)을 지원되는 여러 입력 방법 (API, 파일 업로드 또는 파일 가져오기)과 결합할 수 있습니다. 예를 들어 기본 제품 데이터 소스는 다음 중 하나일 수 있습니다.
- API 피드
- 가져온 파일 피드
- 업로드된 파일 피드
- 자동 피드
이 가이드에서는 다양한 유형의 데이터와 입력 방법을 사용하여 데이터 소스를 관리하는 예를 제공합니다.
특별 고려사항
일부 데이터 소스 유형의 경우 다음 특별 고려사항을 고려하세요.
- 읽기 전용 데이터 소스: 일부 데이터 소스 유형은 데이터 소스 하위 API를 통해 읽기 전용입니다. 즉, 이 API를 사용하여 나열하고 세부정보를 볼 수는 있지만 만들거나 업데이트하거나 삭제할 수는 없습니다. 예를 들면 다음과 같습니다.
- 판매자 센터 UI에서 직접 관리되는 제품이 있는 데이터 소스(입력 유형
UI
) - 자동 피드 (입력 유형
AUTOFEED
). 자동 피드 자체는 데이터 소스 하위 API 내에서 읽기 전용이지만 계정 하위 API의autofeedSettings
메서드를 사용하여 계정의 자동 피드 기능을 사용 설정하거나 중지할 수 있습니다. 자세한 내용은 자동 피드 설정 구성 섹션을 참고하세요.
- 판매자 센터 UI에서 직접 관리되는 제품이 있는 데이터 소스(입력 유형
- 피드 규칙: 데이터 소스 하위 API는 주로 보조 데이터 소스를 기본 데이터 소스에 연결하기 위한 기본 피드 규칙을 지원합니다. 복잡한 맞춤 규칙 생성 및 관리는 이 API 내에서 직접 지원되지 않습니다. 기본 규칙 내에서 보조 데이터 소스의 순서를 관리하여 기본 소스와 보조 소스의 속성이 결합되는 순서를 지정할 수 있습니다.
예약된 파일 가져오기를 사용하여 오프라인 인벤토리 데이터 소스 설정
일정에 따라 지정된 URL에서 파일을 자동으로 가져오는 오프라인 판매점 인벤토리 데이터 소스를 만들 수 있습니다. 지역 인벤토리의 유사한 데이터 소스를 만들려면 요청 본문에서 localInventoryDataSource
필드를 regionalInventoryDataSource
로 바꿉니다.
데이터 소스를 만들려면 dataSources.create
메서드를 사용하고 fetchSettings
이 구성된 fileInput
객체를 제공합니다.
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"
}
}
다음 코드 샘플은 예약된 가져오기를 사용하여 오프라인 인벤토리 데이터 소스를 만드는 방법을 보여줍니다.
자바
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 피드의 경우 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 기반 프로모션 데이터 소스를 만드는 방법을 보여줍니다.
자바
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
을 지정하고 지정된 fileName
이 있는 fileInput
을 포함합니다.
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
객체로 대체하여 유사한 요청을 사용하면 됩니다.
다음 코드 샘플은 수동 파일 업로드를 위한 제품 리뷰 데이터 소스를 만드는 방법을 보여줍니다.
자바
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"
}
}'
자동 피드 설정 구성
자동 피드는 웹사이트의 콘텐츠를 기반으로 제품 데이터를 자동으로 생성합니다.
자동 피드 데이터 소스 자체는 데이터 소스 하위 API 내에서 읽기 전용이지만 계정 하위 API의 autofeedSettings.update
메서드를 사용하여 계정의 자동 피드 기능을 사용 설정하거나 사용 중지할 수 있습니다.
이 예에서는 계정의 자동 피드를 통해 제품 크롤링을 사용 설정합니다.
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
}
다음 코드 샘플은 계정의 자동 피드 설정을 사용 설정하는 방법을 보여줍니다.
자바
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
}'