Google Business Profile API を用いた商品登録手順

お客様: Google Business Profile API (旧 Google My Business API) を利用し、ビジネスプロフィールの商品を登録したいと考えております。

AI: かしこまりました。API を活用することで、プログラムからの効率的な情報管理が可能となります。以下に、商品登録に向けた手順をご案内申し上げます。

Google Cloud コンソールにて、適切なプロジェクトをご作成またはご選択されましたでしょうか?

「My Business Account Management API」および「My Business Business Information API」が有効化されているかご確認ください。

  • はい → 次へ!
  • いいえ → API ライブラリにて両 API を検索し、有効化してください。

OAuth 2.0 クライアント ID を作成し、credentials.json ファイルをダウンロードされましたでしょうか?

初回実行時に認証を通し、token.json ファイルが作成されましたでしょうか?

  • はい → 次へ!
  • いいえ → ロケーション ID 取得コードを実行して認証してください。

ロケーション ID を取得できましたか?

  • はい → 次へ! (.env ファイルに設定してください)
  • いいえ → 以下のコードを実行して取得しましょう!
import os
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/business.manage']

def get_credentials():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds

if __name__ == '__main__':
    creds = get_credentials()
    if creds:
        service = build('mybusinessaccountmanagement', 'v1', credentials=creds)
        try:
            accounts = service.accounts().list().execute()
            if 'accounts' in accounts:
                for account in accounts['accounts']:
                    print(f"アカウント名: {account['name']}")
                    locations = service.accounts().locations().list(parent=account['name']).execute()
                    if 'locations' in locations:
                        for location in locations['locations']:
                            print(f"  ロケーション名: {location['name']}")
                            location_id = location['name'].split('/')[-1]
                            print(f"    ロケーション ID: {location_id}")
        except Exception as e:
            print(f"エラーが発生しました: {e}")
    else:
        print("認証に失敗しました。")

割り当て超過エラー (HttpError 429) が発生した場合は、以下の手順で割り当て引き上げをリクエストしてください。

  1. Google Cloud コンソール にアクセスします。
  2. 左側のメニューから [IAM と管理] > [割り当て] を選択します。
  3. サービスで 「My Business Account Management API」 をフィルタリングします。
  4. 「リクエスト/分/プロジェクト」 の割り当てを選択し、[割り当てを編集] をクリックします。
  5. 新しい割り当て値(最初は 20 程度で試してみましょう)を入力し、理由を記述してリクエストを送信します。
  6. リクエストが承認されるまで待ちます(通常 1~2 営業日)。

.env ファイルに LOCATION_ID および ACCOUNT_ID を設定後、以下のコードを実行して商品登録をテストします。

import os
from dotenv import load_dotenv
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.errors import HttpError

load_dotenv()
LOCATION_ID = os.getenv('LOCATION_ID')
ACCOUNT_ID = os.getenv('ACCOUNT_ID')
SCOPES = ['https://www.googleapis.com/auth/business.manage']

def get_credentials():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return creds

def add_product(service, location_id, product_data):
    try:
        request = service.locations().products().create(
            parent=location_id,
            body=product_data
        )
        response = request.execute()
        print('商品が登録されました:', response)
    except HttpError as err:
        print(f'商品登録エラーが発生しました: {err}')
        if err.resp and err.content:
            print(f'詳細: {err.content.decode("utf-8")}')

if __name__ == '__main__':
    creds = get_credentials()
    if creds:
        business_info_service = build('mybusinessbusinessinformation', 'v1', credentials=creds)

        if LOCATION_ID and ACCOUNT_ID:
            product_data = {
                'title': 'テスト商品 (環境変数)',
                'description': 'dotenv から読み込んだロケーション ID を使用した登録テストです。',
                'category': 'その他',  # 適切なカテゴリを指定してください
                'price': {
                    'currency': 'JPY',
                    'units': 1200,
                    'nanos': 0  # 必要に応じて修正
                }
            }
            add_product(business_info_service, f"accounts/{ACCOUNT_ID}/locations/{LOCATION_ID}", product_data)
        else:
            print("環境変数 LOCATION_ID または ACCOUNT_ID が設定されていません。")
    else:
        print("認証に失敗しました。")

商品登録でエラーが発生した場合は、エラーメッセージの詳細をお知らせください。

現在、割り当て引き上げの承認をお待ちいただいているとのこと、承知いたしました。承認後、上記の手順に従って商品登録のテストに進むことができます。何かご不明な点がございましたら、お気軽にお知らせください。引き続き、ご支援させていただきます。