Thư viện ứng dụng

Trong phương pháp tương tác với Merchant API này, bạn sử dụng các thư viện dựng sẵn để đóng gói thông tin chi tiết cấp thấp về việc đưa ra yêu cầu và xử lý phản hồi, mang đến một cách thức thuận tiện hơn và thường là theo ngôn ngữ đặc trưng để tương tác với API. Chúng xử lý việc xác thực, tuần tự hoá/giải tuần tự hoá yêu cầu và phản hồi, cũng như mã chuẩn khác.

Bước 1. Thiết lập quy trình xác thực và định cấu hình mã mẫu

Để biết hướng dẫn, hãy xem phần Thiết lập phương thức xác thực và cấu hình mẫu cho Merchant API.

Bước 2. Tải xuống và cài đặt thư viện ứng dụng và mã mẫu

Để biết hướng dẫn về cách tải xuống và cài đặt thư viện ứng dụng, cũng như cách sử dụng mã mẫu trên GitHub, hãy xem Mã mẫu Python của Google Merchant API.

Bước 3. Đăng ký làm nhà phát triển

Để sử dụng Merchant API, bạn phải đăng ký thông tin liên hệ của nhà phát triển.

Việc đăng ký sẽ giúp bạn:

  • Tạo một người liên hệ kỹ thuật cho tài khoản Merchant Center bằng cách chỉ định vai trò API developer cho một người dùng. Nhờ đó, Google có thể gửi các thông tin cập nhật quan trọng về API và những tính năng mà nhà phát triển đang sử dụng, chẳng hạn như thông báo về dịch vụ và thông tin về các tính năng mới. Những thông tin này có thể không được những người không phải là nhà phát triển quan tâm.
  • Cho phép bạn làm việc với nhiều tài khoản người bán mà không cần phải đăng ký nhiều lần. Khi bạn đăng ký, mã dự án Google Cloud dùng để xác thực với Merchant API sẽ được liên kết với tài khoản Merchant Center của bạn, tài khoản này có thông tin liên hệ kỹ thuật (API developer). Bằng cách này, bạn có thể nhận được thông tin cập nhật quan trọng cho tất cả tài khoản người bán mà bạn quản lý, miễn là bạn xác thực bằng dự án đã đăng ký trên Google Cloud.

Khi đăng ký, hãy tuân thủ các điều kiện tiên quyết và hạn chế được nêu chi tiết tại phần Đăng ký.

Để biết ví dụ về cách đăng ký dự án bằng thư viện ứng dụng, hãy xem mẫu Đăng ký dự án trên Google Cloud, cung cấp địa chỉ email của nhà phát triển bằng 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 DeveloperRegistrationServiceClient
from google.shopping.merchant_accounts_v1 import RegisterGcpRequest


def register_gcp(account_id: str, developer_email: str) -> None:
  """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.
  """
  # 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)
  except RuntimeError as e:
    print(f"An error occurred: {e}")


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)

Bước 4. Quản lý thông tin liên hệ và quyền của nhà phát triển

Khi bạn đăng ký:

  • Nếu địa chỉ email thuộc về một người dùng trong tài khoản Merchant Center, thì người dùng đó sẽ được cấp vai trò API_DEVELOPER.
  • Nếu địa chỉ email không thuộc về một người dùng hiện có, thì một lời mời sẽ được gửi đến địa chỉ đó. Người nhận phải chấp nhận lời mời thì mới được thêm làm người dùng mới có vai trò API_DEVELOPER.

Sau lần đăng ký ban đầu, bạn nên thêm nhiều nhà phát triển và cấp cho họ các quyền truy cập bổ sung.

Bước 4a. Cấp thêm quyền

Bạn phải có vai trò API_DEVELOPER để nhận thông báo quan trọng, nhưng vai trò này có rất ít quyền trong Merchant Center. Để cho phép người dùng này thực hiện các lệnh gọi API khác hoặc quản lý chế độ cài đặt trong giao diện người dùng Merchant Center, bạn cần cấp cho họ các vai trò bổ sung, chẳng hạn như STANDARD hoặc ADMIN. Để biết thêm thông tin, hãy xem phần Các loại quyền truy cập.

Bạn có thể cập nhật quyền truy cập của người dùng bằng phương thức accounts.users.patch.

Mã mẫu cho biết cách cập nhật người dùng để cấp cho họ cả vai trò ADMINAPI_DEVELOPER. Điều này cho phép họ quản lý hoàn toàn tài khoản và có nghĩa là họ cũng sẽ nhận được thông tin liên lạc liên quan đến 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)


Bước 4b. Thêm nhà phát triển dự phòng

Để tránh bị gián đoạn quyền truy cập API nếu người liên hệ chính của nhà phát triển rời khỏi tổ chức của bạn, bạn nên thêm ít nhất một nhà phát triển dự phòng.

Bạn có thể thêm người dùng bằng phương thức accounts.users.create hoặc cập nhật người dùng hiện tại bằng phương thức accounts.users.patch. Bạn nên cấp cho người dùng này cả vai trò ADMINAPI_DEVELOPER.

Bước 5. Tạo một nguồn dữ liệu sản phẩm chính

Bạn cần có một nguồn dữ liệu sản phẩm chính trước khi có thể chèn một sản phẩm. Để xem mã mẫu tạo nguồn dữ liệu, hãy xem Tạo một nguồn dữ liệu sản phẩm chính hỗ trợ mẫu nhiều ngôn ngữ bằng 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()


Bạn có thể xem nguồn dữ liệu này trong giao diện người dùng của Merchant Center. Để biết thêm thông tin, hãy xem bài viết Cách tìm thẻ Nguồn dữ liệu.

Bước 6. Chèn sản phẩm

Sau khi tạo nguồn dữ liệu, hãy thử chèn một sản phẩm vào đó. Để biết mã mẫu cho thấy cách thực hiện việc này bằng thư viện ứng dụng, hãy xem Chèn mẫu dữ liệu đầu vào của sản phẩm bằng 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

_ACCOUNT = configuration.Configuration().read_merchant_info()
_PARENT = f"accounts/{_ACCOUNT}"

# You can only insert products into datasource types of Input "API" and
# "FILE", and of Type "Primary" or "Supplemental."
_DATA_SOURCE = "[INSERT_DATA_SOURCE_HERE]"
_DATA_SOURCE_NAME = f"accounts/{_ACCOUNT}/dataSources/{_DATA_SOURCE}"


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():
  """Inserts the specified `ProductInput` resource."""

  # Gets OAuth Credentials.
  credentials = generate_user_credentials.main()

  # Creates a client.
  client = merchant_products_v1.ProductInputsServiceClient(
      credentials=credentials
  )

  # 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_NAME,
  )

  # 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}")
  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.


if __name__ == "__main__":
  insert_product_input()


Bước 7. Đăng sản phẩm

Để xem mã mẫu liệt kê các sản phẩm trong nguồn dữ liệu, hãy xem Liệt kê mẫu sản phẩm bằng 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()