Add hotel Ad

Java
// Copyright 2018 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 com.google.ads.googleads.examples.hotelads;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v1.errors.GoogleAdsException;
import com.google.ads.googleads.v1.common.HotelAdInfo;
import com.google.ads.googleads.v1.common.PercentCpc;
import com.google.ads.googleads.v1.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v1.enums.AdGroupStatusEnum.AdGroupStatus;
import com.google.ads.googleads.v1.enums.AdGroupTypeEnum.AdGroupType;
import com.google.ads.googleads.v1.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v1.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod;
import com.google.ads.googleads.v1.enums.CampaignStatusEnum.CampaignStatus;
import com.google.ads.googleads.v1.errors.GoogleAdsError;
import com.google.ads.googleads.v1.resources.Ad;
import com.google.ads.googleads.v1.resources.AdGroup;
import com.google.ads.googleads.v1.resources.AdGroupAd;
import com.google.ads.googleads.v1.resources.Campaign;
import com.google.ads.googleads.v1.resources.Campaign.HotelSettingInfo;
import com.google.ads.googleads.v1.resources.Campaign.NetworkSettings;
import com.google.ads.googleads.v1.resources.CampaignBudget;
import com.google.ads.googleads.v1.services.AdGroupAdOperation;
import com.google.ads.googleads.v1.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v1.services.AdGroupOperation;
import com.google.ads.googleads.v1.services.AdGroupServiceClient;
import com.google.ads.googleads.v1.services.CampaignBudgetOperation;
import com.google.ads.googleads.v1.services.CampaignBudgetServiceClient;
import com.google.ads.googleads.v1.services.CampaignOperation;
import com.google.ads.googleads.v1.services.CampaignServiceClient;
import com.google.ads.googleads.v1.services.MutateAdGroupAdResult;
import com.google.ads.googleads.v1.services.MutateAdGroupResult;
import com.google.ads.googleads.v1.services.MutateCampaignBudgetsResponse;
import com.google.ads.googleads.v1.services.MutateCampaignResult;
import com.google.ads.googleads.v1.services.MutateCampaignsResponse;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.BoolValue;
import com.google.protobuf.Int64Value;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;

/**
 * Creates a hotel campaign, a hotel ad group and a hotel ad group ad.
 *
 * <p>Prerequisite: You need to have access to the Hotel Ads Center, which can be granted during
 * integration with Google Hotels. The integration instructions can be found at:
 * https://support.google.com/hotelprices/answer/6101897.
 */
public class AddHotelAd {

