Z tej strony dowiesz się, jak przesyłać produkty i zarządzać nimi za pomocą programowania. Za pomocą interfejsu Merchant Products API możesz wstawiać i aktualizować produkty w źródle danych, pobierać produkty z konta oraz usuwać je z źródła danych.
Interfejs Merchant Products API zawiera te zasoby:
ProductInput
reprezentuje dane wejściowe Twoich produktów.Product
reprezentuje przetworzone produkty, które zostały utworzone z podanych przez Ciebie części.
ProductInput
może być podstawowy lub dodatkowy, w zależności od tego, czy jest przesłany do podstawowego źródła danych czy do dodatkowego źródła danych.
Każdy element Product
będzie zbudowany z jednego podstawowego elementu ProductInput
i dowolnej liczby dodatkowych elementów ProductInput
.
Interfejs Merchant Products API umożliwia tworzenie katalogów sklepów internetowych lub lokalnych. Są to produkty, które mogą się wyświetlać w wielu miejscach docelowych zakupów.
Zasób ProductInput
możesz użyć po utworzeniu konta Merchant Center, skonfigurowaniu pierwszego źródła danych i przesłaniu początkowego zestawu produktów za pomocą interfejsu API.
Chociaż sprzedawcy mogą przesyłać produkty za pomocą pliku o nazwie PrimaryProductDataSource, tworzenie i usuwanie produktów za pomocą interfejsu Merchant API ma kilka zalet. Zalety to m.in. szybszy czas reakcji i możliwość aktualizowania produktów w czasie rzeczywistym bez konieczności zarządzania dużymi plikami. Zanim zmiany produktów wprowadzone przez wywołania interfejsu API pojawią się w bazie danych Zakupów Google, może minąć do kilku godzin.
Wymagania wstępne
Jeśli nie masz źródła danych, utwórz je za pomocą interfejsu API źródeł danych sprzedawcy lub w Merchant Center.
Jeśli masz już źródło danych utworzone za pomocą interfejsu Merchant Center lub interfejsu API, możesz dodać produkty za pomocą interfejsu Merchant Products API. Jeśli do dodawania produktów używasz interfejsu Content API for Shopping, zapoznaj się z przewodnikiem po migracji, aby dowiedzieć się, jak zacząć korzystać z interfejsu Merchant Products API.
Użytkownik jest odpowiedzialny za przestrzeganie zasad dotyczących reklam produktowych i bezpłatnych informacji. Zastrzegamy sobie prawo do egzekwowania tych zasad i podejmowania odpowiednich działań, jeśli wykryjemy treści lub zachowania, które są z nimi niezgodne.
Zasoby
Zasób Product
umożliwia pobieranie informacji o produktach z bazy danych Zakupów Google.
Zasób ProductInput
reprezentuje dane wejściowe przesłane dla produktu. Zawiera też metody, które umożliwiają aktualizowanie lub usuwanie informacji o produktach pojedynczo lub wiele naraz w trybie zbiorczym. Zasób ProductInput
musi zawierać te pola:
channel
: kanał produktu.offerId
: unikalny identyfikator produktu.contentLanguage
: dwuliterowy kod języka ISO 639-1 produktu.feedLabel
: etykieta, która pozwala kategoryzować i identyfikować produkty. Maksymalna dozwolona liczba znaków to 20. Obsługiwane znaki toA-Z
,0-9
, łącznik i podkreślenie. Etykieta pliku danych nie może zawierać spacji. Więcej informacji znajdziesz w artykule Używanie etykiet pliku danych.
Przesyłanie danych produktu na konto
Aby przesłać dane produktu na swoje konto, użyj metody accounts.productInputs.insert
. Musisz przekazać unikalny identyfikator źródła danych podstawowego lub uzupełniającego.
Ten przykładowy żądanie pokazuje, jak za pomocą metody accounts.productInputs.insert
przesłać dane produktu na konto sprzedawcy. Żądanie określa cenę dostawy i region oraz atrybuty niestandardowe, takie jak data produkcji i rozmiar.
POST https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/productInputs:insert?dataSource={DATASOURCE}
{
"name": "{PRODUCT_TITLE}",
"versionNumber": {VERSION_NUMBER},
"contentLanguage": "{CONTENT_LANGUAGE}",
"feedLabel": "{FEED_LABEL}",
"offerId": "{OFFER_ID}",
"channel": "ONLINE",
"attributes": {
"availability": "in stock",
"imageLink": "{IMAGE_LINK}",
"link": "{PRODUCT_LINK}",
"brand": "{BRAND_NAME}",
"price": {
"currencyCode": "{CURRENCY_CODE}",
"amountMicros": {PRICE}
},
"color": "red",
"productWeight": {
"value": 320,
"unit": "g"
},
"adult": false,
"shipping": [
{
"country": "GB",
"price": {
"amountMicros": {SHIPPING_COST},
"currencyCode": "{CURRENCY_CODE_SHIPPING}"
},
"postalCode": "{SHIPPING_POSTALCODE}",
"service": "",
"region": "{SHIPPING_REGION}",
"maxHandlingTime": "{MAX_HANDLING_TIME}",
"minHandlingTime": "{MIN_HANDLING_TIME}",
"maxTransitTime": "{MAX_TRANSIT_TIME}",
"minTransitTime": "{MIN_TRANSIT_TIME}"
}
],
"gender": "Female"
},
"customAttributes": [
{
"name": "size",
"value": "Large"
},
{
"name": "Date of Manufacturing",
"value": "2024-05-05"
}
]
}
Zastąp następujące elementy:
- {ACCOUNT_ID}: unikalny identyfikator Twojego konta Merchant Center.
- {DATASOURCE}: unikalny identyfikator źródła danych. Powinien mieć format
accounts/
{ACCOUNT_ID}/dataSources/
{DATASOURCE_ID}. - {PRODUCT_TITLE}: nazwa produktu.
- {VERSION_NUMBER}: numer wersji produktu. Opcjonalnie.
- {CONTENT_LANGUAGE}: dwuliterowy kod języka ISO 639-1 produktu. Wymagane.
- {FEED_LABEL}: etykieta, która pozwala kategoryzować i identyfikować produkty. Maksymalna dozwolona liczba znaków to 20. Obsługiwane znaki to
A-Z
,0-9
, łącznik i podkreślenie. Etykieta pliku danych nie może zawierać spacji. - {OFFER_ID}: unikalny identyfikator produktu. Wymagane.
- {IMAGE_LINK}: link do obrazu produktu na Twojej stronie internetowej. Opcjonalnie.
- {PRODUCT_LINK}: link do produktu w Twojej witrynie. Opcjonalnie.
- {CURRENCY_CODE}: waluta, w której podano cenę, przedstawiona za pomocą skrótu składającego się z 3 liter zgodnie z normą ISO 4217. Opcjonalnie.
- {PRICE}: cena produktu wyrażona jako liczba w mikro. Opcjonalnie.
- {SHIPPING_COST}: stała cena dostawy reprezentowana jako liczba. Opcjonalnie.
- {SHIPPING_POSTALCODE}: zakres kodów pocztowych, w których obowiązuje koszt dostawy. Opcjonalnie.
- {MAX_HANDLING_TIME}: Maksymalny czas obsługi zamówienia w dniach roboczych od momentu jego otrzymania do wysłania. Opcjonalnie.
- {MIN_HANDLING_TIME}: minimalny czas obsługi zamówienia w dniach roboczych między jego otrzymaniem a wysłaniem. Wartość 0 oznacza, że zamówienie jest dostarczane tego samego dnia, w którym zostało złożone. Opcjonalnie.
- {MAX_TRANSIT_TIME}: Maksymalny czas przewozu w dniach roboczych od wysyłki do dostarczenia zamówienia. Opcjonalnie.
- {MIN_TRANSIT_TIME}: minimalny czas przewozu w dniach roboczych między wysyłką zamówienia a jego dostarczeniem. Wartość 0 oznacza, że zamówienie jest dostarczane tego samego dnia, w którym zostało wysłane. Opcjonalnie.
Gdy żądanie zostanie zrealizowane, zobaczysz tę odpowiedź:
{
"name": "{PRODUCT_NAME}",
"product": "{PRODUCT_ID}",
"channel": "ONLINE",
"offerId": "{OFFER_ID}",
"contentLanguage": "{CONTENT_LANGUAGE}",
"feedLabel": "{FEED_LABEL}",
"versionNumber": "{VERSION_NUMBER}",
"attributes": {
"link": "{PRODUCT_LINK}",
"imageLink": "{IMAGE_LINK}",
"adult": false,
"availability": "in stock",
"brand": "{BRAND_NAME}",
"color": "red",
"gender": "Female",
"price": {
"amountMicros": "{PRICE}",
"currencyCode": "{CURRENCY_CODE}"
},
"shipping": [
{
"price": {
"amountMicros": "{SHIPPING_COST}",
"currencyCode": "{CURRENCY_CODE}"
},
"country": "{SHIPPING_COUNTRY}",
"region": "{SHIPPING_REGION}",
"postalCode": "{SHIPPING_POSTALCODE}",
"minHandlingTime": "{MIN_HANDLING_TIME}",
"maxHandlingTime": "{MAX_HANDLING_TIME}",
"minTransitTime": "{MIN_TRANSIT_TIME}",
"maxTransitTime": "{MAX_TRANSIT_TIME}"
}
],
"productWeight": {
"value": 320,
"unit": "g"
}
},
"customAttributes": [
{
"name": "Size",
"value": "Large"
},
{
"name": "Date of Manufacturing",
"value": "2024-05-05"
}
]
}
Aby dodać produkt do konta Merchant Center, możesz użyć metody google.shopping.merchant.accounts.v1beta.InsertProductInputSample
, jak pokazano w tym przykładzie.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.products.v1beta.Attributes;
import com.google.shopping.merchant.products.v1beta.InsertProductInputRequest;
import com.google.shopping.merchant.products.v1beta.ProductInput;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceClient;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceSettings;
import com.google.shopping.merchant.products.v1beta.Shipping;
import com.google.shopping.type.Channel.ChannelEnum;
import com.google.shopping.type.Price;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to insert a product input */
public class InsertProductInputSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void insertProductInput(Config config, String dataSource) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
ProductInputsServiceSettings productInputsServiceSettings =
ProductInputsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent to identify where to insert the product.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (ProductInputsServiceClient productInputsServiceClient =
ProductInputsServiceClient.create(productInputsServiceSettings)) {
// Price to be used for shipping ($33.45).
Price price = Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode("USD").build();
Shipping shipping =
Shipping.newBuilder()
.setPrice(price)
.setCountry("GB")
.setService("1st class post")
.build();
Shipping shipping2 =
Shipping.newBuilder()
.setPrice(price)
.setCountry("FR")
.setService("1st class post")
.build();
Attributes attributes =
Attributes.newBuilder()
.setTitle("A Tale of Two Cities")
.setDescription("A classic novel about the French Revolution")
.setLink("https://exampleWebsite.com/tale-of-two-cities.html")
.setImageLink("https://exampleWebsite.com/tale-of-two-cities.jpg")
.setAvailability("in stock")
.setCondition("new")
.setGoogleProductCategory("Media > Books")
.addGtin("9780007350896")
.addShipping(shipping)
.addShipping(shipping2)
.build();
// The datasource can be either a primary or supplemental datasource.
InsertProductInputRequest request =
InsertProductInputRequest.newBuilder()
.setParent(parent)
// You can only insert products into datasource types of Input "API" and "FILE", and
// of Type "Primary" or "Supplemental."
// This field takes the `name` field of the datasource.
.setDataSource(dataSource)
// If this product is already owned by another datasource, when re-inserting, the
// new datasource will take ownership of the product.
.setProductInput(
ProductInput.newBuilder()
.setChannel(ChannelEnum.ONLINE)
.setContentLanguage("en")
.setFeedLabel("label")
.setOfferId("sku123")
.setAttributes(attributes)
.build())
.build();
System.out.println("Sending insert ProductInput request");
ProductInput response = productInputsServiceClient.insertProductInput(request);
System.out.println("Inserted ProductInput Name below");
// The last part of the product name will be the product ID assigned to a product by Google.
// Product ID has the format `channel~contentLanguage~feedLabel~offerId`
System.out.println(response.getName());
System.out.println("Inserted Product Name below");
System.out.println(response.getProduct());
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// Identifies the data source that will own the product input.
String dataSource = "accounts/" + config.getAccountId() + "/dataSources/{INSERT_DATASOURCE_ID}";
insertProductInput(config, dataSource);
}
}
Pobieranie przetworzonego produktu z konta
Aby odzyskać przetworzony produkt z konta, użyj metody accounts.products.get
. Po wstawieniu przetworzonego produktu może minąć kilka minut, zanim się pojawi.
GET https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/products/{PRODUCT_NAME}
Zastąp {PRODUCT_NAME} nazwą zasobu danych wejściowych usługi, który chcesz pobrać. Na przykład: online~en~US~sku123
.
Nazwę zasobu przetworzonego produktu możesz uzyskać z pola Product
w odpowiedzi na accounts.productInputs.insert
.
Aby pobrać pojedynczy produkt na danym koncie Merchant Center, możesz użyć metody google.shopping.merchant.accounts.v1beta.GetProductRequest
, jak pokazano w tym przykładzie.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.products.v1beta.GetProductRequest;
import com.google.shopping.merchant.products.v1beta.Product;
import com.google.shopping.merchant.products.v1beta.ProductsServiceClient;
import com.google.shopping.merchant.products.v1beta.ProductsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to get a single product for a given Merchant Center account */
public class GetProductSample {
public static void getProduct(Config config, String product) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
ProductsServiceSettings productsServiceSettings =
ProductsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Calls the API and catches and prints any network failures/errors.
try (ProductsServiceClient productsServiceClient =
ProductsServiceClient.create(productsServiceSettings)) {
// The name has the format: accounts/{account}/products/{productId}
GetProductRequest request = GetProductRequest.newBuilder().setName(product).build();
System.out.println("Sending get product request:");
Product response = productsServiceClient.getProduct(request);
System.out.println("Retrieved Product below");
System.out.println(response);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// The name of the `product`, returned after a `Product.insert` request. We recommend
// having stored this value in your database to use for all future requests.
String product = "accounts/{datasource}/products/{productId}";
getProduct(config, product);
}
}
Usuwanie danych produktu z konta
Aby usunąć dane produktu z konta, użyj metody accounts.productInputs.delete
. Aby usunąć produkt za pomocą interfejsu Merchant Products API, musisz przekazać unikalny identyfikator podstawowego lub uzupełniającego źródła danych, do którego należy produkt.
Z tego żądania dowiesz się, jak za pomocą metody accounts.productInputs.delete
usunąć dane wejściowe produktu:
DELETE https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/productInputs/{PRODUCT_NAME}?dataSource=accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}
Zastąp {PRODUCT_NAME} nazwą zasobu danych wejściowych produktu, który chcesz usunąć. Na przykład: online~en~US~sku123
.
Aby usunąć produkt z danego konta Merchant Center, możesz użyć metody
google.shopping.merchant.accounts.v1beta.DeleteProductInputRequest
, jak pokazano w tym przykładzie.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.products.v1beta.DeleteProductInputRequest;
import com.google.shopping.merchant.products.v1beta.ProductInputName;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceClient;
import com.google.shopping.merchant.products.v1beta.ProductInputsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to delete a product for a given Merchant Center account */
public class DeleteProductInputSample {
public static void deleteProductInput(Config config, String productId, String dataSource)
throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
ProductInputsServiceSettings productInputsServiceSettings =
ProductInputsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates product name to identify product.
String name =
ProductInputName.newBuilder()
.setAccount(config.getAccountId().toString())
.setProductinput(productId)
.build()
.toString();
// Calls the API and catches and prints any network failures/errors.
try (ProductInputsServiceClient productInputsServiceClient =
ProductInputsServiceClient.create(productInputsServiceSettings)) {
DeleteProductInputRequest request =
DeleteProductInputRequest.newBuilder().setName(name).setDataSource(dataSource).build();
System.out.println("Sending deleteProductInput request");
productInputsServiceClient.deleteProductInput(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. If you make a products.get or products.list request before a few"
+ " minutes have passed, the old product data may be returned.");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// An ID assigned to a product by Google. In the format
// channel~contentLanguage~feedLabel~offerId
String productId = "online~en~label~sku123";
// The name of the dataSource from which to delete the product. If it is a primary feed, this
// will delete the product completely. If it's a supplemental feed, it will only delete the
// product information from that feed, but the product will still be available from the primary
// feed.
String dataSource = "accounts/{account}/dataSources/{dataSource}";
deleteProductInput(config, productId, dataSource);
}
}
Wyświetlanie produktów na koncie
Aby wyświetlić przetworzone produkty na swoim koncie, użyj metody accounts.products.list
, jak pokazano w poniższym żądaniu.
GET https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/products
Aby wyświetlić produkt na danym koncie Merchant Center, możesz użyć metody google.shopping.merchant.accounts.v1beta.ListProductsRequest
, jak pokazano w tym przykładzie.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.products.v1beta.ListProductsRequest;
import com.google.shopping.merchant.products.v1beta.Product;
import com.google.shopping.merchant.products.v1beta.ProductsServiceClient;
import com.google.shopping.merchant.products.v1beta.ProductsServiceClient.ListProductsPagedResponse;
import com.google.shopping.merchant.products.v1beta.ProductsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the products for a given merchant center account */
public class ListProductsSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static void listProducts(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.
ProductsServiceSettings productsServiceSettings =
ProductsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent to identify the account from which to list all products.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (ProductsServiceClient productsServiceClient =
ProductsServiceClient.create(productsServiceSettings)) {
// The parent has the format: accounts/{account}
// Page size is set to the maximum value. If you are returned more
// responses than your page size, this code will automatically
// re-call the service with the `pageToken` until all responses
// are returned.
ListProductsRequest request =
ListProductsRequest.newBuilder().setParent(parent).setPageSize(250).build();
System.out.println("Sending list products request:");
ListProductsPagedResponse response = productsServiceClient.listProducts(request);
int count = 0;
// 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 (Product product : response.iterateAll()) {
System.out.println(product); // The product includes the `productStatus` field
// That shows approval and disapproval information.
count++;
}
System.out.print("The following count of products were returned: ");
System.out.println(count);
} catch (Exception e) {
System.out.println("An error has occured: ");
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
listProducts(config);
}
}