获取商品

用于获取商品的 Merchant API 代码示例。

AppsScript

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

/**
 * Get a specific product for a given Merchant Center account.
 */
function getProduct() {
  // IMPORTANT:
  // Enable the Merchant API Products sub-API Advanced Service and call it
  // "MerchantApiProducts"

  // Replace this with your Merchant Center ID.
  const accountId = '<MERCHANT_CENTER_ID>';

  // The ID of the product to retrieve.
  // This ID is assigned by Google and typically follows the format:
  // channel~contentLanguage~feedLabel~offerId
  // Replace with an actual product ID from your Merchant Center account.
  const productId = '<PRODUCT_ID>';

  // Construct the parent name
  const parent = 'accounts/' + accountId;

  // Construct the product resource name
  const name = parent + "/products/" + productId;

  try {
    console.log('Sending get Product request');
    // Call the Products.get API method.
    product = MerchantApiProducts.Accounts.Products.get(name);
    console.log(product);
  } catch (e) {
    console.log('ERROR!');
    console.log(e);
  }
}

Java

// Copyright 2025 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.v1;


import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.common.io.BaseEncoding;
import com.google.shopping.merchant.products.v1.GetProductRequest;
import com.google.shopping.merchant.products.v1.Product;
import com.google.shopping.merchant.products.v1.ProductsServiceClient;
import com.google.shopping.merchant.products.v1.ProductsServiceSettings;
import java.nio.charset.StandardCharsets;
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 {

  // Base64Url encoder/decoder without padding
  private static final BaseEncoding BASE64URL_NOPADDING = BaseEncoding.base64Url().omitPadding();

  // Encodes a string to base64url without padding
  public static String encodeProductId(String productId) {
    return BASE64URL_NOPADDING.encode(productId.getBytes(StandardCharsets.UTF_8));
  }

  public static void getProduct(Config config, String accountId, String productId)
      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}
      String name = "accounts/" + accountId + "/products/" + productId;

      // The name has the format: accounts/{account}/products/{productId}
      GetProductRequest request = GetProductRequest.newBuilder().setName(name).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();
    String accountId = config.getAccountId().toString();

    // 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 productId = "en~US~sku123"; // Replace with your actual product ID

    // Uncomment the following line if the product name contains special characters (such as forward
    // slashes) and needs base64url encoding.
    // productId = encodeProductId(productId);

    getProduct(config, accountId, productId);
  }
}

Node.js

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

'use strict';
const fs = require('fs');
const authUtils = require('../../authentication/authenticate.js');
const {ProductsServiceClient} = require('@google-shopping/products').v1;

/**
 * Retrieves a single product for a given Merchant Center account.
 * @param {!object} config - The configuration object.
 * @param {string} productName - The name of the product to retrieve.
 */
async function getProduct(config, productName) {
  // Get credentials.
  const authClient = await authUtils.getOrGenerateUserCredentials();

  // Create options object for the client.
  const options = {authClient: authClient};

  // Create the ProductsServiceClient.
  const productsClient = new ProductsServiceClient(options);

  // Construct the request object.
  const request = {
    name: productName,
  };

  try {
    console.log('Sending get product request:');
    // Call the API to get the product.
    const response = await productsClient.getProduct(request);

    console.log('Retrieved Product below');
    console.log(response);
  } catch (error) {
    console.error(error.message);
  }
}

/**
 * Main function to call the getProduct sample.
 */
async function main() {
  const config = authUtils.getConfig();
  // Read merchant_id from merchant-info.json.
  const merchantInfo =
      JSON.parse(fs.readFileSync(config.merchantInfoFile, 'utf8'));
  const merchantId = merchantInfo.merchantId;

  // The name of the `product`. Replace {product} with the actual ID.
  // Format: accounts/{account}/products/{product}
  // {product} is usually in the format:
  // contentLanguage~feedLabel~offerId
  const productName = `accounts/${merchantId}/products/{productId}`;

  await getProduct(config, productName);
}

main();

PHP

<?php
/**
 * Copyright 2025 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\Shopping\Merchant\Products\V1\Client\ProductsServiceClient;
use Google\Shopping\Merchant\Products\V1\GetProductRequest;

/**
 * This class demonstrates how to get a single product for a given Merchant
 * Center account.
 */
