這種與 Merchant API 互動的方法,會使用預先建構的程式庫,封裝發出要求和處理回應的低階詳細資料,提供更便利且通常符合語言慣例的方式與 API 互動。負責處理驗證、要求和回應序列化/反序列化,以及其他樣板程式碼。
步驟 1:設定驗證機制及程式碼範例
如需操作說明,請參閱「設定 Merchant API 的驗證和範例設定」。
步驟 2:下載並安裝用戶端程式庫和程式碼範例
如需下載及安裝用戶端程式庫,以及使用 GitHub 程式碼範例的操作說明,請參閱 Google Merchant API Python 範例。
步驟 3:註冊成為開發人員
如要使用 Merchant API,請務必註冊開發人員聯絡資訊。
註冊後可執行下列操作:
- 將
API developer角色指派給使用者,為 Merchant Center 帳戶建立技術聯絡人。這樣一來,Google 就能傳送與 API 和開發人員所用功能相關的重要更新,例如服務公告和新功能資訊,這些資訊可能對非開發人員較不重要。 - 可讓你使用多個商家帳戶,不必多次註冊。註冊時,用於驗證 Merchant API 的 Google Cloud 雲端專案 ID 會與 Merchant Center 帳戶建立關聯,該帳戶包含技術聯絡人 (
API developer)。這樣一來,只要使用註冊的 Google Cloud 雲端專案完成驗證,就能取得所管理所有商家帳戶的重要更新。
註冊時,請遵守「註冊」一節詳述的必要條件和限制。
如需使用用戶端程式庫註冊專案的範例,請參閱「註冊 Google Cloud 專案,並使用 Python 提供開發人員電子郵件地址」範例:
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
#
# 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 example registers a GCP project with a developer email."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import DeveloperRegistration
from google.shopping.merchant_accounts_v1 import DeveloperRegistrationServiceClient
from google.shopping.merchant_accounts_v1 import RegisterGcpRequest
def register_gcp(
account_id: str, developer_email: str
) -> DeveloperRegistration:
"""Registers the GCP project used to call the Merchant API with a developer email.
Args:
account_id: The ID of your Merchant Center account.
developer_email: The email address of the developer to register.
Returns:
The created or updated DeveloperRegistration object.
"""
# Get OAuth credentials.
credentials = generate_user_credentials.main()
# Create a client to the Developer Registration Service.
client = DeveloperRegistrationServiceClient(credentials=credentials)
# The name has the format: accounts/{account}/developerRegistration
name = f"accounts/{account_id}/developerRegistration"
# Create the request to register the GCP project.
request = RegisterGcpRequest(
name=name,
developer_email=developer_email,
)
# Make the API call and handle potential errors.
try:
print("Sending RegisterGcp request:")
response = client.register_gcp(request=request)
print("Registered GCP project successfully:")
print(response)
return response
except RuntimeError as e:
print(f"An error occurred: {e}")
raise
if __name__ == "__main__":
# Your Merchant Center account ID.
# This can be found in the Merchant Center UI.
_account_id = configuration.Configuration().read_merchant_info()
# The developer email to associate with the GCP project.
_developer_email = "YOUR_EMAIL_HERE"
register_gcp(_account_id, _developer_email)
步驟 4:管理開發人員聯絡人和權限
註冊時:
- 如果電子郵件地址屬於 Merchant Center 帳戶中的使用者,該使用者會獲得
API_DEVELOPER角色。 - 如果電子郵件地址不屬於現有使用者,系統會傳送邀請到該地址。收件者必須接受邀請,才能以
API_DEVELOPER角色新增為新使用者。
完成初始註冊後,建議您新增多位開發人員,並授予額外存取權。
步驟 4a. 授予其他權限
API_DEVELOPER 角色是接收重要通知的必要角色,但在 Merchant Center 中具備的權限最少。如要允許這位使用者發出其他 API 呼叫,或在 Merchant Center 使用者介面中管理設定,您必須授予其他角色,例如 STANDARD 或 ADMIN。詳情請參閱「存取權類型」。
您可以使用 accounts.users.patch 方法更新使用者的存取權。
程式碼範例說明如何更新使用者,同時授予 ADMIN 和 API_DEVELOPER 角色。這樣一來,他們就能完整管理帳戶,並接收 API 相關通訊。
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 update a user."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.protobuf import field_mask_pb2
from google.shopping.merchant_accounts_v1 import AccessRight
from google.shopping.merchant_accounts_v1 import UpdateUserRequest
from google.shopping.merchant_accounts_v1 import User
from google.shopping.merchant_accounts_v1 import UserServiceClient
FieldMask = field_mask_pb2.FieldMask
_ACCOUNT = configuration.Configuration().read_merchant_info()
def update_user(user_email, user_access_right):
"""Updates a user to make it an admin of the MC account."""
credentials = generate_user_credentials.main()
client = UserServiceClient(credentials=credentials)
# Create user name string
name = "accounts/" + _ACCOUNT + "/users/" + user_email
user = User(name=name, access_rights=[user_access_right])
field_mask = FieldMask(paths=["access_rights"])
try:
request = UpdateUserRequest(user=user, update_mask=field_mask)
print("Sending Update User request")
response = client.update_user(request=request)
print("Updated User Name below")
print(response.name)
except RuntimeError as e:
print(e)
if __name__ == "__main__":
# Modify this email to update the right user
email = "USER_MAIL_ACCOUNT"
access_right = AccessRight.ADMIN
update_user(email, access_right)
步驟 4b. 新增備用開發人員
為避免主要開發人員聯絡人離職時,API 存取權中斷,建議您至少新增一位備用開發人員。
您可以使用 accounts.users.create 方法新增使用者,或使用 accounts.users.patch 方法更新現有使用者。建議同時授予這位使用者 ADMIN 和 API_DEVELOPER 角色。
步驟 5:建立主要產品資料來源
你必須先有主要產品資料來源,才能插入產品。如需建立資料來源的程式碼範例,請參閱「使用 Python 建立支援多種語言的主要產品資料來源範例」。
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.
"""This class demonstrates how to create a Primary product datasource all `feedLabel` and `contentLanguage` combinations.
This works only for API primary feeds.
"""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_datasources_v1 import CreateDataSourceRequest
from google.shopping.merchant_datasources_v1 import DataSource
from google.shopping.merchant_datasources_v1 import DataSourcesServiceClient
from google.shopping.merchant_datasources_v1 import PrimaryProductDataSource
_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"
def create_primary_product_data_source_multiple_languages():
"""Creates a `DataSource` resource."""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = DataSourcesServiceClient(credentials=credentials)
# Creates a PrimaryProductDataSource.
primary_datasource = PrimaryProductDataSource()
primary_datasource.countries = ["GB"]
# Creates a DataSource and populates its attributes.
data_source = DataSource()
data_source.display_name = "Example Multiple Languages Primary DataSource"
data_source.primary_product_data_source = primary_datasource
# Creates the request.
request = CreateDataSourceRequest(parent=_PARENT, data_source=data_source)
# Makes the request and catches and prints any error messages.
try:
response = client.create_data_source(request=request)
print(f"DataSource successfully created: {response}")
except RuntimeError as e:
print("DataSource creation failed")
print(e)
if __name__ == "__main__":
create_primary_product_data_source_multiple_languages()
你可以在 Merchant Center 使用者介面中查看這個資料來源。詳情請參閱「如何找出『資料來源』分頁」。
步驟 6:插入一項產品
建立資料來源後,請嘗試在其中插入產品。如要查看程式碼範例,瞭解如何使用用戶端程式庫執行這項操作,請參閱「使用 Python 插入產品輸入範例」。
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 Product Input."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_products_v1
from google.shopping.merchant_products_v1 import Availability
from google.shopping.merchant_products_v1 import Condition
from google.shopping.type import Price
def create_product_input():
"""Creates a `ProductInput` resource."""
# Creates a shipping setting
price = Price()
price.amount_micros = 33_450_000
price.currency_code = "GBP"
shipping_option_1 = merchant_products_v1.Shipping()
shipping_option_1.price = price
shipping_option_1.country = "GB"
shipping_option_1.service = "1st class post"
price2 = Price()
price2.amount_micros = 33_450_000
price2.currency_code = "EUR"
shipping_option_2 = merchant_products_v1.Shipping()
shipping_option_2.price = price2
shipping_option_2.country = "FR"
shipping_option_2.service = "2nd class post"
# Sets product attributes. Make sure to replace these values with your own.
attributes = merchant_products_v1.ProductAttributes()
attributes.title = "A Tale of Two Cities"
attributes.description = "A classic novel about the French Revolution"
attributes.link = "https://exampleWebsite.com/tale-of-two-cities.html"
attributes.image_link = "https://exampleWebsite.com/tale-of-two-cities.jpg"
attributes.price = price
attributes.availability = Availability.IN_STOCK
attributes.condition = Condition.NEW
attributes.google_product_category = "Media > Books"
attributes.gtins = ["9780007350896"]
attributes.shipping = [shipping_option_1, shipping_option_2]
return merchant_products_v1.ProductInput(
content_language="en",
feed_label="GB",
offer_id="sku123",
product_attributes=attributes,
)
def insert_product_input(account_id: str, data_source: str):
"""Inserts the specified `ProductInput` resource.
Args:
account_id: The Merchant Center account ID.
data_source: The resource name of the data source that will own the product
input.
Returns:
The inserted `ProductInput` resource.
"""
# Gets OAuth Credentials.
credentials = generate_user_credentials.main()
# Creates a client.
client = merchant_products_v1.ProductInputsServiceClient(
credentials=credentials
)
parent = f"accounts/{account_id}"
# Creates the request.
request = merchant_products_v1.InsertProductInputRequest(
parent=parent,
# If this product is already owned by another datasource, when
# re-inserting, the new datasource will take ownership of the product.
product_input=create_product_input(),
data_source=data_source,
)
# Makes the request and catches and prints any error messages.
try:
response = client.insert_product_input(request=request)
# The last part of the product name will be the product ID assigned to a
# product by Google. Product ID has the format
# `contentLanguage~feedLabel~offerId`
print(f"Input successful: {response}")
return response
except RuntimeError as e:
print("Input failed")
print(e)
# After the product is inserted, the product ID will be returned in the
# response. We recommend that you check the Merchant Center to ensure that
# the product is approved and visible to users before using the product ID
# in any downstream processes.
raise
if __name__ == "__main__":
# Retrieves the Merchant Center account ID from the configuration file.
merchant_account_id = configuration.Configuration().read_merchant_info()
# Identifies the data source that will own the product input.
# You can only insert products into datasource types of Input "API" and
# "FILE", and of Type "Primary" or "Supplemental."
target_data_source = (
f"accounts/{merchant_account_id}/dataSources/[INSERT_DATA_SOURCE_HERE]"
)
insert_product_input(merchant_account_id, target_data_source)
步驟 7:刊登產品
如需列出資料來源中產品的程式碼範例,請參閱「使用 Python 列出產品範例」。
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 Products."""
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping import merchant_products_v1
_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_v1.ProductsServiceClient(
credentials=credentials
)
# Creates the request. Set the page size to the maximum value.
request = merchant_products_v1.ListProductsRequest(
parent=_PARENT, page_size=1000
)
# Makes the request and catches and prints any error messages.
try:
response = client.list_products(request=request)
for product in response:
print(product)
print("List request successful!")
except RuntimeError as e:
print("List request failed")
print(e)
if __name__ == "__main__":
list_products()