Add hotel callout extension

Java

// Copyright 2019 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.extensions;

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.v4.common.HotelCalloutFeedItem;
import com.google.ads.googleads.v4.enums.ExtensionTypeEnum.ExtensionType;
import com.google.ads.googleads.v4.errors.GoogleAdsError;
import com.google.ads.googleads.v4.errors.GoogleAdsException;
import com.google.ads.googleads.v4.resources.AdGroupExtensionSetting;
import com.google.ads.googleads.v4.resources.CampaignExtensionSetting;
import com.google.ads.googleads.v4.resources.CustomerExtensionSetting;
import com.google.ads.googleads.v4.resources.ExtensionFeedItem;
import com.google.ads.googleads.v4.services.AdGroupExtensionSettingOperation;
import com.google.ads.googleads.v4.services.AdGroupExtensionSettingServiceClient;
import com.google.ads.googleads.v4.services.CampaignExtensionSettingOperation;
import com.google.ads.googleads.v4.services.CampaignExtensionSettingServiceClient;
import com.google.ads.googleads.v4.services.CustomerExtensionSettingOperation;
import com.google.ads.googleads.v4.services.CustomerExtensionSettingServiceClient;
import com.google.ads.googleads.v4.services.ExtensionFeedItemOperation;
import com.google.ads.googleads.v4.services.ExtensionFeedItemServiceClient;
import com.google.ads.googleads.v4.services.MutateAdGroupExtensionSettingsResponse;
import com.google.ads.googleads.v4.services.MutateCampaignExtensionSettingsResponse;
import com.google.ads.googleads.v4.services.MutateCustomerExtensionSettingsResponse;
import com.google.ads.googleads.v4.services.MutateExtensionFeedItemsResponse;
import com.google.ads.googleads.v4.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import com.google.protobuf.StringValue;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Adds a hotel callout extension to a specific account, campaign within the account, and ad group
 * within the campaign.
 */
public class AddHotelCallout {

  private static class AddHotelCalloutParams extends CodeSampleParams {
    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;

    @Parameter(names = ArgumentNames.CALLOUT_TEXT, required = true)
    private String calloutText;

    // See supported languages at:
    // https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.
    @Parameter(names = ArgumentNames.LANGUAGE_CODE, required = true)
    private String languageCode;
  }

