Merchant API code sample to insert shipping settings.

### 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.shippingsettings.v1;
    import com.google.api.gax.core.FixedCredentialsProvider;
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.shopping.merchant.accounts.v1.DeliveryTime;
    import com.google.shopping.merchant.accounts.v1.InsertShippingSettingsRequest;
    import com.google.shopping.merchant.accounts.v1.RateGroup;
    import com.google.shopping.merchant.accounts.v1.Service;
    import com.google.shopping.merchant.accounts.v1.Service.ShipmentType;
    import com.google.shopping.merchant.accounts.v1.ShippingSettings;
    import com.google.shopping.merchant.accounts.v1.ShippingSettingsServiceClient;
    import com.google.shopping.merchant.accounts.v1.ShippingSettingsServiceSettings;
    import com.google.shopping.merchant.accounts.v1.Value;
    import com.google.shopping.type.Price;
    import shopping.merchant.samples.utils.Authenticator;
    import shopping.merchant.samples.utils.Config;

    /** This class demonstrates how to insert a ShippingSettings for a Merchant Center account. */
    public class InsertShippingSettingsSample {

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

      public static void insertShippingSettings(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.
        ShippingSettingsServiceSettings shippingSettingsServiceSettings =
            ShippingSettingsServiceSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credential))
                .build();

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

        // Calls the API and catches and prints any network failures/errors.
        try (ShippingSettingsServiceClient shippingSettingsServiceClient =
            ShippingSettingsServiceClient.create(shippingSettingsServiceSettings)) {

          InsertShippingSettingsRequest request =
              InsertShippingSettingsRequest.newBuilder()
                  .setParent(parent)
                  .setShippingSetting(
                      ShippingSettings.newBuilder()
                          // Etag needs to be an empty string on initial insert
                          // On future inserts, call GET first to get the Etag
                          // Then use the retrieved Etag on future inserts.
                          // NOTE THAT ON THE INITIAL INSERT, YOUR SHIPPING SETTINGS WILL
                          // NOT BE STORED, YOU HAVE TO CALL INSERT AGAIN WITH YOUR
                          // RETRIEVED ETAG.
                          // .setEtag("")
                          .setEtag("PPa=")
                          .addServices(
                              Service.newBuilder()
                                  .setServiceName("Canadian Postal Service")
                                  .setActive(true)
                                  .addDeliveryCountries("CA")
                                  .setCurrencyCode("CAD")
                                  .setDeliveryTime(
                                      DeliveryTime.newBuilder()
                                          .setMinTransitDays(0)
                                          .setMaxTransitDays(3)
                                          .setMinHandlingDays(0)
                                          .setMaxHandlingDays(3)
                                          .build())
                                  .addRateGroups(
                                      RateGroup.newBuilder()
                                          .addApplicableShippingLabels("Oversized")
                                          .addApplicableShippingLabels("Perishable")
                                          .setSingleValue(Value.newBuilder().setPricePercentage("5.4"))
                                          .setName("Oversized and Perishable items")
                                          .build())
                                  .setShipmentType(ShipmentType.DELIVERY)
                                  .setMinimumOrderValue(
                                      Price.newBuilder()
                                          .setAmountMicros(10000000)
                                          .setCurrencyCode("CAD")
                                          .build())
                                  .build())
                          .build())
                  .build();

          System.out.println("Sending insert ShippingSettings request");
          ShippingSettings response = shippingSettingsServiceClient.insertShippingSettings(request);
          System.out.println("Inserted ShippingSettings Name below");
          System.out.println(response.getName());
          // You can apply ShippingSettings to specific products by using the `shippingLabel` field
          // on the product.
        } catch (Exception e) {
          System.out.println(e);
        }
      }

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

        insertShippingSettings(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\Client\ShippingSettingsServiceClient;
    use Google\Shopping\Merchant\Accounts\V1\DeliveryTime;
    use Google\Shopping\Merchant\Accounts\V1\InsertShippingSettingsRequest;
    use Google\Shopping\Merchant\Accounts\V1\RateGroup;
    use Google\Shopping\Merchant\Accounts\V1\Service;
    use Google\Shopping\Merchant\Accounts\V1\Service\ShipmentType;
    use Google\Shopping\Merchant\Accounts\V1\ShippingSettings;
    use Google\Shopping\Merchant\Accounts\V1\Value;
    use Google\Shopping\Type\Price;

    /**
     * This class demonstrates how to insert a ShippingSettings for a Merchant Center account.
     */
    class InsertShippingSettings
    {
        /**
         * A helper function to create the parent string.
         *
         * @param string $accountId The account ID.
         * @return string The parent in the format "accounts/{accountId}".
         */
        private static function getParent(string $accountId): string
        {
            return sprintf("accounts/%s", $accountId);
        }

        /**
         * Inserts shipping settings for the specified Merchant Center account.
         *
         * @param array $config The configuration data containing the account ID.
         * @return void
         */
        public static function insertShippingSettings($config)
        {
            // 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.
            $shippingSettingsServiceClient = new ShippingSettingsServiceClient($options);

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

            // Calls the API and catches and prints any network failures/errors.
            try {
                $request = (new InsertShippingSettingsRequest())
                    ->setParent($parent)
                    ->setShippingSetting(
                        (new ShippingSettings())
                            // Etag needs to be an empty string on initial insert
                            // On future inserts, call GET first to get the Etag
                            // Then use the retrieved Etag on future inserts.
                            // NOTE THAT ON THE INITIAL INSERT, YOUR SHIPPING SETTINGS WILL
                            // NOT BE STORED, YOU HAVE TO CALL INSERT AGAIN WITH YOUR
                            // RETRIEVED ETAG.
                            ->setEtag("")
                            ->setServices([
                                (new Service())
                                    ->setServiceName("Canadian Postal Service")
                                    ->setActive(true)
                                    ->setDeliveryCountries(["CA"])
                                    ->setCurrencyCode("CAD")
                                    ->setDeliveryTime(
                                        (new DeliveryTime())
                                            ->setMinTransitDays(0)
                                            ->setMaxTransitDays(3)
                                            ->setMinHandlingDays(0)
                                            ->setMaxHandlingDays(3)
                                    )
                                    ->setRateGroups(
                                        [(new RateGroup())
                                            ->setApplicableShippingLabels(["Oversized","Perishable"])
                                            ->setSingleValue((new Value())->setPricePercentage("5.4"))
                                            ->setName("Oversized and Perishable items")]
                                    )
                                    ->setShipmentType(ShipmentType::DELIVERY)
                                    ->setMinimumOrderValue(
                                        (new Price())
                                            ->setAmountMicros(10000000)
                                            ->setCurrencyCode("CAD")
                                    )
                            ])
                    );

                print "Sending insert ShippingSettings request" . PHP_EOL;
                $response = $shippingSettingsServiceClient->insertShippingSettings($request);
                print "Inserted ShippingSettings below" . PHP_EOL;
                print_r($response);
                // You can apply ShippingSettings to specific products by using the `shippingLabel` field
                // on the product.
            } catch (ApiException $e) {
                print $e->getMessage();
            }
        }

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

            // Makes the call to insert shipping settings for the MC account.
            self::insertShippingSettings($config);
        }
    }

    // Run the script
    $sample = new InsertShippingSettings();
    $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 insert a ShippingSettings for a given Merchant Center account."""

    from examples.authentication import configuration
    from examples.authentication import generate_user_credentials
    from google.shopping.merchant_accounts_v1 import DeliveryTime
    from google.shopping.merchant_accounts_v1 import InsertShippingSettingsRequest
    from google.shopping.merchant_accounts_v1 import RateGroup
    from google.shopping.merchant_accounts_v1 import Service
    from google.shopping.merchant_accounts_v1 import ShippingSettings
    from google.shopping.merchant_accounts_v1 import ShippingSettingsServiceClient
    from google.shopping.merchant_accounts_v1 import Value

    _ACCOUNT = configuration.Configuration().read_merchant_info()
    _PARENT = f"accounts/{_ACCOUNT}"


    def insert_shipping_settings():
      """Inserts a ShippingSettings for a Merchant Center account."""

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

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

      # Creates the request.
      request = InsertShippingSettingsRequest(
          parent=_PARENT,
          shipping_setting=ShippingSettings(
              # Etag needs to be an empty string on initial insert
              # On future inserts, call GET first to get the Etag
              # Then use the retrieved Etag on future inserts.
              # NOTE THAT ON THE INITIAL INSERT, YOUR SHIPPING SETTINGS WILL
              # NOT BE STORED, YOU HAVE TO CALL INSERT AGAIN WITH YOUR
              # RETRIEVED ETAG.
              etag="",
              services=[
                  Service(
                      service_name="Canadian Postal Service",
                      active=True,
                      delivery_countries=["CA"],
                      currency_code="CAD",
                      delivery_time=DeliveryTime(
                          min_transit_days=0,
                          max_transit_days=3,
                          min_handling_days=0,
                          max_handling_days=3,
                      ),
                      rate_groups=[
                          RateGroup(
                              applicable_shipping_labels=[
                                  "Oversized",
                                  "Perishable",
                              ],
                              single_value=Value(price_percentage="5.4"),
                              name="Oversized and Perishable items",
                          )
                      ],
                      shipment_type=Service.ShipmentType.DELIVERY,
                      minimum_order_value={
                          "amount_micros": 10000000,
                          "currency_code": "CAD",
                      },
                  )
              ],
          ),
      )

      # Makes the request and prints the inserted ShippingSettings name.
      try:
        response = client.insert_shipping_settings(request=request)
        print("Inserted ShippingSettings below")
        print(response)
        # You can apply ShippingSettings to specific products by using the
        # `shippingLabel` field on the product.
      except RuntimeError as e:
        print(e)


    if __name__ == "__main__":
      insert_shipping_settings()