Merchant API code sample to create a sub account.

### 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.accounts.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.shopping.merchant.accounts.v1.Account;
    import com.google.shopping.merchant.accounts.v1.AccountAggregation;
    import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
    import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
    import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest;
    import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest.AddAccountService;
    import com.google.type.TimeZone;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /** This class demonstrates how to create a sub-account under an advanced account. */
    public class CreateSubAccountSample {

      private static String getParent(String accountId) {
        return String.format("accounts/%s", accountId);
      }

      public static Account createSubAccount(Config config) throws Exception {

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

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

        // Creates parent/provider to identify the advanced account into which to insert the subaccount.
        String parent = getParent(config.getAccountId().toString());

        // Calls the API and catches and prints any network failures/errors.
        try (AccountsServiceClient accountsServiceClient =
            AccountsServiceClient.create(accountsServiceSettings)) {

          CreateAndConfigureAccountRequest request =
              CreateAndConfigureAccountRequest.newBuilder()
                  .setAccount(
                      Account.newBuilder()
                          .setAccountName("Demo Business")
                          .setAdultContent(false)
                          .setTimeZone(TimeZone.newBuilder().setId("America/New_York").build())
                          .setLanguageCode("en-US")
                          .build())
                  .addService(
                      AddAccountService.newBuilder()
                          .setProvider(parent)
                          .setAccountAggregation(AccountAggregation.getDefaultInstance())
                          .build())
                  .build();

          System.out.println("Sending Create SubAccount request");
          Account response = accountsServiceClient.createAndConfigureAccount(request);
          System.out.println("Inserted Account Name below");
          // Format: `accounts/{account}`
          System.out.println(response.getName());
          return response;
        }
      }

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

        createSubAccount(config);
      }
    }

### 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\Account;
    use Google\Shopping\Merchant\Accounts\V1\AccountAggregation;
    use Google\Shopping\Merchant\Accounts\V1\Client\AccountsServiceClient;
    use Google\Shopping\Merchant\Accounts\V1\CreateAndConfigureAccountRequest;
    use Google\Shopping\Merchant\Accounts\V1\CreateAndConfigureAccountRequest\AddAccountService;
    use Google\Type\TimeZone;

    /**
     * This class demonstrates how to create a sub-account under an MCA account.
     */
    class CreateSubAccount
    {

        private static function getParent(string $accountId): string
        {
            return sprintf("accounts/%s", $accountId);
        }


        public static function createSubAccount(array $config): 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.
            $accountsServiceClient = new AccountsServiceClient($options);

            // Creates parent/provider to identify the MCA account into which to insert the subaccount.
            $parent = self::getParent($config['accountId']);

            // Calls the API and catches and prints any network failures/errors.
            try {
                $request = new CreateAndConfigureAccountRequest([
                    'account' => (new Account([
                        'account_name' => 'Demo Business',
                        'adult_content' => false,
                        'time_zone' => (new TimeZone(['id' => 'America/New_York'])),
                        'language_code' => 'en-US',
                    ])),
                    'service' => [
                        (new AddAccountService([
                            'provider' => $parent,
                            'account_aggregation' => new AccountAggregation,
                        ])),
                    ],
                ]);

                print "Sending Create SubAccount request\n";
                $response = $accountsServiceClient->createAndConfigureAccount($request);
                print "Inserted Account Name below\n";
                // Format: `accounts/{account}
                print $response->getName() . PHP_EOL;
            } catch (ApiException $e) {
                print $e->getMessage();
            }
        }
        public function callSample(): void
        {
            $config = Config::generateConfig();
            self::createSubAccount($config);
        }
    }

    $sample = new CreateSubAccount();
    $sample->callSample();

### 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 create and configure a sub-account under an advanced account."""


    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.shopping.merchant_accounts_v1 import Account
    from google.shopping.merchant_accounts_v1 import AccountAggregation
    from google.shopping.merchant_accounts_v1 import AccountsServiceClient
    from google.shopping.merchant_accounts_v1 import CreateAndConfigureAccountRequest


    def get_parent(account_id):
      return f"accounts/{account_id}"


    def create_sub_account(account_id: str) -> Account:
      """Creates a sub-account under an advanced account."""

      # Get OAuth credentials.
      credentials = generate_user_credentials.main()

      # Create a client.
      client = AccountsServiceClient(credentials=credentials)

      # Get the parent advanced account ID.
      parent = get_parent(account_id)

      # Create the request.
      request = CreateAndConfigureAccountRequest(
          account=Account(
              account_name="Demo Business",
              adult_content=False,
              time_zone={"id": "America/New_York"},
              language_code="en-US",
          ),
          service=[
              CreateAndConfigureAccountRequest.AddAccountService(
                  provider=parent,
                  account_aggregation=AccountAggregation(),
              )
          ],
      )

      # Make the request and print the response.
      try:
        print("Sending Create SubAccount request")
        response = client.create_and_configure_account(request=request)
        print("Inserted Account Name below")
        print(response.name)
        return response
      except RuntimeError as e:
        print(e)
        raise


    if __name__ == "__main__":
      _account_id = configuration.Configuration().read_merchant_info()
      create_sub_account(_account_id)