ใช้ตัวอย่างนี้เพื่อเพิ่มสินค้าคงคลังในร้านลงในผลิตภัณฑ์
คุณยังใช้ตัวอย่างนี้เพื่ออัปเดต LocalInventory
ที่มีอยู่ได้ด้วย การโทรนี้
แทนที่ทรัพยากร LocalInventory
ทั้งหมด ดังนั้นโปรดตรวจสอบว่าได้รวม
ด้วย
Java
// Copyright 2023 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.inventories.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.inventories.v1beta.InsertLocalInventoryRequest;
import com.google.shopping.merchant.inventories.v1beta.LocalInventory;
import com.google.shopping.merchant.inventories.v1beta.LocalInventoryServiceClient;
import com.google.shopping.merchant.inventories.v1beta.LocalInventoryServiceSettings;
import com.google.shopping.type.Price;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to insert a Local inventory for a given product */
public class InsertLocalInventorySample {
private static String getParent(String merchantId, String productId) {
return String.format("accounts/%s/products/%s", merchantId, productId);
}
public static void insertLocalInventory(Config config, String productId, String storeCode)
throws Exception {
GoogleCredentials credential = new Authenticator().authenticate();
LocalInventoryServiceSettings localInventoryServiceSettings =
LocalInventoryServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
String parent = getParent(config.getMerchantId().toString(), productId);
try (LocalInventoryServiceClient localInventoryServiceClient =
LocalInventoryServiceClient.create(localInventoryServiceSettings)) {
Price price = Price.newBuilder().setAmountMicros(33_450_000).setCurrencyCode("USD").build();
InsertLocalInventoryRequest request =
InsertLocalInventoryRequest.newBuilder()
.setParent(parent)
.setLocalInventory(
LocalInventory.newBuilder()
.setAvailability("out of stock")
.setStoreCode(storeCode)
.setPrice(price)
.build())
.build();
System.out.println("Sending insert LocalInventory request");
LocalInventory response = localInventoryServiceClient.insertLocalInventory(request);
System.out.println("Inserted LocalInventory Name below");
System.out.println(response.getName());
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
// An ID assigned to a product by Google. In the format
// channel:contentLanguage:feedLabel:offerId
String productId = "local:en:label:1111111111";
// The code uniquely identifying each store.
String storeCode = "Example1";
insertLocalInventory(config, productId, storeCode);
}
}
cURL
curl --location 'https://merchantapi.googleapis.com/inventories/v1beta/accounts/987654321/products/local~en~US~12345/localInventories:insert' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <API_TOKEN>' \
--data '{ "storeCode": "123456", "price": { "amountMicros": "33450000", "currencyCode": "USD"
}, "availability": "out of stock" }'
PHP
<?php
/**
* Copyright 2023 Google Inc. All Rights Reserved.
*
* 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.
*/
require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../Authentication/Authentication.php';
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Inventories\V1beta\LocalInventory;
use Google\Shopping\Merchant\Inventories\V1beta\LocalInventoryServiceClient;
use Google\Shopping\Type\Price;
/**
* Class to insert a `LocalInventory` to a given product in your
* merchant account.
*
* Replaces the full `LocalInventory` resource if an entry with the same
* [`storeCode`]
* [google.shopping.merchant.inventories.v1beta.LocalInventory.storeCode]
* already exists for the product.
*
* It might take up to 30 minutes for the new or updated `LocalInventory`
* resource to appear in products.
*/
class InsertLocalInventory
{
// ENSURE you fill in the merchant account and product ID for the sample to
// work.
private const PARENT = 'accounts/[INSERT_ACCOUNT_HERE]/products/[INSERT_PRODUCT_HERE]';
// ENSURE you fill in store code for the sample to work.
private const LOCAL_INVENTORY_STORE_CODE = 'INSERT_STORE_CODE_HERE';
/**
* Inserts a local inventory underneath the parent product.
*
* @param string $parent The account and product where this inventory will be inserted.
* Format: `accounts/{account}/products/{product}`
* @param string $localInventoryRegion
* ID of the region for this
* `LocalInventory` resource. See the [Local availability and
* pricing](https://support.google.com/merchants/answer/9698880) for more details.
*/
public function insertLocalInventorySample(
string $parent,
string $localInventoryStoreCode
): 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.
$localInventoryServiceClient = new LocalInventoryServiceClient($options);
// Creates a price object.
$price = new Price(
[
'currency_code' => "USD",
'amount_micros' => 33450000,
]
);
// Creates a new local inventory object.
$localInventory = (new LocalInventory())
->setStoreCode($localInventoryStoreCode)
->setAvailability("in stock")
->setPrice($price);
// Calls the API and catches and prints any network failures/errors.
try {
/** @var LocalInventory $response */
$response = $localInventoryServiceClient->insertLocalInventory(
$parent,
$localInventory
);
printf('Response data: %s%s', $response->serializeToJsonString(), PHP_EOL);
} catch (ApiException $ex) {
printf('Call failed with message: %s%s', $ex->getMessage(), PHP_EOL);
}
}
/**
* Helper to execute the sample.
*/
public function callSample(): void
{
// Makes the call to insert the local inventory to the parent product
// for the given region.
$this->insertLocalInventorySample($this::PARENT, $this::LOCAL_INVENTORY_STORE_CODE);
}
}
$sample = new InsertLocalInventory();
$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 insert a Local Inventory."""
from examples.authentication import generate_user_credentials
from google.shopping import merchant_inventories_v1beta
# ENSURE you fill in the merchant account and product ID for the sample to
# work.
_ACCOUNT = "INSERT_ACCOUNT_HERE"
_PRODUCT = "INSERT_PRODUCT_HERE"
_PARENT = f"accounts/{_ACCOUNT}/products/{_PRODUCT}"
# ENSURE you fill in store code for the sample to work.
_STORE_CODE = "INSERT_STORE_CODE_HERE"
def insert_local_inventory():
"""Inserts a `LocalInventory` to a given product.
Replaces the full `LocalInventory` resource if an entry with the same
`region` already exists for the product.
It might take up to 30 minutes for the new or updated `LocalInventory`
resource to appear in products.
"""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = merchant_inventories_v1beta.LocalInventoryServiceClient(
credentials=credentials)
# Creates a Local inventory and populate its attributes.
local_inventory = merchant_inventories_v1beta.LocalInventory()
local_inventory.store_code = _STORE_CODE
local_inventory.availability = "in stock"
local_inventory.price = {
"currency_code": "USD",
"amount_micros": 33450000,
}
# Creates the request.
request = merchant_inventories_v1beta.InsertLocalInventoryRequest(
parent=_PARENT,
local_inventory=local_inventory,
)
# Makes the request and catch and print any error messages.
try:
response = client.insert_local_inventory(request=request)
print("Insert successful")
print(response)
except Exception as e:
print("Insert failed")
print(e)
if __name__ == "__main__":
insert_local_inventory()