  public static void main(String[] args) {
    AddHotelCalloutParams params = new AddHotelCalloutParams();
    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.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
      params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
      params.calloutText = "INSERT_CALLOUT_TEXT_HERE";
      params.languageCode = "INSERT_LANGUAGE_CODE_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 AddHotelCallout()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.campaignId,
              params.adGroupId,
              params.calloutText,
              params.languageCode);
    } 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. */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long campaignId,
      long adGroupId,
      String calloutText,
      String languageCode) {
    // Creates the extension feed item.
    String extensionFeedItemResourceName =
        addExtensionFeedItem(googleAdsClient, customerId, calloutText, languageCode);

    // Adds the extension feed item to the account.
    addExtensionToAccount(googleAdsClient, customerId, extensionFeedItemResourceName);

    // Adds the extension feed item to the campaign.
    addExtensionToCampaign(googleAdsClient, customerId, campaignId, extensionFeedItemResourceName);

    // Adds the extension feed item to the ad group.
    addExtensionToAdGroup(googleAdsClient, customerId, adGroupId, extensionFeedItemResourceName);
  }

  /** Creates a new extension feed item for the callout. */
  private String addExtensionFeedItem(
      GoogleAdsClient googleAdsClient, long customerId, String calloutText, String languageCode) {
    // Creates the callout with text and language of choice.
    HotelCalloutFeedItem hotelCallout =
        HotelCalloutFeedItem.newBuilder()
            .setText(StringValue.of(calloutText))
            .setLanguageCode(StringValue.of(languageCode))
            .build();

    // Attaches the callout to a feed item.
    ExtensionFeedItem feedItem =
        ExtensionFeedItem.newBuilder().setHotelCalloutFeedItem(hotelCallout).build();

    // Creates the feed item operation.
    ExtensionFeedItemOperation feedItemOperation =
        ExtensionFeedItemOperation.newBuilder().setCreate(feedItem).build();

    // Issues the create request to create the feed item.
    try (ExtensionFeedItemServiceClient extensionFeedItemServiceClient =
        googleAdsClient.getLatestVersion().createExtensionFeedItemServiceClient()) {
      MutateExtensionFeedItemsResponse response =
          extensionFeedItemServiceClient.mutateExtensionFeedItems(
              Long.toString(customerId), ImmutableList.of(feedItemOperation));
      String extensionFeedItemResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Added a extension feed item with resource name: '%s'.%n", extensionFeedItemResourceName);
      return extensionFeedItemResourceName;
    }
  }

  /** Adds extension feed item to the account. */
  private void addExtensionToAccount(
      GoogleAdsClient googleAdsClient, long customerId, String extensionFeedItemResourceName) {
    // Creates the customer extension setting, sets it to HOTEL_CALLOUT, and attaches the feed item.
    CustomerExtensionSetting customerExtensionSetting =
        CustomerExtensionSetting.newBuilder()
            .setExtensionType(ExtensionType.HOTEL_CALLOUT)
            .addExtensionFeedItems(StringValue.of(extensionFeedItemResourceName))
            .build();

    // Creates the customer extension setting operation.
    CustomerExtensionSettingOperation op =
        CustomerExtensionSettingOperation.newBuilder().setCreate(customerExtensionSetting).build();

    // Issues the create request to add the callout.
    try (CustomerExtensionSettingServiceClient customerExtensionServiceClient =
        googleAdsClient.getLatestVersion().createCustomerExtensionSettingServiceClient()) {
      MutateCustomerExtensionSettingsResponse response =
          customerExtensionServiceClient.mutateCustomerExtensionSettings(
              Long.toString(customerId), ImmutableList.of(op));

      String customerExtensionResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Added a account extension with resource name: '%s'.%n", customerExtensionResourceName);
    }
  }

  /** Adds the extension feed item to the Campaign. */
  private void addExtensionToCampaign(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long campaignId,
      String extensionFeedItemResourceName) {
    String campaignResourceName = ResourceNames.campaign(customerId, campaignId);

    // Creates the campaign extension setting, sets it to HOTEL_CALLOUT, and attaches the feed item.
    CampaignExtensionSetting campaignExtensionSetting =
        CampaignExtensionSetting.newBuilder()
            .setExtensionType(ExtensionType.HOTEL_CALLOUT)
            .setCampaign(StringValue.of(campaignResourceName))
            .addExtensionFeedItems(StringValue.of(extensionFeedItemResourceName))
            .build();

    // Creates the campaign extension setting operation.
    CampaignExtensionSettingOperation op =
        CampaignExtensionSettingOperation.newBuilder().setCreate(campaignExtensionSetting).build();

    // Issues the create request to add the callout.
    try (CampaignExtensionSettingServiceClient campaignExtensionServiceClient =
        googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) {
      MutateCampaignExtensionSettingsResponse response =
          campaignExtensionServiceClient.mutateCampaignExtensionSettings(
              Long.toString(customerId), ImmutableList.of(op));

      String campaignExtensionResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Added a campaign extension with resource name: '%s'.%n", campaignExtensionResourceName);
    }
  }

  /** Adds the extension feed item to the ad group. */
  private void addExtensionToAdGroup(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long adGroupId,
      String extensionFeedItemResourceName) {
    String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

    // Creates the ad group extension setting, sets it to HOTEL_CALLOUT, and attaches the feed item.
    AdGroupExtensionSetting adGroupExtensionSetting =
        AdGroupExtensionSetting.newBuilder()
            .setExtensionType(ExtensionType.HOTEL_CALLOUT)
            .setAdGroup(StringValue.of(adGroupResourceName))
            .addExtensionFeedItems(StringValue.of(extensionFeedItemResourceName))
            .build();

    // Creates the ad group extension setting operation.
    AdGroupExtensionSettingOperation op =
        AdGroupExtensionSettingOperation.newBuilder().setCreate(adGroupExtensionSetting).build();

    // Issues the create request to add the callout.
    try (AdGroupExtensionSettingServiceClient adGroupExtensionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupExtensionSettingServiceClient()) {
      MutateAdGroupExtensionSettingsResponse response =
          adGroupExtensionServiceClient.mutateAdGroupExtensionSettings(
              Long.toString(customerId), ImmutableList.of(op));

      String adGroupExtensionResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Added an ad group extension with resource name: '%s'.%n", adGroupExtensionResourceName);
    }
  }
}

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, 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.
#
# This example adds a hotel callout extension to a specific account, campaign
# within the account, and ad group within the campaign.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V4::Resources::ExtensionFeedItem;
use Google::Ads::GoogleAds::V4::Resources::CampaignExtensionSetting;
use Google::Ads::GoogleAds::V4::Resources::AdGroupExtensionSetting;
use Google::Ads::GoogleAds::V4::Resources::CustomerExtensionSetting;
use Google::Ads::GoogleAds::V4::Common::HotelCalloutFeedItem;
use Google::Ads::GoogleAds::V4::Enums::ExtensionTypeEnum qw(HOTEL_CALLOUT);
use
  Google::Ads::GoogleAds::V4::Services::ExtensionFeedItemService::ExtensionFeedItemOperation;