  private static class AddHotelAdParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.HOTEL_CENTER_ACCOUNT_ID, required = true)
    private Long hotelCenterAccountId;

    @Parameter(names = ArgumentNames.CPC_BID_CEILING_MICRO_AMOUNT)
    private Long cpcBidCeilingMicroAmount = 20_000_000L;
  }

  public static void main(String[] args) {
    AddHotelAdParams params = new AddHotelAdParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.hotelCenterAccountId = Long.parseLong("INSERT_HOTEL_CENTER_ACCOUNT_ID_HERE");
      params.cpcBidCeilingMicroAmount = Long.parseLong("INSERT_CPC_BID_CEILING_MICRO_AMOUNT_HERE");
    }

    GoogleAdsClient googleAdsClient;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      return;
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      return;
    }

    try {
      new AddHotelAd()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.hotelCenterAccountId,
              params.cpcBidCeilingMicroAmount);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param hotelCenterAccountId the Hotel Center account ID.
   * @param cpcBidCeilingMicroAmount the maximum bid limit that can be set when creating a campaign
   *     using the Percent CPC bidding strategy.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long hotelCenterAccountId,
      long cpcBidCeilingMicroAmount) {

    // Creates a budget to be used by the campaign that will be created below.
    String budgetResourceName = addCampaignBudget(googleAdsClient, customerId);

    // Creates a hotel campaign.
    String campaignResourceName =
        addHotelCampaign(
            googleAdsClient,
            customerId,
            budgetResourceName,
            hotelCenterAccountId,
            cpcBidCeilingMicroAmount);

    // Creates a hotel ad group.
    String adGroupResourceName = addHotelAdGroup(googleAdsClient, customerId, campaignResourceName);

    // Creates a hotel ad group ad.
    addHotelAdGroupAd(googleAdsClient, customerId, adGroupResourceName);
  }

  /**
   * Creates a new campaign budget in the specified client account.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @return resource name of the newly created budget.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String addCampaignBudget(GoogleAdsClient googleAdsClient, long customerId) {
    CampaignBudget budget =
        CampaignBudget.newBuilder()
            .setName(StringValue.of("Interplanetary Cruise Budget #" + System.currentTimeMillis()))
            .setDeliveryMethod(BudgetDeliveryMethod.STANDARD)
            .setAmountMicros(Int64Value.of(5_000_000))
            .build();

    CampaignBudgetOperation op = CampaignBudgetOperation.newBuilder().setCreate(budget).build();

    try (CampaignBudgetServiceClient campaignBudgetServiceClient =
        googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) {
      MutateCampaignBudgetsResponse response =
          campaignBudgetServiceClient.mutateCampaignBudgets(
              Long.toString(customerId), ImmutableList.of(op));
      String budgetResourceName = response.getResults(0).getResourceName();
      System.out.printf("Added a budget with resource name: '%s'%n", budgetResourceName);
      return budgetResourceName;
    }
  }

  /**
   * Creates a new hotel campaign in the specified client account.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param budgetResourceName the resource name of the budget for the campaign.
   * @param hotelCenterAccountId the Hotel Center account ID.
   * @param cpcBidCeilingMicroAmount the maximum bid limit that can be set when creating a campaign
   *     using the Percent CPC bidding strategy.
   * @return resource name of the newly created campaign.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String addHotelCampaign(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String budgetResourceName,
      long hotelCenterAccountId,
      long cpcBidCeilingMicroAmount) {

    // Configures the hotel settings.
    HotelSettingInfo hotelSettingInfo =
        HotelSettingInfo.newBuilder().setHotelCenterId(Int64Value.of(hotelCenterAccountId)).build();

    // Configures the campaign network options. Only Google Search is allowed for
    // hotel campaigns.
    NetworkSettings networkSettings =
        NetworkSettings.newBuilder().setTargetGoogleSearch(BoolValue.of(true)).build();

    // Creates the campaign.
    Campaign campaign =
        Campaign.newBuilder()
            .setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis()))
            // Configures settings related to hotel campaigns including advertising channel type
            // and hotel setting info.
            .setAdvertisingChannelType(AdvertisingChannelType.HOTEL)
            .setHotelSetting(hotelSettingInfo)
            // Recommendation: Sets the campaign to PAUSED when creating it to prevent
            // the ads from immediately serving. Set to ENABLED once you've added
            // targeting and the ads are ready to serve
            .setStatus(CampaignStatus.PAUSED)
            // Sets the bidding strategy to Percent CPC. Only Manual CPC and Percent CPC can be used
            // for hotel campaigns.
            .setPercentCpc(
                PercentCpc.newBuilder()
                    .setCpcBidCeilingMicros(Int64Value.of(cpcBidCeilingMicroAmount))
                    .build())
            // Sets the budget.
            .setCampaignBudget(StringValue.of(budgetResourceName))
            // Adds the networkSettings configured above.
            .setNetworkSettings(networkSettings)
            .build();

    // Creates a campaign operation.
    CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();

    // Issues a mutate request to add the campaign.
    try (CampaignServiceClient campaignServiceClient = googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
      MutateCampaignsResponse response =
          campaignServiceClient.mutateCampaigns(
              Long.toString(customerId), Collections.singletonList(operation));
      MutateCampaignResult result = response.getResults(0);
      System.out.printf(
          "Added a hotel campaign with resource name: '%s'%n", result.getResourceName());
      return result.getResourceName();
    }
  }

  /**
   * Creates a new hotel ad group in the specified campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignResourceName the resource name of the campaign that the new ad group will belong
   *     to.
   * @return resource name of the newly created ad group.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String addHotelAdGroup(
      GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
    // Creates an ad group.
    AdGroup adGroup =
        AdGroup.newBuilder()
            .setName(StringValue.of("Earth to Mars Cruises #" + System.currentTimeMillis()))
            .setCampaign(StringValue.of(campaignResourceName))
            // Sets the ad group type to HOTEL_ADS. This cannot be set to other types.
            .setType(AdGroupType.HOTEL_ADS)
            .setCpcBidMicros(Int64Value.of(1_000_000L))
            .setStatus(AdGroupStatus.ENABLED)
            .build();

    // Creates an ad group operation.
    AdGroupOperation operation = AdGroupOperation.newBuilder().setCreate(adGroup).build();

    // Issues a mutate request to add an ad group.
    try (AdGroupServiceClient adGroupServiceClient = googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
      MutateAdGroupResult mutateAdGroupResult =
          adGroupServiceClient
              .mutateAdGroups(Long.toString(customerId), Collections.singletonList(operation))
              .getResults(0);
      System.out.printf(
          "Added a hotel ad group with resource name: '%s'%n",
          mutateAdGroupResult.getResourceName());
      return mutateAdGroupResult.getResourceName();
    }
  }

  /**
   * Creates a new hotel ad group ad in the specified ad group.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupResourceName the resource name of the ad group that the new ad group ad will
   *     belong to.
   * @return resource name of the newly created ad group ad.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String addHotelAdGroupAd(
      GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
    // Creates a new hotel ad.
    Ad ad = Ad.newBuilder().setHotelAd(HotelAdInfo.newBuilder().build()).build();
    // Creates a new ad group ad and sets the hotel ad to it.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            // Sets the ad to the ad created above.
            .setAd(ad)
            .setStatus(AdGroupAdStatus.PAUSED)
            // Sets the ad group.
            .setAdGroup(StringValue.of(adGroupResourceName))
            .build();

    // Creates an ad group ad operation.
    AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    // Issues a mutate request to add an ad group ad.
    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      MutateAdGroupAdResult mutateAdGroupAdResult =
          adGroupAdServiceClient
              .mutateAdGroupAds(Long.toString(customerId), Collections.singletonList(operation))
              .getResults(0);
      System.out.printf(
          "Added a hotel ad group ad with resource name: '%s'%n",
          mutateAdGroupAdResult.getResourceName());
      return mutateAdGroupAdResult.getResourceName();
    }
  }
}
C#
// Copyright 2018 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.

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V1.Errors;
using Google.Ads.GoogleAds.V1.Common;
using Google.Ads.GoogleAds.V1.Resources;
using Google.Ads.GoogleAds.V1.Services;

using System;
using static Google.Ads.GoogleAds.V1.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.AdGroupStatusEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.AdGroupTypeEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V1.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V1.Resources.Campaign.Types;

namespace Google.Ads.GoogleAds.Examples.V1
{
    /// <summary>
    /// This code example creates a hotel campaign, a hotel ad group and hotel ad group ad.
    ///
    /// Prerequisite: You need to have access to the Hotel Ads Center, which can be granted during
    /// integration with Google Hotels. The integration instructions can be found at:
    /// https://support.google.com/hotelprices/answer/6101897.
    /// </summary>
    public class AddHotelAd : ExampleBase
    {
        // Specify maximum bid limit that can be set when creating a campaign using the Percent CPC
        // bidding strategy.
        private const long CPC_BID_CEILING_MICRO_AMOUNT = 20000000;

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            AddHotelAd codeExample = new AddHotelAd();
            Console.WriteLine(codeExample.Description);

            // The customer ID for which the call is made.
            int customerId = int.Parse("INSERT_CUSTOMER_ID_HERE");

            // Optional: Specify the maximum bid limit that can be set when creating a campaign
            // using the Percent CPC bidding strategy.
            long? cpcBidCeilingMicroAmount = CPC_BID_CEILING_MICRO_AMOUNT;

            long tempVal = 0;
            if (long.TryParse("INSERT_CPC_BID_CEILING_MICRO_AMOUNT", out tempVal))
            {
                cpcBidCeilingMicroAmount = tempVal;
            }

            // Specify your Hotels account ID below. You can see how to find the account ID in the
            // Hotel Ads Center at: https://support.google.com/hotelprices/answer/6399770.
            // This ID is the same account ID that you use in API requests to the Travel Partner
            // APIs (https://developers.google.com/hotels/hotel-ads/api-reference/).
            int hotelCenterAccountId = int.Parse("INSERT_HOTEL_CENTER_ACCOUNT_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId, hotelCenterAccountId,
                cpcBidCeilingMicroAmount.Value);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return " This code example creates a hotel campaign, a hotel ad group and " +
                    "hotel ad group ad. \n\n Prerequisite: You need to have access to the Hotel " +
                    "Ads Center, which can be granted during integration with Google Hotels. " +
                    "The integration instructions can be found at: " +
                    "https://support.google.com/hotelprices/answer/6101897.";
            }
        }

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The customer ID for which the call is made.</param>
        /// <param name="hotelCenterAccountId">The Hotel Center account ID.</param>
        /// <param name="cpcBidCeilingMicroAmount">The CPC bid ceiling micro amount.</param>
        public void Run(GoogleAdsClient client, long customerId, long hotelCenterAccountId,
            long cpcBidCeilingMicroAmount)
        {
            try
            {
                // Create a budget to be used by the campaign that will be created below.
                string budgetResourceName = AddCampaignBudget(client, customerId);

                // Create a hotel campaign.
                string campaignResourceName = AddHotelCampaign(client, customerId,
                    budgetResourceName, hotelCenterAccountId, cpcBidCeilingMicroAmount);

                // Create a hotel ad group.
                string adGroupResourceName = AddHotelAdGroup(client, customerId,
                    campaignResourceName);

                // Create a hotel ad group ad.
                AddHotelAdGroupAd(client, customerId, adGroupResourceName);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
            }
        }

        /// <summary>
        /// Creates a new campaign budget in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The resource name of the newly created budget.</returns>
        private static string AddCampaignBudget(GoogleAdsClient client, long customerId)
        {
            // Get the CampaignBudgetService.
            CampaignBudgetServiceClient service = client.GetService(
                Services.V1.CampaignBudgetService);

            // Create a campaign budget.
            CampaignBudget budget = new CampaignBudget()
            {
                Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                DeliveryMethod = BudgetDeliveryMethod.Standard,
                AmountMicros = 50000000
            };

            // Create a campaign budget operation.
            CampaignBudgetOperation campaignBudgetOperation = new CampaignBudgetOperation()
            {
                Create = budget
            };

            // Create the budget.
            MutateCampaignBudgetsResponse response = service.MutateCampaignBudgets(
                customerId.ToString(), new CampaignBudgetOperation[] { campaignBudgetOperation });

            string budgetResourceName = response.Results[0].ResourceName;
            Console.WriteLine($"Added a budget with resource name: '{budgetResourceName}'.");
            return budgetResourceName;
        }

        /// <summary>
        /// Creates a new hotel campaign in the specified client account.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The resource name of budget for a new campaign.
        /// </param>
        /// <param name="hotelCenterAccountId">The Hotel Center account ID.</param>
        /// <param name="cpcBidCeilingMicroAmount">The CPC bid ceiling micro amount.</param>
        /// <returns>The resource name of the newly created campaign.</returns>
        private static string AddHotelCampaign(GoogleAdsClient client, long customerId,
            string budgetResourceName, long hotelCenterAccountId, long cpcBidCeilingMicroAmount)
        {
            // Get the CampaignService.
            CampaignServiceClient service = client.GetService(Services.V1.CampaignService);

            // Create a campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Interplanetary Cruise Campaign #" + ExampleUtilities.GetRandomString(),

                // Configure settings related to hotel campaigns including advertising channel type
                // and hotel setting info.
                AdvertisingChannelType = AdvertisingChannelType.Hotel,
                HotelSetting = new HotelSettingInfo()
                {
                    HotelCenterId = hotelCenterAccountId
                },

                // Recommendation: Set the campaign to PAUSED when creating it to prevent
                // the ads from immediately serving. Set to ENABLED once you've added
                // targeting and the ads are ready to serve.
                Status = CampaignStatus.Paused,

                // Sets the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC can
                // be used for hotel campaigns.
                PercentCpc = new PercentCpc()
                {
                    CpcBidCeilingMicros = cpcBidCeilingMicroAmount
                },

                // Set the budget.
                CampaignBudget = budgetResourceName,

                // Configure the campaign network options. Only Google Search is allowed for
                // hotel campaigns.
                NetworkSettings = new NetworkSettings()
                {
                    TargetGoogleSearch = true
                }
            };

            // Create a campaign operation.
            CampaignOperation campaignOperation = new CampaignOperation()
            {
                Create = campaign
            };

            // Issue a mutate request to add campaigns.
            MutateCampaignsResponse response = service.MutateCampaigns(customerId.ToString(),
                new CampaignOperation[] { campaignOperation });

            return response.Results[0].ResourceName;
        }

        /// <summary>
        /// Adds the hotel ad group.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignResourceName">The resource name of campaign that a new ad group
        /// will belong to.</param>
        /// <returns>The resource name of the newly created ad group.</returns>
        private static string AddHotelAdGroup(GoogleAdsClient client, long customerId,
            string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient service = client.GetService(Services.V1.AdGroupService);

            // Create an ad group.
            AdGroup adGroup = new AdGroup()
            {
                Name = "Earth to Mars Cruise #" + ExampleUtilities.GetRandomString(),

                // Sets the campaign.
                Campaign = campaignResourceName,

                // Optional: Sets the ad group type to HOTEL_ADS.
                // This cannot be set to other types.
                Type = AdGroupType.HotelAds,

                CpcBidMicros = 10000000,
                Status = AdGroupStatus.Enabled
            };

            // Create an ad group operation.
            AdGroupOperation adGroupOperation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Issue a mutate request to add an ad group.
            MutateAdGroupsResponse response = service.MutateAdGroups(customerId.ToString(),
                new AdGroupOperation[] { adGroupOperation });
            return response.Results[0].ResourceName;
        }

        /// <summary>
        /// Creates a new hotel ad group ad in the specified ad group.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupResourceName">The resource name of ad group that a new ad group
        /// ad will belong to</param>
        private static void AddHotelAdGroupAd(GoogleAdsClient client, long customerId,
            string adGroupResourceName)
        {
            // Get the AdGroupAdService.
            AdGroupAdServiceClient service = client.GetService(Services.V1.AdGroupAdService);

            // Create a new ad group ad and sets the hotel ad to it.
            AdGroupAd adGroupAd = new AdGroupAd()
            {
                // Create a new hotel ad.
                Ad = new Ad()
                {
                    HotelAd = new HotelAdInfo(),
                },
                // Set the ad group.
                AdGroup = adGroupResourceName,
                Status = AdGroupAdStatus.Paused
            };

            // Create an ad group ad operation.
            AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation()
            {
                Create = adGroupAd
            };

            // Issue a mutate request to add an ad group ad.
            MutateAdGroupAdsResponse response = service.MutateAdGroupAds(customerId.ToString(),
                new AdGroupAdOperation[] { adGroupAdOperation });

            MutateAdGroupAdResult addedAdGroupAd = response.Results[0];
            Console.WriteLine($"Added a hotel ad group ad with resource name " +
                $"{addedAdGroupAd.ResourceName}.");
        }
    }
}
PHP
<?php
/**
 * Copyright 2018 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.
 */

