Update an account relationship

Merchant API code sample to update an account relationship.

Java

// 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
//
//     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.accountrelationships.v1;

import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.protobuf.FieldMask;
import com.google.shopping.merchant.accounts.v1.AccountRelationship;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipName;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountRelationshipsServiceSettings;
import com.google.shopping.merchant.accounts.v1.UpdateAccountRelationshipRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to update a business relationship. */
public class UpdateAccountRelationshipSample {

  public static void updateAccountRelationship(Config config, long providerId) throws Exception {

    GoogleCredentials credential = new Authenticator().authenticate();

    AccountRelationshipsServiceSettings accountRelationshipServiceSettings =
        AccountRelationshipsServiceSettings.newBuilder()
            .setCredentialsProvider(FixedCredentialsProvider.create(credential))
            .build();

    // Gets the account ID from the config file.
    String accountId = config.getAccountId().toString();

    // Creates account relationship name to identify the account relationship.
    String name =
        AccountRelationshipName.newBuilder()
            .setAccount(accountId)
            .setRelationship(String.valueOf(providerId))
            .build()
            .toString();

    // Create a AccountRelationship with the updated fields.
    AccountRelationship accountRelationship =
        AccountRelationship.newBuilder().setName(name).setAccountIdAlias("alias").build();

    FieldMask fieldMask = FieldMask.newBuilder().addPaths("account_id_alias").build();

    try (AccountRelationshipsServiceClient accountRelationshipServiceClient =
        AccountRelationshipsServiceClient.create(accountRelationshipServiceSettings)) {

      UpdateAccountRelationshipRequest request =
          UpdateAccountRelationshipRequest.newBuilder()
              .setAccountRelationship(accountRelationship)
              .setUpdateMask(fieldMask)
              .build();

      System.out.println("Sending Update AccountRelationship request");
      AccountRelationship response =
          accountRelationshipServiceClient.updateAccountRelationship(request);
      System.out.println("Updated AccountRelationship below");
      System.out.println(response);
    } catch (Exception e) {
      System.out.println(e);
    }
  }

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

    updateAccountRelationship(config, 111L);
  }
}

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\Protobuf\FieldMask;
use Google\Shopping\Merchant\Accounts\V1\AccountRelationship;
use Google\Shopping\Merchant\Accounts\V1\Client\AccountRelationshipsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\UpdateAccountRelationshipRequest;

/**
 * This class demonstrates how to update an account relationship.
 */
class UpdateAccountRelationshipSample
{
    /**
     * Updates a specific account relationship.
     *
     * @param array $config The configuration file for authentication.
     * @param int $providerId The ID of the provider for the relationship.
     */
    public static function updateAccountRelationshipSample(array $config, int $providerId): 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.
        $accountRelationshipsServiceClient = new AccountRelationshipsServiceClient($options);

        // The name of the account relationship to update.
        // Format: accounts/{account}/relationships/{provider}
        $name = $accountRelationshipsServiceClient->accountRelationshipName(
            $config['accountId'],
            $providerId
        );

        // Creates an AccountRelationship with the updated fields.
        $accountRelationship = new AccountRelationship([
            'name' => $name,
            'account_id_alias' => 'alias'
        ]);

        // Creates a field mask to specify which fields to update. In this case,
        // only `account_id_alias` will be updated.
        $fieldMask = new FieldMask([
            'paths' => ['account_id_alias']
        ]);

        // Creates the request.
        $request = new UpdateAccountRelationshipRequest([
            'account_relationship' => $accountRelationship,
            'update_mask' => $fieldMask
        ]);

        // Calls the API and catches and prints any network failures/errors.
        try {
            printf("Sending Update AccountRelationship request%s", PHP_EOL);
            $response = $accountRelationshipsServiceClient->updateAccountRelationship($request);
            printf("Updated AccountRelationship below%s", PHP_EOL);
            print $response->serializeToJsonString(true) . PHP_EOL;
        } catch (ApiException $e) {
            print $e->getMessage() . PHP_EOL;
        }
    }

    /**
     * Helper to execute the sample.
     */
    public function callSample(): void
    {
        $config = Config::generateConfig();
        // The ID of the provider for which you want to update the relationship.
        $providerId = 111;
        self::updateAccountRelationshipSample($config, $providerId);
    }
}

// Runs the sample.
$sample = new UpdateAccountRelationshipSample();
$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.

"""Sample for updating an account relationship."""
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 AccountRelationship
from google.shopping.merchant_accounts_v1 import AccountRelationshipsServiceClient
from google.shopping.merchant_accounts_v1 import UpdateAccountRelationshipRequest

# Gets the account ID from the configuration file.
_ACCOUNT_ID = configuration.Configuration().read_merchant_info()


def update_account_relationship(account_id: str, provider_id: int) -> None:
  """Updates a business relationship."""

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

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

  # Creates the name of the relationship to update.
  # The name has the format: accounts/{account}/relationships/{provider}
  name = f"accounts/{account_id}/relationships/{provider_id}"

  # Creates an AccountRelationship with the updated fields.
  account_relationship = AccountRelationship()
  account_relationship.name = name
  account_relationship.account_id_alias = "alias"

  # Creates a field mask to specify which fields to update.
  field_mask = field_mask_pb2.FieldMask(paths=["account_id_alias"])

  # Creates the request.
  request = UpdateAccountRelationshipRequest(
      account_relationship=account_relationship,
      update_mask=field_mask,
  )

  # Makes the request and catches and prints any error messages.
  try:
    print("Sending Update AccountRelationship request")
    response = client.update_account_relationship(request=request)
    print("Updated AccountRelationship below")
    print(response)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  # The provider ID of the relationship to update.
  provider_id_ = 111
  update_account_relationship(_ACCOUNT_ID, provider_id_)