关联 Google 商家资料账号

用于关联 GBP 账号的 Merchant API 代码示例。

Java

// 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.

package shopping.merchant.samples.accounts.gbpaccounts.v1;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccountName;
import com.google.shopping.merchant.accounts.v1.GbpAccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.GbpAccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.LinkGbpAccountRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to link the specified merchant to a GBP account */
public class LinkGbpAccountSample {

  public static void linkGbpAccount(Config config, String gbpEmail) throws Exception {

    // Obtains OAuth token based on the user's configuration.
    GoogleCredentials credential = new Authenticator().authenticate();

    // Creates service settings using the credentials retrieved above.
    GbpAccountsServiceSettings gbpAccountsServiceSettings =
        GbpAccountsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Calls the API and catches and prints any network failures/errors.
    try (GbpAccountsServiceClient gbpAccountsServiceClient =
        GbpAccountsServiceClient.create(gbpAccountsServiceSettings)) {
      String accountId = config.getAccountId().toString();
      // Creates parent to identify the omnichannelSetting from which to list all Lfp Providers.
      String parent = AccountName.newBuilder().setAccount(accountId).build().toString();

      LinkGbpAccountRequest request =
          LinkGbpAccountRequest.newBuilder().setParent(parent).setGbpEmail(gbpEmail).build();

      System.out.println("Sending link GBP account request:");
      // Empty response returned on success.
      gbpAccountsServiceClient.linkGbpAccount(request);
      System.out.println(String.format("Successfully linked to GBP account: %s", gbpEmail));
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    // The email address of the Business Profile account.
    String gbpEmail = "{GBP_EMAIL}";

    linkGbpAccount(config, gbpEmail);
  }
}

PHP

<?php
/**
 * 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.
 */
require_once __DIR__ . '/../../../../vendor/autoload.php';
require_once __DIR__ . '/../../../Authentication/Authentication.php';
require_once __DIR__ . '/../../../Authentication/Config.php';

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\GbpAccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\LinkGbpAccountRequest;

/**
 * This class demonstrates how to link the specified merchant to a GBP account.
 */
class LinkGbpAccountSample
{
    /**
     * A helper function to create the parent string.
     *
     * @param string $accountId The account ID.
     *
     * @return string The parent has the format: `accounts/{account_id}`
     */
    private static function getParent(string $accountId): string
    {
        return sprintf('accounts/%s', $accountId);
    }

    /**
     * Links the specified merchant to a GBP account.
     *
     * @param array $config The configuration data for authentication and account ID.
     * @param string $gbpEmail The email address of the Business Profile account.
     *
     * @return void
     */
    public static function linkGbpAccount(array $config, string $gbpEmail): 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.
        $gbpAccountsServiceClient = new GbpAccountsServiceClient($options);

        // Creates the parent account name to identify the merchant.
        $parent = self::getParent($config['accountId']);

        // Creates the request to link the GBP account.
        $request = new LinkGbpAccountRequest([
            'parent' => $parent,
            'gbp_email' => $gbpEmail
        ]);

        // Calls the API and catches and prints any network failures/errors.
        try {
            printf("Sending link GBP account request:%s", PHP_EOL);
            // An empty response is returned on success.
            $gbpAccountsServiceClient->linkGbpAccount($request);
            printf("Successfully linked to GBP account: %s%s", $gbpEmail, PHP_EOL);
        } catch (ApiException $e) {
            printf("An error has occurred: %s%s", $e->getMessage(), PHP_EOL);
        }
    }

    /**
     * Helper to execute the sample.
     *
     * @return void
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();

        // The email address of the Business Profile account.
        $gbpEmail = '{GBP_EMAIL}';

        self::linkGbpAccount($config, $gbpEmail);
    }
}

// Runs the script.
$sample = new LinkGbpAccountSample();
$sample->callSample();

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
#
#     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 link the specified merchant to a GBP account."""

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import GbpAccountsServiceClient
from google.shopping.merchant_accounts_v1 import LinkGbpAccountRequest

# Gets the merchant account ID from the configuration file.
_ACCOUNT = configuration.Configuration().read_merchant_info()
# Creates the parent resource name string.
_PARENT = f"accounts/{_ACCOUNT}"


def link_gbp_account(gbp_email: str) -> None:
  """Links the specified merchant to a Google Business Profile account.

  Args:
    gbp_email: The email address of the Business Profile account.
  """

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

  # Creates a client.
  client = GbpAccountsServiceClient(credentials=credentials)

  # Creates the request.
  request = LinkGbpAccountRequest(parent=_PARENT, gbp_email=gbp_email)

  # Makes the request and catches and prints any error messages.
  try:
    print("Sending link GBP account request:")
    # An empty response is returned on success.
    client.link_gbp_account(request=request)
    print(f"Successfully linked to GBP account: {gbp_email}")
  except RuntimeError as e:
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  # The email address of the Business Profile account.
  _gbp_email = "{GBP_EMAIL}"
  link_gbp_account(_gbp_email)