use
  Google::Ads::GoogleAds::V4::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation;
use
  Google::Ads::GoogleAds::V4::Services::AdGroupExtensionSettingService::AdGroupExtensionSettingOperation;
use
  Google::Ads::GoogleAds::V4::Services::CustomerExtensionSettingService::CustomerExtensionSettingOperation;
use Google::Ads::GoogleAds::V4::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

# 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.
my $customer_id  = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id  = "INSERT_CAMPAIGN_ID_HERE";
my $ad_group_id  = "INSERT_AD_GROUP_ID_HERE";
my $callout_text = "INSERT_CALLOUT_TEXT_HERE";
# See supported languages at:
# https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.
my $language_code = "INSERT_LANGUAGE_CODE_HERE";

sub add_hotel_callout {
  my (
    $api_client,  $customer_id,  $campaign_id,
    $ad_group_id, $callout_text, $language_code
  ) = @_;

  # Create an extension feed item as hotel callout.
  my $extension_feed_item_resource_name =
    add_extension_feed_item($api_client, $customer_id, $callout_text,
    $language_code);

  # Add the extension feed item to the account.
  add_extension_to_account($api_client, $customer_id,
    $extension_feed_item_resource_name);

  # Add the extension feed item to the campaign.
  add_extension_to_campaign($api_client, $customer_id, $campaign_id,
    $extension_feed_item_resource_name);

  # Add the extension feed item to the ad group.
  add_extension_to_ad_group($api_client, $customer_id, $ad_group_id,
    $extension_feed_item_resource_name);

  return 1;
}

# Creates a new extension feed item for the callout extension.
sub add_extension_feed_item {
  my ($api_client, $customer_id, $callout_text, $language_code) = @_;

  # Create the callout feed item with text and language of choice.
  my $hotel_callout_feed_item =
    Google::Ads::GoogleAds::V4::Common::HotelCalloutFeedItem->new({
      text         => $callout_text,
      languageCode => $language_code
    });

  # Create a feed item from the hotel callout extension.
  my $extension_feed_item =
    Google::Ads::GoogleAds::V4::Resources::ExtensionFeedItem->new({
      hotelCalloutFeedItem => $hotel_callout_feed_item
    });

  # Create an extension feed item operation.
  my $extension_feed_item_operation =
    Google::Ads::GoogleAds::V4::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
    ->new({
      create => $extension_feed_item
    });

  # Issue a mutate request to add the extension feed item.
  my $extension_feed_item_response =
    $api_client->ExtensionFeedItemService()->mutate({
      customerId => $customer_id,
      operations => [$extension_feed_item_operation]});

  # Print out some information about the added extension feed item.
  my $extension_feed_item_resource_name =
    $extension_feed_item_response->{results}[0]{resourceName};
  printf "Created an extension feed item with resource name: '%s'.\n",
    $extension_feed_item_resource_name;

  return $extension_feed_item_resource_name;
}

