Отзывы о товарах играют важную роль в процессе совершения покупок для покупателей. Эти рейтинги и отзывы помогают покупателям в изучении товаров и принятии решений о покупке. Положительные отзывы о товарах могут привлечь больше потенциальных клиентов на страницы продавцов. Источниками отзывов являются продавцы, агрегаторы отзывов, сайты с отзывами и пользователи Google.
На этой странице объясняется, как управлять отзывами о товарах с помощью API Merchant.
Предпосылки
Google требует от вас предоставления конкретной информации. Необходимо следующее:
- Активный канал обзоров товаров в Google Merchant Center.
- Ваша учётная запись должна быть зарегистрирована в программе рейтингов продуктов. Если вы не уверены, зарегистрированы ли вы уже, проверьте Merchant Center. Если вы ещё не зарегистрированы, узнайте больше о регистрации в программе рейтингов продуктов .
- Чтобы просмотреть продукты с помощью Merchant API, отправьте запрос, используя эту форму .
Создать источник данных
Используйте API datasource.create
для создания фида отзывов о продукте. Если существующий фид отзывов о продукте доступен, используйте accounts.dataSources.get
для получения файла accounts.dataSources.name
. Форма запроса выглядит следующим образом:
POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/{account}/dataSources/{datasource}
Пример
В примере показан типичный запрос и ответ.
Запрос
POST https://merchantapi.googleapis.com/datasources/v1beta/accounts/123/dataSources {"displayName": "test api feed", "productReviewDataSource":{} }
Ответ
{
"name": "accounts/123/dataSources/1000000573361824",
"dataSourceId": "1000000573361824",
"displayName": "test api feed",
"productReviewDataSource": {},
"input": "API"
}
Дополнительную информацию см. в статье Создание источника данных для обзоров продуктов .
Создать обзор продукта
Метод accounts.productreviews.insert
принимает в качестве входных accounts.productreviews.insert
ресурс productreview
и имя источника данных. В случае успешного выполнения он возвращает новый или обновлённый productreview
. Для создания обзора продукта необходимо иметь datasource.name
.
Форма запроса:
POST https://merchantapi.googleapis.com/reviews/v1alpha/{parent=accounts/{ACCOUNT_ID}/}productReviews:insert
Следующий пример запроса иллюстрирует, как можно создать обзор продукта.
POST https://merchantapi.googleapis.com/reviews/v1alpha/accounts/{ACCOUNT_ID}/productReviews:insert?dataSource=accounts/{ACCOUNT_ID}/dataSources/{DATASOURCE_ID}
productReviewId = 'my_product_review'
productReviewAttributes {
aggregatorName = 'aggregator_name'
subclientName = 'subclient_name'
publisherName = 'publisher_name'
publisherFavicon = 'https://www.google.com/favicon.ico'
reviewerId = 'reviewer_id'
reviewerIsAnonymous = false
reviewerUsername = 'reviewer_username'
reviewLanguage = 'en'
reviewCountry = 'US'
reviewTime = '2024-04-01T00:00:00Z'
title = 'Incredible product'
content = 'This is an incredible product.'
pros = ['pro1', 'pro2']
cons = ['con1', 'con2']
reviewLink = {
type = 'SINGLETON'
link = 'https://www.google.com'
}
reviewerImageLink = 'https://www.google.com/reviewer.png'
minRating = 1
maxRating = 10
rating = 8.5
productName = 'product_name'
productLink = 'https://www.google.com/product'
asins = ['asin1', 'asin2']
gtins = ['gtin1', 'gtin2']
mpns = ['mpn1', 'mpn2']
skus = ['sku1', 'sku2']
brands = ['brand1', 'brand2']
isSpam = false
collectionMethod = 'POST_FULFILLMENT'
transactionId = 'transaction_id'
}
После создания обзора продукта его распространение может занять несколько минут.
Вот пример, который можно использовать для асинхронной вставки нескольких обзоров продуктов:
Ява
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.reviews.v1beta.ListProductReviewsRequest;
import com.google.shopping.merchant.reviews.v1beta.ProductReview;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient.ListProductReviewsPagedResponse;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the product reviews in a given account. */
public class ListProductReviewsSample {
public static void listProductReviews(String accountId) throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
ProductReviewsServiceSettings productReviewsServiceSettings =
ProductReviewsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
try (ProductReviewsServiceClient productReviewsServiceClient =
ProductReviewsServiceClient.create(productReviewsServiceSettings)) {
ListProductReviewsRequest request =
ListProductReviewsRequest.newBuilder()
.setParent(String.format("accounts/%s", accountId))
.build();
System.out.println("Sending list product reviews request:");
ListProductReviewsPagedResponse response =
productReviewsServiceClient.listProductReviews(request);
int count = 0;
// Iterates over all rows in all pages and prints all product reviews.
for (ProductReview element : response.iterateAll()) {
System.out.println(element);
count++;
}
System.out.print("The following count of elements were returned: ");
System.out.println(count);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
listProductReviews(config.getAccountId().toString());
}
}
Получить обзор продукта
Чтобы просмотреть обзор продукта, используйте accounts.productreviews.get
. Он доступен только для чтения. В поле «Имя» необходимо указать идентификатор вашего accountId
и идентификатор обзора продукта. Метод GET
возвращает соответствующий ресурс обзора продукта.
GET https://merchantapi.googleapis.com/reviews/v1/{name=accounts/{ACCOUNT_ID}/productReviews/*}
Вот пример, который вы можете использовать для получения обзора продукта:
Ява
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.reviews.v1beta.GetProductReviewRequest;
import com.google.shopping.merchant.reviews.v1beta.ProductReview;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to get a product review. */
public class GetProductReviewSample {
public static void getProductReview(String accountId, String productReviewId) throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
ProductReviewsServiceSettings productReviewsServiceSettings =
ProductReviewsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
try (ProductReviewsServiceClient productReviewsServiceClient =
ProductReviewsServiceClient.create(productReviewsServiceSettings)) {
GetProductReviewRequest request =
GetProductReviewRequest.newBuilder()
.setName(String.format("accounts/%s/productReviews/%s", accountId, productReviewId))
.build();
System.out.println("Sending get product review request:");
ProductReview response = productReviewsServiceClient.getProductReview(request);
System.out.println("Product review retrieved successfully:");
System.out.println(response.getName());
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
String productReviewId = "YOUR_PRODUCT_REVIEW_ID";
getProductReview(config.getAccountId().toString(), productReviewId);
}
}
Список обзоров продуктов
Для просмотра всех созданных обзоров продуктов можно использовать метод productreviews.list
.
GET https://merchantapi.googleapis.com/reviews/v1/{parent=accounts/{ACCOUNT_ID}}/productReviews
Вот пример, который вы можете использовать для составления списка всех отзывов о продукте:
Ява
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.reviews.v1beta.ListProductReviewsRequest;
import com.google.shopping.merchant.reviews.v1beta.ProductReview;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient.ListProductReviewsPagedResponse;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the product reviews in a given account. */
public class ListProductReviewsSample {
public static void listProductReviews(String accountId) throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
ProductReviewsServiceSettings productReviewsServiceSettings =
ProductReviewsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
try (ProductReviewsServiceClient productReviewsServiceClient =
ProductReviewsServiceClient.create(productReviewsServiceSettings)) {
ListProductReviewsRequest request =
ListProductReviewsRequest.newBuilder()
.setParent(String.format("accounts/%s", accountId))
.build();
System.out.println("Sending list product reviews request:");
ListProductReviewsPagedResponse response =
productReviewsServiceClient.listProductReviews(request);
int count = 0;
// Iterates over all rows in all pages and prints all product reviews.
for (ProductReview element : response.iterateAll()) {
System.out.println(element);
count++;
}
System.out.print("The following count of elements were returned: ");
System.out.println(count);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
listProductReviews(config.getAccountId().toString());
}
}
Удалить отзывы о продукте
Чтобы удалить отзыв о товаре, используйте accounts.productreviews.delete
. Как и метод GET
, этот метод требует поле «Имя» отзыва о товаре, возвращаемого при его создании.
DELETE https://merchantapi.googleapis.com/reviews/v1/{name=accounts/{ACCOUNT_ID}/productReviews/*}
Вот пример, который вы можете использовать для удаления отзыва о продукте:
Ява
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.reviews.v1beta.DeleteProductReviewRequest;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceClient;
import com.google.shopping.merchant.reviews.v1beta.ProductReviewsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to delete a product review. */
public class DeleteProductReviewSample {
public static void deleteProductReview(String accountId, String productReviewId)
throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
ProductReviewsServiceSettings productReviewsServiceSettings =
ProductReviewsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
try (ProductReviewsServiceClient productReviewsServiceClient =
ProductReviewsServiceClient.create(productReviewsServiceSettings)) {
DeleteProductReviewRequest request =
DeleteProductReviewRequest.newBuilder()
.setName(String.format("accounts/%s/productReviews/%s", accountId, productReviewId))
.build();
System.out.println("Sending delete product review request:");
productReviewsServiceClient.deleteProductReview(request);
System.out.println("Product review deleted successfully");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
String productReviewId = "YOUR_PRODUCT_REVIEW_ID";
deleteProductReview(config.getAccountId().toString(), productReviewId);
}
}
Статус обзора продукта
Ресурс обзора продукта содержит статус, аналогичный другим API, который является неотъемлемой частью ресурса и следует той же структуре проблем и назначений.