Merchant API Code Sample to Filter Disapproved Products
Java
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// THIS ONE GETS A CANCELED ERROR STRANGELY ENOUGH - DEBUG:
// com.google.api.gax.rpc.CancelledException: io.grpc.StatusRuntimeException: CANCELLED: Failed to
// read message.
package shopping.merchant.samples.products.v1beta;
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.ProductStatus.DestinationStatus;
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 java.util.ArrayList;
import java.util.List;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/**
* This class demonstrates how to get the list of all the disapproved products for a given merchant
* center account.
*/
public class FilterDisapprovedProductsSample {
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}
ListProductsRequest request = ListProductsRequest.newBuilder().setParent(parent).build();
System.out.println("Sending list products request:");
System.out.println("Will filter through response for disapproved products.");
ListProductsPagedResponse response = productsServiceClient.listProducts(request);
ArrayList<Product> disapprovedProducts = new ArrayList<Product>();
// Iterates over all rows in all pages.
// Automatically uses the `nextPageToken` if returned to fetch all pages of data.
// Creates a list of all products that are disapproved in at least one country
// for at least one destination.
for (Product product : response.iterateAll()) {
List<DestinationStatus> destinationStatuses =
product.getProductStatus().getDestinationStatusesList();
// Filter through all the destinations and capture if the product is disapproved in any
// country.
for (DestinationStatus destinationStatus : destinationStatuses) {
if (destinationStatus.getDisapprovedCountriesCount() > 0) {
disapprovedProducts.add(product);
break; // exit the inner loop, so we don't add the same product multiple times
// if it's disapproved for different destinations.
}
}
}
System.out.print("The following count of disapproved products were returned: ");
System.out.println(disapprovedProducts.size());
} 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);
}
}
PHP
<?php
/**
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once __DIR__ . '/../../../vendor/autoload.php';
require_once __DIR__ . '/../../Authentication/Authentication.php';
require_once __DIR__ . '/../../Authentication/Config.php';
use Google\ApiCore\ApiException;
use Google\ApiCore\PagedListResponse;
use Google\Shopping\Merchant\Products\V1beta\ListProductsRequest;
use Google\Shopping\Merchant\Products\V1beta\Product;
use Google\Shopping\Merchant\Products\V1beta\Client\ProductsServiceClient;
/**
* This class demonstrates how to filter through all the products returned via
* `Products.List` to find all the disapproved products for a given Merchant Center
* account.
*/
class FilterDisapprovedProducts
{
/**
* A helper function to create the parent string.
*
* @param array $accountId The account that owns the product.
*
* @return string The parent has the format: `accounts/{account_id}`
*/
private static function getParent($accountId)
{
return sprintf("accounts/%s", $accountId);
}
/**
* Filters to find all disapproved products in your Merchant Center account.
*
* @param array $config
* The configuration data used for authentication and getting the acccount
* ID.
*
* @return void
*/
public static function filterDisapprovedProductsSample($config): void
{
// Obtains OAuth token based on the user's configuration.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates options config containing credentials for the client to use.
$options = ['credentials' => $credentials];
// Creates a client.
$productsServiceClient = new ProductsServiceClient($options);
// Creates parent to identify the account from which to list all products.
$parent = self::getParent($config['accountId']);
// Creates the request.
$request = new ListProductsRequest(['parent' => $parent]);
// Calls the API and catches and prints any network failures/errors.
try {
// Page size is set to the default 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.
$parameters = ['pageSize' => 25000];
$disapprovedProducts = [];
echo "Sending list products request:\n";
echo ("Will filter through response for disapproved products.");
/**
* Call the listProducts service and get back a response object
* with all products.
*
* @var PagedListResponse $response
*/
$response = $productsServiceClient->listProducts($request, $parameters);
/**
* Filter through all the destinations and capture if the product
* is disapproved in any country.
*
* @var Product $product
*/
foreach ($response as $product) {
$destinationStatuses = $product
->getProductStatus()
->getDestinationStatuses();
foreach ($destinationStatuses as $destinationStatus) {
if (count($destinationStatus->getDisapprovedCountries()) > 0) {
$disapprovedProducts[] = $product;
// Exit the inner loop, so we don't add the same product
// multiple times if it's disapproved for different
// destinations.
break;
}
}
// The product includes the `productStatus` field that shows approval
// and disapproval information.
printf(
'Disapproved Product data: %s%s',
$product->serializeToJsonString(),
PHP_EOL
);
}
echo "The following count of disapproved products were returned: ";
echo count($disapprovedProducts) . PHP_EOL;
} catch (ApiException $e) {
printf('Call failed with message: %s%s', $ex->getMessage(), PHP_EOL);
}
}
/**
* Helper to execute the sample.
*
* @return void
*/
public function callSample(): void
{
$config = Config::generateConfig();
self::filterDisapprovedProductsSample($config);
}
}
// Run the script
$sample = new FilterDisapprovedProducts();
$sample->callSample();
Python
# -*- coding: utf-8 -*-
# Copyright 2024 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A module to list and filter disapproved Products."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_products_v1beta
_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"
def filter_disapproved_products():
"""Lists and filters the disapproved `Product` resources for a given account."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = merchant_products_v1beta.ProductsServiceClient(
credentials=credentials
)
# Creates the request.
request = merchant_products_v1beta.ListProductsRequest(parent=_PARENT)
# Makes the request and catches and prints any error messages.
try:
response = client.list_products(request=request)
disapproved_products = []
for product in response.products:
for destination in product.product_status.destination_statuses:
# If the product is disapproved in any country for any destination.
# Note that product.product_status also has an item_level_issues field
# which can be used to filter products with specific issues.
if destination.disapproved_countries:
disapproved_products.append(product)
break
print(f"You have {len(disapproved_products)} disapproved products.")
except RuntimeError as e:
print("List request failed")
print(e)
if __name__ == "__main__":
filter_disapproved_products()