namespace Google\Ads\GoogleAds\Examples\HotelAds;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V1\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\V1\Common\HotelAdInfo;
use Google\Ads\GoogleAds\V1\Common\PercentCpc;
use Google\Ads\GoogleAds\V1\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V1\Enums\AdGroupStatusEnum\AdGroupStatus;
use Google\Ads\GoogleAds\V1\Enums\AdGroupTypeEnum\AdGroupType;
use Google\Ads\GoogleAds\V1\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V1\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V1\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V1\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V1\Resources\Ad;
use Google\Ads\GoogleAds\V1\Resources\AdGroup;
use Google\Ads\GoogleAds\V1\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V1\Resources\Campaign;
use Google\Ads\GoogleAds\V1\Resources\Campaign\HotelSettingInfo;
use Google\Ads\GoogleAds\V1\Resources\Campaign\NetworkSettings;
use Google\Ads\GoogleAds\V1\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V1\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V1\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V1\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V1\Services\CampaignOperation;
use Google\ApiCore\ApiException;
use Google\Protobuf\BoolValue;
use Google\Protobuf\Int64Value;
use Google\Protobuf\StringValue;

/**
 * This example creates a hotel campaign, a hotel ad group and hotel ad group ad.
 *
 * <p> Prerequisite: You need to have an access to the Hotel Ads Center, which can be granted during
 * integration with Google Hotels. The integration instructions can be found at:
 * https://support.google.com/hotelprices/answer/6101897.
 */