# Adds the extension feed item to the customer account.
sub add_extension_to_account {
  my ($api_client, $customer_id, $extension_feed_item_resource_name) = @_;

  # Create a customer extension setting, set its type to HOTEL_CALLOUT, and
  # attache the feed item.
  my $customer_extension_setting =
    Google::Ads::GoogleAds::V4::Resources::CustomerExtensionSetting->new({
      extensionType      => HOTEL_CALLOUT,
      extensionFeedItems => [$extension_feed_item_resource_name]});

  # Create a customer extension setting operation.
  my $customer_extension_setting_operation =
    Google::Ads::GoogleAds::V4::Services::CustomerExtensionSettingService::CustomerExtensionSettingOperation
    ->new({
      create => $customer_extension_setting
    });

  # Issue a mutate request to add the customer extension setting.
  my $customer_extension_setting_response =
    $api_client->CustomerExtensionSettingService()->mutate({
      customerId => $customer_id,
      operations => [$customer_extension_setting_operation]});

  # Print out some information about the added customer extension setting.
  my $customer_extension_setting_resource_name =
    $customer_extension_setting_response->{results}[0]{resourceName};
  printf "Created a customer extension setting with resource name: '%s'.\n",
    $customer_extension_setting_resource_name;
}

# Adds the extension feed item to the specified campaign.
sub add_extension_to_campaign {
  my ($api_client, $customer_id, $campaign_id,
    $extension_feed_item_resource_name)
    = @_;

  # Create a campaign extension setting, set its type to HOTEL_CALLOUT, and
  # attache the feed item.
  my $campaign_extension_setting =
    Google::Ads::GoogleAds::V4::Resources::CampaignExtensionSetting->new({
      extensionType => HOTEL_CALLOUT,
      campaign => Google::Ads::GoogleAds::V4::Utils::ResourceNames::campaign(
        $customer_id, $campaign_id
      ),
      extensionFeedItems => [$extension_feed_item_resource_name]});

  # Create a campaign extension setting operation.
  my $campaign_extension_setting_operation =
    Google::Ads::GoogleAds::V4::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation
    ->new({
      create => $campaign_extension_setting
    });

  # Issue a mutate request to add the campaign extension setting.
  my $campaign_extension_setting_response =
    $api_client->CampaignExtensionSettingService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_extension_setting_operation]});

  # Print out some information about the added campaign extension setting.
  my $campaign_extension_setting_resource_name =
    $campaign_extension_setting_response->{results}[0]{resourceName};
  printf "Created a campaign extension setting with resource name: '%s'.\n",
    $campaign_extension_setting_resource_name;
}

# Adds the extension feed item to the specified ad group.
sub add_extension_to_ad_group {
  my ($api_client, $customer_id, $ad_group_id,
    $extension_feed_item_resource_name)
    = @_;

  # Create an ad group extension setting, set its type to HOTEL_CALLOUT, and
  # attache the feed item.
  my $ad_group_extension_setting =
    Google::Ads::GoogleAds::V4::Resources::AdGroupExtensionSetting->new({
      extensionType => HOTEL_CALLOUT,
      adGroup => Google::Ads::GoogleAds::V4::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      extensionFeedItems => [$extension_feed_item_resource_name]});

  # Create an ad group extension setting operation.
  my $ad_group_extension_setting_operation =
    Google::Ads::GoogleAds::V4::Services::AdGroupExtensionSettingService::AdGroupExtensionSettingOperation
    ->new({
      create => $ad_group_extension_setting
    });

  # Issue a mutate request to add the ad group extension setting.
  my $ad_group_extension_setting_response =
    $api_client->AdGroupExtensionSettingService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_extension_setting_operation]});

  # Print out some information about the added ad group extension setting.
  my $ad_group_extension_setting_resource_name =
    $ad_group_extension_setting_response->{results}[0]{resourceName};
  printf "Created an ad group extension setting with resource name: '%s'.\n",
    $ad_group_extension_setting_resource_name;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"   => \$customer_id,
  "campaign_id=i"   => \$campaign_id,
  "ad_group_id=i"   => \$ad_group_id,
  "callout_text=s"  => \$callout_text,
  "language_code=s" => \$language_code
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
  if not check_params($customer_id, $campaign_id, $ad_group_id, $callout_text,
  $language_code);

# Call the example.
add_hotel_callout($api_client, $customer_id =~ s/-//gr,
  $campaign_id, $ad_group_id, $callout_text, $language_code);

=pod

=head1 NAME

add_hotel_callout

=head1 DESCRIPTION

This example adds a hotel callout extension to a specific account, campaign
within the account, and ad group within the campaign.

=head1 SYNOPSIS

add_hotel_callout.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -campaign_id                The campaign ID.
    -ad_group_id                The ad group ID.
    -callout_text               The hotel callout text.
    -language_code              The hotel callout language code, e.g. specify 'en' for English.

=cut