class GetProductSample
{
    /**
     * A helper function to create the product name string.
     *
     * @param string $accountId
     *      The account that owns the product.
     * @param string $productId
     *      The ID of the product.
     *
     * @return string The name has the format: `accounts/{account}/products/{product}`
     */
    private static function getName(string $accountId, string $productId): string
    {
        return sprintf("accounts/%s/products/%s", $accountId, $productId);
    }

    /**
     * Encodes a string to base64url without padding. This is needed if the
     * product ID contains special characters (such as forward slashes) and
     * needs base64url encoding.
     *
     * @param string $productId
     *      The ID of the product.
     *
     * @return string The encoded product ID.
     */
    public static function encodeProductId(string $productId): string
    {
        return rtrim(strtr(base64_encode($productId), '+/', '-_'), '=');
    }

    /**
     * Retrieves a product from your Merchant Center account.
     *
     * @param array $config
     *      The configuration data used for authentication and getting the
     *      account ID.
     * @param string $productId
     *      The ID of the product, in the form of
     *      `contentLanguage:feedLabel:offerId`.
     *
     * @return void
     */
    public static function getProduct(array $config, string $productId): void
    {
        // Gets the OAuth credentials to make the request.
        $credentials = Authentication::useServiceAccountOrTokenFile();

        // Creates options config containing credentials for the client to use.
        $options = ['credentials' => $credentials];

        // Creates a client.
        $productsServiceClient = new ProductsServiceClient($options);

        // The name has the format: accounts/{account}/products/{productId}
        $name = self::getName($config['accountId'], $productId);

        // Creates the request.
        $request = new GetProductRequest([
            'name' => $name
        ]);

        // Calls the API and catches and prints any network failures/errors.
        try {
            print "Sending get product request:\n";
            $response = $productsServiceClient->getProduct($request);
            print "Retrieved Product below\n";
            // Pretty-prints the JSON representation of the response.
            print $response->serializeToJsonString(true) . "\n";
        } catch (ApiException $e) {
            printf("Call failed with message: %s\n", $e->getMessage());
        }
    }

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

        // 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.
        $productId = 'en~US~sku123'; // Replace with your actual product ID

        // Uncomment the following line if the product name contains special
        // characters (such as forward slashes) and needs base64url encoding.
        // $productId = self::encodeProductId($productId);

        self::getProduct($config, $productId);
    }
}

// Runs the sample.
$sample = new GetProductSample();
$sample->callSample();

Python

# -*- coding: utf-8 -*-
# Copyright 2025 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 get a single product for a given Merchant Center account."""

import base64

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_products_v1 import GetProductRequest
from google.shopping.merchant_products_v1 import ProductsServiceClient


# This is needed for base64url encoding if product IDs contain special
# characters such as forward slashes.
def encode_product_id(product_id_to_encode: str) -> str:
  """Base64url encodes a string without padding.

  Args:
    product_id_to_encode: The product ID string to encode.

  Returns:
    The encoded product ID string.
  """
  encoded_bytes = base64.urlsafe_b64encode(product_id_to_encode.encode("utf-8"))
  return encoded_bytes.rstrip(b"=").decode("utf-8")


def get_product(account_id_arg: str, product_id_arg: str) -> None:
  """Retrieves a single product from a Merchant Center account.

  Args:
    account_id_arg: The ID of the Merchant Center account.
    product_id_arg: The ID of the product to retrieve.
  """
  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = ProductsServiceClient(credentials=credentials)

  # The name has the format: accounts/{account}/products/{product}
  name = f"accounts/{account_id_arg}/products/{product_id_arg}"

  # Creates the request.
  request = GetProductRequest(name=name)

  print("Sending get product request:")

  # Makes the request and catches and prints any error messages.
  try:
    response = client.get_product(request=request)
    print("Retrieved Product below")
    print(response)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  # Retrieves the configured account ID from the config file.
  account_id = configuration.Configuration().read_merchant_info()

  # The ID of the product, which is the final component of the product's
  # resource name. The product ID is the same as the offer ID.
  # For example, `en~US~sku123`.
  product_id = "en~US~sku123"  # Replace with your actual product ID.

  # Uncomment the following line if the product ID contains special characters
  # (such as forward slashes) and needs base64url encoding.
  # product_id = encode_product_id(product_id)

  get_product(account_id, product_id)