Enumera productos

Ejemplo de código de la API de Merchant para mostrar productos

// 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.

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.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}
      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);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    listProducts(config);
  }
}
<?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 list all products in your Merchant Center account.
 */
class ListProducts
{

    /**
     * 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);
    }

    /**
     * Lists all products in your Merchant Center account.
     *
     * @param array $config
     *      The configuration data used for authentication and getting the acccount
     *      ID.
     */
    public static function listProductsSample($config)
    {
        // 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];

            echo "Sending list products request:\n";
            /**
             * Call the listProducts service and get back a response object
             * with all products.
             *
             * @var PagedListResponse $response
             */
            $response = $productsServiceClient->listProducts($request, $parameters);

            /**
             * Loop through every product and print out its data.
             *
             * @var Product $product
             */
            foreach ($response as $product) {
                // The product includes the `productStatus` field that shows approval
                // and disapproval information.
                printf(
                    'Product data: %s%s',
                    $product->serializeToJsonString(), PHP_EOL
                );
            }
        } catch (ApiException $e) {
            printf('Call failed with message: %s%s', $e->getMessage(), PHP_EOL);
        }
    }

    /**
     * Helper to execute the sample.
     *
     * @return void
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        self::listProductsSample($config);
    }
}


// Run the script
$sample = new ListProducts();
$sample->callSample();
# -*- 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 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 list_products():
  """Lists the `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)
    print(f"List request successful: {response}")
  except RuntimeError as e:
    print("List request failed")
    print(e)


if __name__ == "__main__":
  list_products()