class AddHotelAds
{
    const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Specify your Hotels account ID below. You can see how to find the account ID in the Hotel
    // Ads Center at: https://support.google.com/hotelprices/answer/6399770.
    // This ID is the same account ID that you use in API requests to the Travel Partner APIs
    // (https://developers.google.com/hotels/hotel-ads/api-reference/).
    const HOTEL_CENTER_ACCOUNT_ID = 'INSERT_HOTEL_CENTER_ACCOUNT_ID_HERE';
    // Specify maximum bid limit that can be set when creating a campaign using the Percent CPC
    // bidding strategy.
    const CPC_BID_CEILING_MICRO_AMOUNT = 20000000;

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::HOTEL_CENTER_ACCOUNT_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CPC_BID_CEILING_MICRO_AMOUNT => GetOpt::OPTIONAL_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::HOTEL_CENTER_ACCOUNT_ID] ?: self::HOTEL_CENTER_ACCOUNT_ID,
                $options[ArgumentNames::CPC_BID_CEILING_MICRO_AMOUNT]
                    ?: self::CPC_BID_CEILING_MICRO_AMOUNT
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID without hyphens
     * @param int $hotelCenterAccountId the Hotel Center account ID
     * @param int $cpcBidCeilingMicroAmount the CPC bid ceiling micro amount
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $hotelCenterAccountId,
        $cpcBidCeilingMicroAmount
    ) {
        // Creates a budget to be used by the campaign that will be created below.
        $budgetResourceName = self::addCampaignBudget($googleAdsClient, $customerId);
        // Creates a hotel campaign.
        $campaignResourceName = self::addHotelCampaign(
            $googleAdsClient,
            $customerId,
            $budgetResourceName,
            $hotelCenterAccountId,
            $cpcBidCeilingMicroAmount
        );
        // Creates a hotel ad group.
        $adGroupResourceName =
            self::addHotelAdGroup($googleAdsClient, $customerId, $campaignResourceName);
        // Creates a hotel ad group ad.
        self::addHotelAdGroupAd($googleAdsClient, $customerId, $adGroupResourceName);
    }

    /**
     * Creates a new campaign budget in the specified client account.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @return string the resource name of the newly created budget
     */
    private static function addCampaignBudget(GoogleAdsClient $googleAdsClient, $customerId)
    {
        // Creates a campaign budget.
        $budget = new CampaignBudget([
            'name' => new StringValue(['value' => 'Interplanetary Cruise Budget #' . uniqid()]),
            'delivery_method' => BudgetDeliveryMethod::STANDARD,
            // Sets the amount of budget.
            'amount_micros' => new Int64Value(['value' => 50000000]),
            // Makes the budget explicitly shared.
            'explicitly_shared' => new BoolValue(['value' => true])
        ]);

        // Creates a campaign budget operation.
        $campaignBudgetOperation = new CampaignBudgetOperation();
        $campaignBudgetOperation->setCreate($budget);

        // Issues a mutate request.
        $campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
        $response = $campaignBudgetServiceClient->mutateCampaignBudgets(
            $customerId,
            [$campaignBudgetOperation]
        );

        /** @var CampaignBudget $addedBudget */
        $addedBudget = $response->getResults()[0];
        printf(
            "Added a budget with resource name '%s'.%s",
            $addedBudget->getResourceName(),
            PHP_EOL
        );

        return $addedBudget->getResourceName();
    }

    /**
     * Creates a new hotel campaign in the specified client account.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $budgetResourceName the resource name of budget for a new campaign
     * @param int $hotelCenterAccountId the Hotel Center account ID
     * @param int $cpcBidCeilingMicroAmount the CPC bid ceiling micro amount
     * @return string the resource name of the newly created campaign
     */
    private static function addHotelCampaign(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $budgetResourceName,
        $hotelCenterAccountId,
        $cpcBidCeilingMicroAmount
    ) {
        // Creates a campaign.
        $campaign = new Campaign([
            'name' => new StringValue(['value' => 'Interplanetary Cruise Campaign #' . uniqid()]),
            // Configures settings related to hotel campaigns including advertising channel type
            // and hotel setting info.
            'advertising_channel_type' => AdvertisingChannelType::HOTEL,
            'hotel_setting' => new HotelSettingInfo([
                'hotel_center_id' => new Int64Value(['value' => $hotelCenterAccountId])
            ]),
            // Recommendation: Set the campaign to PAUSED when creating it to prevent
            // the ads from immediately serving. Set to ENABLED once you've added
            // targeting and the ads are ready to serve.
            'status' => CampaignStatus::PAUSED,
            // Sets the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC can be used
            // for hotel campaigns.
            'percent_cpc' => new PercentCpc([
                'cpc_bid_ceiling_micros' => new Int64Value(['value' => $cpcBidCeilingMicroAmount])
            ]),
            // Sets the budget.
            'campaign_budget' => new StringValue(['value' => $budgetResourceName]),
            // Configures the campaign network options. Only Google Search is allowed for
            // hotel campaigns.
            'network_settings' => new NetworkSettings([
                'target_google_search' => new BoolValue(['value' => true]),
            ]),
        ]);

        // Creates a campaign operation.
        $campaignOperation = new CampaignOperation();
        $campaignOperation->setCreate($campaign);

        // Issues a mutate request to add campaigns.
        $campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
        $response = $campaignServiceClient->mutateCampaigns($customerId, [$campaignOperation]);

        /** @var Campaign $addedCampaign */
        $addedCampaign = $response->getResults()[0];
        printf(
            "Added a hotel campaign with resource name '%s'.%s",
            $addedCampaign->getResourceName(),
            PHP_EOL
        );

        return $addedCampaign->getResourceName();
    }

    /**
     * Creates a new hotel ad group in the specified campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $campaignResourceName the resource name of campaign that a new ad group will
     *     belong to
     * @return string the resource name of the newly created ad group
     */
    private static function addHotelAdGroup(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $campaignResourceName
    ) {
        // Creates an ad group.
        $adGroup = new AdGroup([
            'name' => new StringValue(['value' => 'Earth to Mars Cruise #' . uniqid()]),
            // Sets the campaign.
            'campaign' => new StringValue(['value' => $campaignResourceName]),
            // Sets the ad group type to HOTEL_ADS.
            // This cannot be set to other types.
            'type' => AdGroupType::HOTEL_ADS,
            'cpc_bid_micros' => new Int64Value(['value' => 10000000]),
            'status' => AdGroupStatus::ENABLED,
        ]);

        // Creates an ad group operation.
        $adGroupOperation = new AdGroupOperation();
        $adGroupOperation->setCreate($adGroup);

        // Issues a mutate request to add an ad group.
        $adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
        $response = $adGroupServiceClient->mutateAdGroups($customerId, [$adGroupOperation]);

        /** @var AdGroup $addedAdGroup */
        $addedAdGroup = $response->getResults()[0];
        printf(
            "Added a hotel ad group with resource name '%s'.%s",
            $addedAdGroup->getResourceName(),
            PHP_EOL
        );

        return $addedAdGroup->getResourceName();
    }

    /**
     * Creates a new hotel ad group ad in the specified ad group.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $adGroupResourceName the resource name of ad group that a new ad group ad will
     *     belong to
     */
    private static function addHotelAdGroupAd(
        GoogleAdsClient $googleAdsClient,
        $customerId,
        $adGroupResourceName
    ) {
        // Creates a new hotel ad.
        $ad = new Ad([
            'hotel_ad' => new HotelAdInfo(),
        ]);

        // Creates a new ad group ad and sets the hotel ad to it.
        $adGroupAd = new AdGroupAd([
            'ad' => $ad,
            'status' => AdGroupAdStatus::PAUSED,
            // Sets the ad group.
            'ad_group' => new StringValue(['value' => $adGroupResourceName])
        ]);

        // Creates an ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);

        // Issues a mutate request to add an ad group ad.
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
        $response = $adGroupAdServiceClient->mutateAdGroupAds($customerId, [$adGroupAdOperation]);

        /** @var AdGroupAd $addedAdGroupAd */
        $addedAdGroupAd = $response->getResults()[0];
        printf(
            "Added a hotel ad group ad with resource name '%s'.%s",
            $addedAdGroupAd->getResourceName(),
            PHP_EOL
        );
    }
}

