用于获取商品的 Merchant API 代码示例
// 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.GetProductRequest;
import com.google.shopping.merchant.products.v1beta.Product;
import com.google.shopping.merchant.products.v1beta.ProductsServiceClient;
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 get a single product for a given Merchant Center account */
public class GetProductSample {
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);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// 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 product = "accounts/{datasource}/products/{productId}";
getProduct(config, product);
}
}
<?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\Shopping\Merchant\Products\V1beta\GetProductRequest;
use Google\Shopping\Merchant\Products\V1beta\Product;
use Google\Shopping\Merchant\Products\V1beta\Client\ProductsServiceClient;
/**
* This class demonstrates how to get a single product for a given Merchant Center
* account.
*/
class GetProduct
{
// ENSURE you fill in the product ID for the sample to work.
private const PRODUCT = 'INSERT_PRODUCT_ID_HERE';
/**
* Gets a product from your Merchant Center account.
*
* @param array $config
* The configuration data used for authentication and getting the acccount
* ID.
* @param string $product
* The product ID to get.
* Format: `accounts/{account}/products/{productId}`.
*
* @return void
*/
public static function getProductSample($config, $product) : 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);
try {
// Creates the request.
$request = new GetProductRequest(
[
'name' => $product
]
);
// Sends the request.
echo "Sending get Product request\n";
$response = $productsServiceClient->getProduct($request);
// Outputs the response.
echo "Retrieved Product below\n";
print_r($response);
} catch (Exception $e) {
echo $e->getMessage();
}
}
/**
* Helper to execute the sample.
*
* @return void
*/
public function callSample(): void
{
$config = Config::generateConfig();
// Identifies the product to retrieve.
// The name has the format: accounts/{account}/products/{productId}.
$product = ProductsServiceClient::productName(
$config['accountId'],
self::PRODUCT
);
self::getProductSample($config, $product);
}
}
$sample = new GetProduct();
$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 get a Product."""
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()
# ENSURE you fill in the product ID for the sample to
# work.
# In the format of `channel~contentLanguage~feedLabel~offerId`
_PRODUCT = "[INSERT_PRODUCT_HERE]"
_NAME = f"accounts/{_ACCOUNT}/products/{_PRODUCT}"
def get_product():
"""Gets the specified `Product` resource."""
# 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.GetProductRequest(name=_NAME)
# Makes the request and catches and prints any error messages.
try:
response = client.get_product(request=request)
print(f"Get successful: {response}")
except RuntimeError as e:
print("Get failed")
print(e)
if __name__ == "__main__":
get_product()