클라이언트 라이브러리

Merchant API와 상호작용하는 이 접근 방식에서는 요청을 하고 응답을 처리하는 하위 수준 세부정보를 캡슐화하는 사전 빌드된 라이브러리를 사용하여 API와 더 편리하고 언어에 맞는 방식으로 상호작용합니다. 인증, 요청 및 응답 직렬화/역직렬화, 기타 상용구 코드를 처리합니다.

1단계: 인증 설정 및 코드 샘플 구성

자세한 내용은 판매자 API 인증 설정 및 샘플 구성 샘플을 참고하세요.

2단계: 클라이언트 라이브러리 및 코드 샘플 다운로드 및 설치

클라이언트 라이브러리를 다운로드 및 설치하고 GitHub의 코드 샘플을 사용하는 방법은 Google Merchant API Python 샘플을 참고하세요.

3단계: 개발자로 등록

Merchant API를 사용하려면 개발자 연락처 정보를 등록해야 합니다.

등록을 통해 다음을 수행할 수 있습니다.

  • 사용자에게 API developer 역할을 할당하여 판매자 센터 계정의 기술 담당자를 만듭니다. 이를 통해 Google은 개발자가 사용하는 API 및 기능에 관한 중요한 업데이트(예: 서비스 공지사항, 새로운 기능에 관한 정보)를 전송할 수 있습니다. 이러한 업데이트는 개발자가 아닌 사용자에게는 관심이 없을 수 있습니다.
  • 여러 번 등록하지 않고도 여러 판매자 계정으로 작업할 수 있습니다. 등록하면 판매자 API에 인증하는 데 사용되는 Google Cloud 프로젝트 ID가 기술 담당자 (API developer)가 있는 판매자 센터 계정과 연결됩니다. 이렇게 하면 등록된 Google Cloud 프로젝트로 인증하는 한 관리하는 모든 판매자 계정에 대한 중요한 업데이트를 받을 수 있습니다.

등록 시 등록에 자세히 설명된 기본 요건과 제한사항을 준수하세요.

클라이언트 라이브러리를 사용하여 프로젝트를 등록하는 방법의 예는 Python을 사용하여 개발자 이메일 주소를 제공하여 Google Cloud 프로젝트 등록 샘플을 참고하세요.

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)

4단계: 개발자 연락처 및 권한 관리

등록 시 다음 사항이 적용됩니다.

  • 이메일 주소가 판매자 센터 계정의 사용자에게 속한 경우 해당 사용자에게 API_DEVELOPER 역할이 부여됩니다.
  • 이메일 주소가 기존 사용자의 주소가 아닌 경우 해당 주소로 초대가 전송됩니다. API_DEVELOPER 역할이 있는 새 사용자로 추가되려면 수신자가 초대를 수락해야 합니다.

초기 등록 후에는 여러 개발자를 추가하고 추가 액세스 권한을 부여하는 것이 좋습니다.

4a단계. 추가 권한 부여

API_DEVELOPER 역할은 중요한 알림을 받는 데 필요하지만 판매자 센터 내에서 최소한의 권한을 갖습니다. 이 사용자가 다른 API를 호출하거나 판매자 센터 UI에서 설정을 관리하도록 허용하려면 STANDARD 또는 ADMIN과 같은 추가 역할을 부여해야 합니다. 자세한 내용은 액세스 유형을 참고하세요.

accounts.users.patch 메서드로 사용자의 액세스 권한을 업데이트할 수 있습니다.

샘플 코드는 사용자에게 ADMINAPI_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 메서드를 사용하여 기존 사용자를 업데이트할 수 있습니다. 이 사용자에게 ADMINAPI_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()


판매자 센터 UI에서 이 데이터 소스를 확인할 수 있습니다. 자세한 내용은 데이터 소스 탭을 찾는 방법을 참고하세요.

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

_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()


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()