AddHotelAds::main();
Python
#!/usr/bin/env python
# Copyright 2018 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.
"""This example adds a hotel campaign, ad group, and ad group ad.

Prerequisite: You need to have access to the Hotel Ads Center, which can be
granted during integration with Google Hotels. The integration instructions can
be found at:
https://support.google.com/hotelprices/answer/6101897.
"""

from __future__ import absolute_import

import argparse
import six
import sys
import uuid

import google.ads.google_ads.client


def main(client, customer_id, hotel_center_account_id,
         bid_ceiling_micro_amount):
    # Add budget
    budget_resource_name = add_budget(client, customer_id)

    # Add hotel campaign
    campaign_resource_name = add_hotel_campaign(
        client, customer_id, budget_resource_name, hotel_center_account_id,
        bid_ceiling_micro_amount)

    # Add hotel ad group
    ad_group_resource_name = add_hotel_ad_group(client, customer_id,
                                                campaign_resource_name)

    # Add hotel ad
    add_hotel_ad(client, customer_id, ad_group_resource_name)


def add_budget(client, customer_id):
    campaign_budget_service = client.get_service('CampaignBudgetService',
                                                 version='v1')

    # Create a budget, which can be shared by multiple campaigns.
    campaign_budget_operation = client.get_type('CampaignBudgetOperation',
                                                version='v1')
    campaign_budget = campaign_budget_operation.create
    campaign_budget.name.value = 'Interplanetary Budget %s' % uuid.uuid4()
    campaign_budget.delivery_method = client.get_type(
        'BudgetDeliveryMethodEnum').STANDARD
    campaign_budget.amount_micros.value = 500000

    # Add budget.
    try:
        campaign_budget_response = (
            campaign_budget_service.mutate_campaign_budgets(
                customer_id, [campaign_budget_operation]))
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    budget_resource_name = campaign_budget_response.results[0].resource_name

    print('Created budget %s' % budget_resource_name)

    return budget_resource_name


