Crear región

Ejemplo de código de la API de Merchant para crear una región

// 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.regions.v1beta;
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1beta.CreateRegionRequest;
import com.google.shopping.merchant.accounts.v1beta.Region;
import com.google.shopping.merchant.accounts.v1beta.Region.PostalCodeArea;
import com.google.shopping.merchant.accounts.v1beta.Region.PostalCodeArea.PostalCodeRange;
import com.google.shopping.merchant.accounts.v1beta.RegionsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.RegionsServiceSettings;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;

/** This class demonstrates how to create a region for a Merchant Center account. */
public class CreateRegionSample {

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

  public static void createRegion(Config config, String regionId) throws Exception {

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

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

    // Creates parent to identify where to insert the region.
    String parent = getParent(config.getAccountId().toString());

    // Calls the API and catches and prints any network failures/errors.
    try (RegionsServiceClient regionsServiceClient =
        RegionsServiceClient.create(regionsServiceSettings)) {

      CreateRegionRequest request =
          CreateRegionRequest.newBuilder()
              .setParent(parent)
              .setRegionId(regionId)
              .setRegion(
                  Region.newBuilder()
                      .setDisplayName("New York")
                      .setPostalCodeArea(
                          PostalCodeArea.newBuilder()
                              .setRegionCode("US")
                              .addPostalCodes(
                                  PostalCodeRange.newBuilder()
                                      .setBegin("10001")
                                      .setEnd("10282")
                                      .build())
                              .build())
                      .build())
              .build();

      System.out.println("Sending Create Region request");
      Region response = regionsServiceClient.createRegion(request);
      System.out.println("Inserted Region Name below");
      // The last part of the region name will be the ID of the region.
      // Format: `accounts/{account}/region/{region}`
      System.out.println(response.getName());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    // The unique ID of this region.
    String regionId = "123456AB";

    createRegion(config, regionId);
  }
}
<?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\V1beta\Client\RegionsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\CreateRegionRequest;
use Google\Shopping\Merchant\Accounts\V1beta\Region;
use Google\Shopping\Merchant\Accounts\V1beta\Region\PostalCodeArea;
use Google\Shopping\Merchant\Accounts\V1beta\Region\PostalCodeArea\PostalCodeRange;


/**
 * This class demonstrates how to create a region for a Merchant Center account.
 */
class CreateRegionSample
{
    private static function getParent(string $accountId): string
    {
        return sprintf("accounts/%s", $accountId);
    }


    public static function createRegionSample(array $config, string $regionId): 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.
        $regionsServiceClient = new RegionsServiceClient($options);

        // Creates parent to identify where to insert the region.
        $parent = self::getParent($config['accountId']);

        try {
            // Creates the request.
            $request = new CreateRegionRequest([
                'parent' => $parent,
                'region_id' => $regionId,
                'region' => (new Region([
                    'display_name' => 'New York',
                    'postal_code_area' => (new PostalCodeArea([
                        'region_code' => 'US',
                        'postal_codes' => [
                            (new PostalCodeRange([
                                'begin' => '10001',
                                'end' => '10282'
                            ]))
                        ]
                    ]))
                ]))
            ]);

            print "Sending Create Region request\n";
            $response = $regionsServiceClient->createRegion($request);
            print "Inserted Region Name below\n";
            print $response->getName() . "\n";

        } catch (ApiException $e) {
            print $e->getMessage();
        }
    }

    public function callSample(): void
    {
        $config = Config::generateConfig();
        // Replace this with the ID of the region to be created.
        $regionId = "[INSERT REGION ID HERE]";
        self::createRegionSample($config, $regionId);
    }
}

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

# -*- 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 a Region."""

from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1beta import CreateRegionRequest
from google.shopping.merchant_accounts_v1beta import Region
from google.shopping.merchant_accounts_v1beta import RegionsServiceClient

_ACCOUNT = configuration.Configuration().read_merchant_info()


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


def create_region(region_id_to_create):
  """Creates a region for a Merchant Center account."""

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

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

  # Creates parent to identify where to insert the region.
  parent = get_parent(_ACCOUNT)

  # Creates the request.
  request = CreateRegionRequest(
      parent=parent,
      region_id=region_id_to_create,
      region=Region(
          display_name="New York",
          postal_code_area=Region.PostalCodeArea(
              region_code="US",
              postal_codes=[
                  Region.PostalCodeArea.PostalCodeRange(
                      begin="10001", end="10282"
                  )
              ],
          ),
      ),
  )

  # Makes the request and catches and prints any error messages.
  try:
    response = client.create_region(request=request)
    print("Inserted Region Name below")
    print(response.name)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  # The unique ID of this region.
  region_id = "123456AB"
  create_region(region_id)