Questa pagina spiega come caricare e gestire i prodotti in modo programmatico. Con l'API Merchant Products, puoi inserire o aggiornare un prodotto in un'origine dati, recuperare un prodotto dal tuo account ed eliminare un prodotto da un'origine dati.
L'API Merchant Products contiene due risorse.
productInputs
rappresenta le parti di input dei tuoi prodotti.products
rappresenta i prodotti elaborati creati a partire dalle parti di input.
productInputs
può essere principale e supplementare, a seconda che sia caricato in un'origine dati principale o in un'origine dati supplementare.
Ogni product
verrà creato da un singolo productInput
principale e da un qualsiasi numero di productInputs
supplementari.
Puoi utilizzare l'API Merchant Products per creare cataloghi di negozi online o locali, ovvero prodotti che possono essere visualizzati su più destinazioni di acquisto.
Puoi utilizzare la risorsa productInputs
dopo aver creato il tuo account Merchant Center, aver configurato la tua prima origine dati e aver caricato un primo insieme di prodotti tramite l'API.
Sebbene i commercianti abbiano la possibilità di caricare i prodotti utilizzando un file chiamato PrimaryProductDataSource, esistono diversi vantaggi nella creazione e nell'eliminazione dei prodotti tramite l'API Merchant. Questi vantaggi includono tempi di risposta più rapidi e la possibilità di aggiornare i prodotti in tempo reale, senza dover gestire file di grandi dimensioni. Potrebbero essere necessarie diverse ore prima che le modifiche ai prodotti apportate tramite le chiamate API vengano visualizzate nel database Shopping.
Prerequisiti
Se non hai un'origine dati, creane una utilizzando l'API Merchant Data Sources o Merchant Center.
Se hai già un'origine dati creata utilizzando l'interfaccia utente di Merchant Center o l'API, puoi utilizzare l'API Merchant Products per aggiungere i tuoi prodotti. Se utilizzi l'API Content for Shopping per aggiungere prodotti, consulta la guida alla migrazione per scoprire come iniziare a utilizzare l'API Merchant Products.
Sei responsabile della conformità alle norme relative agli annunci Shopping e alle schede senza costi. Google si riserva il diritto di applicare queste norme e di rispondere in modo appropriato se vengono rilevati contenuti o comportamenti che le violano.
Risorse
La risorsa products
ti consente di recuperare le informazioni sui prodotti dal database Shopping.
La risorsa
productInput
rappresenta i dati di input inviati per un prodotto. Fornisce inoltre metodi che consentono di aggiornare o eliminare le informazioni sui prodotti una alla volta o più alla volta in modalità batch. Una risorsa productInput
deve avere i seguenti campi:
channel
: il canale del prodotto.offerId
: l'identificatore univoco del prodotto.contentLanguage
: il codice lingua di due lettere ISO 639-1 per il prodotto.feedLabel
: l'etichetta che ti consente di classificare e identificare i tuoi prodotti. I caratteri massimi consentiti sono 20 e quelli supportati sonoA-Z
,0-9
, trattino e trattino basso. L'etichetta del feed non deve includere spazi. Per ulteriori informazioni, consulta Utilizzare le etichette del feed.
Caricare un input del prodotto nel tuo account
Per caricare un input del prodotto nel tuo account, utilizza il metodo
accounts.productInputs.insert
. Devi passare l'identificatore univoco dell'origine dati principale o supplementare.
La seguente richiesta di esempio mostra come utilizzare il metodo accounts.productInputs.insert
per caricare un input prodotto nel tuo account commerciante. La richiesta imposta il prezzo e la regione di spedizione, nonché attributi personalizzati come la data di produzione e le dimensioni.
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"
}
]
}
Sostituisci quanto segue:
- {ACCOUNT_ID}: l'identificatore univoco del tuo account Merchant Center.
- {DATASOURCE}: l'identificatore univoco della fonte di dati. Deve essere nel formato
accounts/
{ACCOUNT_ID}/dataSources/
{DATASOURCE_ID}. - {PRODUCT_TITLE}: il nome del prodotto.
- {VERSION_NUMBER}: il numero di versione del prodotto. (Facoltativo)
- {CONTENT_LANGUAGE}: il codice lingua ISO 639-1 di due lettere del prodotto. Obbligatorio.
- {FEED_LABEL}: l'etichetta che consente di classificare
e identificare i prodotti. I caratteri massimi consentiti sono 20 e quelli supportati sono
A-Z
,0-9
, trattino e trattino basso. L'etichetta del feed non deve includere spazi. - {OFFER_ID}: l'identificatore univoco del prodotto. Obbligatorio.
- {IMAGE_LINK}: il link all'immagine del prodotto sul tuo sito web. (Facoltativo)
- {PRODUCT_LINK}: il link al prodotto sul tuo sito web. (Facoltativo)
- {CURRENCY_CODE}: la valuta del prezzo utilizzando acronimo di tre lettere in base allo standard ISO 4217. (Facoltativo)
- {PRICE}: il prezzo del prodotto rappresentato come numero in micro. (Facoltativo)
- {SHIPPING_COST}: il prezzo di spedizione fisso rappresentato come numero. (Facoltativo)
- {SHIPPING_POSTALCODE}: l'intervallo di codici postali a cui si applica la tariffa di spedizione. (Facoltativo)
- {MAX_HANDLING_TIME}: il tempo di elaborazione massimo in giorni lavorativi tra la ricezione e la spedizione dell'ordine. (Facoltativo)
- {MIN_HANDLING_TIME}: il tempo di elaborazione minimo in giorni lavorativi tra la ricezione e la spedizione dell'ordine. Il valore 0 indica che l'ordine viene consegnato lo stesso giorno in cui viene ricevuto. (Facoltativo)
- {MAX_TRANSIT_TIME}: il tempo di transito massimo in giorni lavorativi tra la data di spedizione e la data di consegna dell'ordine. (Facoltativo)
- {MIN_TRANSIT_TIME}: il tempo di transito minimo in giorni lavorativi tra la data di spedizione e la data di consegna dell'ordine. Il valore 0 indica che l'ordine viene consegnato lo stesso giorno in cui viene spedito. (Facoltativo)
Quando la richiesta viene eseguita correttamente, viene visualizzata la seguente risposta:
{
"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"
}
]
}
Per aggiungere un prodotto al tuo account Merchant Center, puoi utilizzare il metodo
google.shopping.merchant.accounts.v1beta.InsertProductInputSample
, come mostrato nell'esempio seguente.
Java
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")
.setGtin(0, "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);
}
}
Recuperare un prodotto elaborato dal tuo account
Per recuperare un prodotto elaborato dal tuo account, utilizza il metodo
accounts.products.get
. Potrebbero essere necessari diversi minuti prima che il prodotto elaborato venga visualizzato dopo l'inserimento.
GET https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/products/{PRODUCT_NAME}
Sostituisci {PRODUCT_NAME} con il nome della risorsa di input del prodotto che vuoi eliminare. Ad esempio, online~en~US~sku123
.
Puoi ottenere il nome della risorsa del prodotto elaborato dal campo product
nella
risposta di accounts.productInputs.insert
.
Per recuperare un singolo prodotto per un determinato account Merchant Center, puoi utilizzare il metodo
google.shopping.merchant.accounts.v1beta.GetProductRequest
, come mostrato nell'esempio seguente.
Java
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);
}
}
Eliminare un input del prodotto dal tuo account
Per eliminare un input del prodotto dal tuo account, utilizza il metodo
accounts.productInputs.delete
. Per eliminare un prodotto utilizzando l'API Merchant Products, devi passare l'identificatore univoco dell'origine dati principale o supplementare a cui appartiene il prodotto.
La richiesta seguente mostra come utilizzare il metodo accounts.productInputs.delete
per eliminare un input del prodotto:
DELETE https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/productInputs/{PRODUCT_NAME}?dataSource=accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}
Sostituisci {PRODUCT_NAME} con il nome della risorsa di input del prodotto che vuoi eliminare. Ad esempio, online~en~US~sku123
.
Per eliminare un prodotto per un determinato account Merchant Center, puoi utilizzare il metodo
google.shopping.merchant.accounts.v1beta.DeleteProductInputRequest
, come mostrato nell'esempio seguente.
Java
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);
}
}
Elenca i prodotti del tuo account
Per elencare i prodotti elaborati nel tuo account, utilizza il metodo accounts.products.list
, come mostrato nella richiesta seguente.
GET https://merchantapi.googleapis.com/products/v1beta/accounts/{ACCOUNT_ID}/products
Per mostrare un prodotto per un determinato account Merchant Center, puoi utilizzare il metodo
google.shopping.merchant.accounts.v1beta.ListProductsRequest
, come mostrato nell'esempio seguente.
Java
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}
ListProductsRequest request = ListProductsRequest.newBuilder().setParent(parent).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);
}
}