def add_hotel_ad(client, customer_id, ad_group_resource_name):
    ad_group_ad_service = client.get_service('AdGroupAdService', version='v1')

    # Creates a new ad group ad and sets the hotel ad to it.
    ad_group_ad_operation = client.get_type('AdGroupAdOperation', version='v1')
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group.value = ad_group_resource_name
    ad_group_ad.status = client.get_type('AdGroupAdStatusEnum',
                                         version='v1').PAUSED
    ad_group_ad.ad.hotel_ad.CopyFrom(client.get_type('HotelAdInfo',
                                                     version='v1'))

    # Add the ad group ad.
    try:
        ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
            customer_id, [ad_group_ad_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    ad_group_ad_resource_name = ad_group_ad_response.results[0].resource_name

    print('Created hotel ad %s.' % ad_group_ad_resource_name)

    return ad_group_resource_name


def add_hotel_ad_group(client, customer_id, campaign_resource_name):
    ad_group_service = client.get_service('AdGroupService', version='v1')

    # Create ad group.
    ad_group_operation = client.get_type('AdGroupOperation', version='v1')
    ad_group = ad_group_operation.create
    ad_group.name.value = 'Earth to Mars cruise %s' % uuid.uuid4()
    ad_group.status = client.get_type('AdGroupStatusEnum', version='v1').ENABLED
    ad_group.campaign.value = campaign_resource_name
    # Sets the ad group type to HOTEL_ADS. This cannot be set to other types.
    ad_group.type = client.get_type('AdGroupTypeEnum', version='v1').HOTEL_ADS
    ad_group.cpc_bid_micros.value = 10000000

    # Add the ad group.
    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    ad_group_resource_name = ad_group_response.results[0].resource_name

    print('Added a hotel ad group with resource name "%s".'
          % ad_group_resource_name)

    return ad_group_resource_name


def add_hotel_campaign(client, customer_id, budget_resource_name,
                       hotel_center_account_id, bid_ceiling_micro_amount):
    campaign_service = client.get_service('CampaignService', version='v1')

    # Create campaign.
    campaign_operation = client.get_type('CampaignOperation', version='v1')
    campaign = campaign_operation.create
    campaign.name.value = 'Interplanetary Cruise Campaign %s' % uuid.uuid4()

    # Configures settings related to hotel campaigns including advertising
    # channel type and hotel setting info.
    campaign.advertising_channel_type = client.get_type(
        'AdvertisingChannelTypeEnum').HOTEL
    campaign.hotel_setting.hotel_center_id.value = hotel_center_account_id

    # Recommendation: Set the campaign to PAUSED when creating it to prevent the
    # ads from immediately serving. Set to ENABLED once you've added targeting
    # and the ads are ready to serve.
    campaign.status = client.get_type('CampaignStatusEnum', version='v1').PAUSED

    # Set the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC
    # can be used for hotel campaigns.
    campaign.percent_cpc.cpc_bid_ceiling_micros.value = (
        bid_ceiling_micro_amount)

    # Sets the budget.
    campaign.campaign_budget.value = budget_resource_name

    # Set the campaign network options. Only Google Search is allowed for hotel
    # campaigns.
    campaign.network_settings.target_google_search.value = True

    # Add the campaign.
    try:
        campaign_response = campaign_service.mutate_campaigns(
            customer_id, [campaign_operation])
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print('Request with ID "%s" failed with status "%s" and includes the '
              'following errors:' % (ex.request_id, ex.error.code().name))
        for error in ex.failure.errors:
            print('\tError with message "%s".' % error.message)
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print('\t\tOn field: %s' % field_path_element.field_name)
        sys.exit(1)

    campaign_resource_name = campaign_response.results[0].resource_name

    print('Added a hotel campaign with resource name "%s".'
          % campaign_resource_name)

    return campaign_resource_name


if __name__ == '__main__':
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    google_ads_client = (google.ads.google_ads.client.GoogleAdsClient
                         .load_from_storage())

    parser = argparse.ArgumentParser(
        description=('Adds an expanded text ad to the specified ad group ID, '
                     'for the given customer ID.'))
    # The following argument(s) should be provided to run the example.
    parser.add_argument('-c', '--customer_id', type=six.text_type,
                        required=True, help='The Google Ads customer ID.')
    parser.add_argument('-b', '--bid_ceiling_micro_amount', type=int,
                        required=True, help=('The bid ceiling micro amount for '
                                             'the hotel campaign.'))
    parser.add_argument('-h', '--hotel_center_account_id', type=six.text_type,
                        required=True, help='The hotel center account ID.')
    args = parser.parse_args()

    main(google_ads_client, args.customer_id, args.hotel_center_account_id,
         args.bid_ceiling_micro_amount)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2018 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.
#
# This example creates a hotel campaign, a hotel ad group, and a hotel ad group
# ad.
#
# Prerequisite: You need to have access to the Hotel Ads Center, which can be
# granted during integration with Google Hotels. The integration instructions
# can be found at:
# https://support.google.com/hotelprices/answer/6101897

require 'optparse'
require 'google/ads/google_ads'
require 'date'

def add_hotel_ads(customer_id, hotel_center_account_id,
    cpc_bid_ceiling_micro_amount)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Create a budget to be used by the campaign that will be created below.
  budget_resource = add_campaign_budget(client, customer_id)

  # Create a hotel campaign.
  campaign_resource = add_hotel_campaign(client, customer_id, budget_resource,
      hotel_center_account_id, cpc_bid_ceiling_micro_amount)

  # Create a hotel ad group.
  ad_group_resource = add_hotel_ad_group(client, customer_id, campaign_resource)

  # Create a hotel ad group ad.
  add_hotel_ad_group_ad(client, customer_id, ad_group_resource)
end

# Creates a new campaign budget in the specified client account.
def add_campaign_budget(client, customer_id)
  # Create the budget and set relevant fields.
  budget = client.resource(:CampaignBudget)
  budget.name = generate_random_name_field(client,
      'Interplanetary Cruise Budget')
  budget.delivery_method = client.enum(:BudgetDeliveryMethod)::STANDARD
  budget.amount_micros = client.wrapper.int64(50_000_000)

  # Create the budget operation.
  campaign_budget_operation = client.operation(:CampaignBudget)
  campaign_budget_operation['create'] = budget

  # Issue a mutate request.
  campaign_budget_service = client.service(:CampaignBudget)
  response = campaign_budget_service.mutate_campaign_budgets(customer_id,
      [campaign_budget_operation])

  # Fetch the new budget's resource name.
  budget_resource = response.results.first.resource_name

  puts sprintf('Added budget with resource name "%s".', budget_resource)

  return budget_resource
end

# Creates a new campaign in the specified client account.
def add_hotel_campaign(client, customer_id, budget_resource,
    hotel_center_account_id, cpc_bid_ceiling_micro_amount)
  # Create a campaign.
  campaign = client.resource(:Campaign)
  campaign.name = generate_random_name_field(client,
      'Interplanetary Cruise Campaign')

  # Configure settings related to hotel campaigns.
  campaign.advertising_channel_type =
      client.enum(:AdvertisingChannelType)::HOTEL
  hotel_setting_info = client.resource(:HotelSettingInfo)
  hotel_setting_info.hotel_center_id =
      client.wrapper.int64(hotel_center_account_id)
  campaign.hotel_setting = hotel_setting_info

  # Recommendation: Set the campaign to PAUSED when creating it to prevent the
  # ads from immediately serving. Set to ENABLED once you've added targeting and
  # the ads are ready to serve.
  campaign.status = client.enum(:CampaignStatus)::PAUSED

  # Set the bidding strategy to PercentCpc. Only Manual CPC and Percent CPC can
  # be used for hotel campaigns.
  campaign.percent_cpc = client.resource(:PercentCpc)
  campaign.percent_cpc.cpc_bid_ceiling_micros =
      client.wrapper.int64(cpc_bid_ceiling_micro_amount)

  # Set the budget.
  campaign.campaign_budget = client.wrapper.string(budget_resource)

  # Configures the campaign network options. Only Google Search is allowed for
  # hotel campaigns.
  network_settings = client.resource(:NetworkSettings)
  network_settings.target_google_search = client.wrapper.bool(true)
  campaign.network_settings = network_settings

  # Create a campaign operation.
  campaign_operation = client.operation(:Campaign)
  campaign_operation['create'] = campaign

  # Issue a mutate request to add the campaign.
  campaign_service = client.service(:Campaign)
  response = campaign_service.mutate_campaigns(customer_id,
      [campaign_operation])

  # Fetch the new campaign's resource name.
  campaign_resource = response.results.first.resource_name

  puts sprintf('Added hotel campaign with resource name "%s".',
      campaign_resource)

  return campaign_resource
end

# Creates a new hotel ad group in the specified campaign.
def add_hotel_ad_group(client, customer_id, campaign_resource)
  # Create an ad group.
  ad_group = client.resource(:AdGroup)
  ad_group.name = generate_random_name_field(client,
      'Earth to Mars Cruise')

  # Set the campaign.
  ad_group.campaign = client.wrapper.string(campaign_resource)

  # Optional: Set the ad group type to HOTEL_ADS.
  # This cannot be set to other types.
  ad_group.type = client.enum(:AdGroupType)::HOTEL_ADS
  ad_group.cpc_bid_micros = client.wrapper.int64(10_000_000)
  ad_group.status = client.enum(:AdGroupStatus)::ENABLED

  # Create an ad group operation.
  ad_group_operation = client.operation(:AdGroup)
  ad_group_operation['create'] = ad_group

  # Issue a mutate request to add the ad group.
  ad_group_service = client.service(:AdGroup)
  response = ad_group_service.mutate_ad_groups(customer_id,
      [ad_group_operation])

  # Fetch the new ad group's resource name.
  ad_group_resource = response.results.first.resource_name

  puts sprintf('Added hotel ad group with resource name "%s".',
      ad_group_resource)

  return ad_group_resource
end

# Creates a new hotel ad group ad in the specified ad group.
def add_hotel_ad_group_ad(client, customer_id, ad_group_resource)
  # Create a new hotel ad.
  ad = client.resource(:Ad)
  ad.hotel_ad = client.resource(:HotelAdInfo)

  # Create a new ad group ad and sets the hotel ad to it.
  ad_group_ad = client.resource(:AdGroupAd)
  ad_group_ad.ad = ad
  ad_group_ad.status = client.enum(:AdGroupAdStatus)::PAUSED

  # Set the ad group.
  ad_group_ad.ad_group = client.wrapper.string(ad_group_resource)

  # Create an ad group ad operation.
  ad_group_ad_operation = client.operation(:AdGroupAd)
  ad_group_ad_operation['create'] = ad_group_ad

  # Issue a mutate request to add the ad group ad.
  ad_group_ad_service = client.service(:AdGroupAd)
  response = ad_group_ad_service.mutate_ad_group_ads(customer_id,
      [ad_group_ad_operation])

  # Fetch the new ad group ad's resource name.
  ad_group_ad_resource = response.results.first.resource_name

  puts sprintf('Added hotel ad group ad with resource name "%s".',
      ad_group_ad_resource)
end

# Appends a random number to the provided description text and returns it as a
# string-wrapped value
def generate_random_name_field(client, text)
  random_number = (Time.new.to_f * 100).to_i
  formatted_name = sprintf('%s #%s', text, random_number)
  client.wrapper.string(formatted_name)
end

if __FILE__ == $0
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:hotel_center_account_id] = 'INSERT_HOTEL_CENTER_ACCOUNT_ID_HERE'
  options[:cpc_bid_ceiling_micro_amount] = 20_000_000

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))
    opts.separator ''
    opts.separator 'Options:'
    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-H', '--hotel-center-account-id HOTEL-CENTER-ACCOUNT-ID', Integer,
        'Hotel Center Account ID') do |v|
      options[:hotel_center_account_id] = v
    end

    opts.on('-B', '--cpc-bid-ceiling-micro-amount CPC-BID-CEILING-MICRO_AMOUNT',
        Integer, 'CPC Bid Ceiling Micro Amount') do |v|
      options[:cpc_bid_ceiling_micro_amount] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_hotel_ads(options.fetch(:customer_id).tr("-", ""), options[:hotel_center_account_id],
        options[:cpc_bid_ceiling_micro_amount])
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
  rescue Google::Gax::RetryError => e
    STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \
        "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code,
                  e.cause.details, e.cause.metadata['request-id'])
  end
end

Send feedback about...

Google Ads API
Google Ads API
Need help? Visit our support page.