Stay organized with collections
Save and categorize content based on your preferences.
Merchant API code sample to link a GBP account.
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.packageshopping.merchant.samples.accounts.gbpaccounts.v1;importcom.google.api.gax.core.FixedCredentialsProvider;importcom.google.auth.oauth2.GoogleCredentials;importcom.google.shopping.merchant.accounts.v1.AccountName;importcom.google.shopping.merchant.accounts.v1.GbpAccountsServiceClient;importcom.google.shopping.merchant.accounts.v1.GbpAccountsServiceSettings;importcom.google.shopping.merchant.accounts.v1.LinkGbpAccountRequest;importshopping.merchant.samples.utils.Authenticator;importshopping.merchant.samples.utils.Config;/** This class demonstrates how to link the specified merchant to a GBP account */publicclassLinkGbpAccountSample{publicstaticvoidlinkGbpAccount(Configconfig,StringgbpEmail)throwsException{// Obtains OAuth token based on the user's configuration.GoogleCredentialscredential=newAuthenticator().authenticate();// Creates service settings using the credentials retrieved above.GbpAccountsServiceSettingsgbpAccountsServiceSettings=GbpAccountsServiceSettings.newBuilder().setCredentialsProvider(FixedCredentialsProvider.create(credential)).build();// Calls the API and catches and prints any network failures/errors.try(GbpAccountsServiceClientgbpAccountsServiceClient=GbpAccountsServiceClient.create(gbpAccountsServiceSettings)){StringaccountId=config.getAccountId().toString();// Creates parent to identify the omnichannelSetting from which to list all Lfp Providers.Stringparent=AccountName.newBuilder().setAccount(accountId).build().toString();LinkGbpAccountRequestrequest=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(Exceptione){System.out.println("An error has occured: ");System.out.println(e);}}publicstaticvoidmain(String[]args)throwsException{Configconfig=Config.load();// The email address of the Business Profile account.StringgbpEmail="{GBP_EMAIL}";linkGbpAccount(config,gbpEmail);}}
<?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();
# -*- 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."""fromexamples.authenticationimportconfigurationfromexamples.authenticationimportgenerate_user_credentialsfromgoogle.shopping.merchant_accounts_v1importGbpAccountsServiceClientfromgoogle.shopping.merchant_accounts_v1importLinkGbpAccountRequest# 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}"deflink_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}")exceptRuntimeErrorase: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)
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-21 UTC."],[],[],null,["# Link a GBP account\n\nMerchant API code sample to link a GBP account. \n\n### Java\n\n // Copyright 2025 Google LLC\n\n // Licensed under the Apache License, Version 2.0 (the \"License\");\n // you may not use this file except in compliance with the License.\n // You may obtain a copy of the License at\n //\n // https://www.apache.org/licenses/LICENSE-2.0\n //\n // Unless required by applicable law or agreed to in writing, software\n // distributed under the License is distributed on an \"AS IS\" BASIS,\n // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n // See the License for the specific language governing permissions and\n // limitations under the License.\n\n package shopping.merchant.samples.accounts.gbpaccounts.v1;\n\n import com.google.api.gax.core.FixedCredentialsProvider;\n import com.google.auth.oauth2.GoogleCredentials;\n import com.google.shopping.merchant.accounts.v1.AccountName;\n import com.google.shopping.merchant.accounts.v1.GbpAccountsServiceClient;\n import com.google.shopping.merchant.accounts.v1.GbpAccountsServiceSettings;\n import com.google.shopping.merchant.accounts.v1.LinkGbpAccountRequest;\n import shopping.merchant.samples.utils.Authenticator;\n import shopping.merchant.samples.utils.Config;\n\n /** This class demonstrates how to link the specified merchant to a GBP account */\n public class LinkGbpAccountSample {\n\n public static void linkGbpAccount(Config config, String gbpEmail) throws Exception {\n\n // Obtains OAuth token based on the user's configuration.\n GoogleCredentials credential = new Authenticator().authenticate();\n\n // Creates service settings using the credentials retrieved above.\n GbpAccountsServiceSettings gbpAccountsServiceSettings =\n GbpAccountsServiceSettings.newBuilder()\n .setCredentialsProvider(FixedCredentialsProvider.create(credential))\n .build();\n\n // Calls the API and catches and prints any network failures/errors.\n try (GbpAccountsServiceClient gbpAccountsServiceClient =\n GbpAccountsServiceClient.create(gbpAccountsServiceSettings)) {\n String accountId = config.getAccountId().toString();\n // Creates parent to identify the omnichannelSetting from which to list all Lfp Providers.\n String parent = AccountName.newBuilder().setAccount(accountId).build().toString();\n\n LinkGbpAccountRequest request =\n LinkGbpAccountRequest.newBuilder().setParent(parent).setGbpEmail(gbpEmail).build();\n\n System.out.println(\"Sending link GBP account request:\");\n // Empty response returned on success.\n gbpAccountsServiceClient.linkGbpAccount(request);\n System.out.println(String.format(\"Successfully linked to GBP account: %s\", gbpEmail));\n } catch (Exception e) {\n System.out.println(\"An error has occured: \");\n System.out.println(e);\n }\n }\n\n public static void main(String[] args) throws Exception {\n Config config = Config.load();\n\n // The email address of the Business Profile account.\n String gbpEmail = \"{GBP_EMAIL}\";\n\n linkGbpAccount(config, gbpEmail);\n }\n } \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/java/src/main/java/shopping/merchant/samples/accounts/gbpaccounts/v1/LinkGbpAccountSample.java\n\n### PHP\n\n \u003c?php\n /**\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n require_once __DIR__ . '/../../../../vendor/autoload.php';\n require_once __DIR__ . '/../../../Authentication/Authentication.php';\n require_once __DIR__ . '/../../../Authentication/Config.php';\n\n use Google\\ApiCore\\ApiException;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\Client\\GbpAccountsServiceClient;\n use Google\\Shopping\\Merchant\\Accounts\\V1\\LinkGbpAccountRequest;\n\n /**\n * This class demonstrates how to link the specified merchant to a GBP account.\n */\n class LinkGbpAccountSample\n {\n /**\n * A helper function to create the parent string.\n *\n * @param string $accountId The account ID.\n *\n * @return string The parent has the format: `accounts/{account_id}`\n */\n private static function getParent(string $accountId): string\n {\n return sprintf('accounts/%s', $accountId);\n }\n\n /**\n * Links the specified merchant to a GBP account.\n *\n * @param array $config The configuration data for authentication and account ID.\n * @param string $gbpEmail The email address of the Business Profile account.\n *\n * @return void\n */\n public static function linkGbpAccount(array $config, string $gbpEmail): void\n {\n // Gets the OAuth credentials to make the request.\n $credentials = Authentication::useServiceAccountOrTokenFile();\n\n // Creates options config containing credentials for the client to use.\n $options = ['credentials' =\u003e $credentials];\n\n // Creates a client.\n $gbpAccountsServiceClient = new GbpAccountsServiceClient($options);\n\n // Creates the parent account name to identify the merchant.\n $parent = self::getParent($config['accountId']);\n\n // Creates the request to link the GBP account.\n $request = new LinkGbpAccountRequest([\n 'parent' =\u003e $parent,\n 'gbp_email' =\u003e $gbpEmail\n ]);\n\n // Calls the API and catches and prints any network failures/errors.\n try {\n printf(\"Sending link GBP account request:%s\", PHP_EOL);\n // An empty response is returned on success.\n $gbpAccountsServiceClient-\u003elinkGbpAccount($request);\n printf(\"Successfully linked to GBP account: %s%s\", $gbpEmail, PHP_EOL);\n } catch (ApiException $e) {\n printf(\"An error has occurred: %s%s\", $e-\u003egetMessage(), PHP_EOL);\n }\n }\n\n /**\n * Helper to execute the sample.\n *\n * @return void\n */\n public function callSample(): void\n {\n $config = Config::generateConfig();\n\n // The email address of the Business Profile account.\n $gbpEmail = '{GBP_EMAIL}';\n\n self::linkGbpAccount($config, $gbpEmail);\n }\n }\n\n // Runs the script.\n $sample = new LinkGbpAccountSample();\n $sample-\u003ecallSample(); \n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/php/examples/accounts/gbpaccounts/v1/LinkGbpAccountSample.php\n\n### Python\n\n # -*- coding: utf-8 -*-\n # Copyright 2025 Google LLC\n #\n # Licensed under the Apache License, Version 2.0 (the \"License\");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # http://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an \"AS IS\" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n \"\"\"This class demonstrates how to link the specified merchant to a GBP account.\"\"\"\n\n from examples.authentication import configuration\n from examples.authentication import generate_user_credentials\n from google.shopping.merchant_accounts_v1 import GbpAccountsServiceClient\n from google.shopping.merchant_accounts_v1 import LinkGbpAccountRequest\n\n # Gets the merchant account ID from the configuration file.\n _ACCOUNT = configuration.Configuration().read_merchant_info()\n # Creates the parent resource name string.\n _PARENT = f\"accounts/{_ACCOUNT}\"\n\n\n def link_gbp_account(gbp_email: str) -\u003e None:\n \"\"\"Links the specified merchant to a Google Business Profile account.\n\n Args:\n gbp_email: The email address of the Business Profile account.\n \"\"\"\n\n # Gets OAuth Credentials.\n credentials = generate_user_credentials.main()\n\n # Creates a client.\n client = GbpAccountsServiceClient(credentials=credentials)\n\n # Creates the request.\n request = LinkGbpAccountRequest(parent=_PARENT, gbp_email=gbp_email)\n\n # Makes the request and catches and prints any error messages.\n try:\n print(\"Sending link GBP account request:\")\n # An empty response is returned on success.\n client.link_gbp_account(request=request)\n print(f\"Successfully linked to GBP account: {gbp_email}\")\n except RuntimeError as e:\n print(\"An error has occured: \")\n print(e)\n\n\n if __name__ == \"__main__\":\n # The email address of the Business Profile account.\n _gbp_email = \"{GBP_EMAIL}\"\n link_gbp_account(_gbp_email)\n\n https://github.com/google/merchant-api-samples/blob/c6de994268c785ce22af0065932518a9ac5b3c03/python/examples/accounts/gbpaccounts/v1/link_gbp_account_sample.py"]]