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.v6.common.HotelCalloutFeedItem;
import com.google.ads.googleads.v6.enums.ExtensionTypeEnum.ExtensionType;
import com.google.ads.googleads.v6.errors.GoogleAdsError;
import com.google.ads.googleads.v6.errors.GoogleAdsException;
import com.google.ads.googleads.v6.resources.AdGroupExtensionSetting;
import com.google.ads.googleads.v6.resources.CampaignExtensionSetting;
import com.google.ads.googleads.v6.resources.CustomerExtensionSetting;
import com.google.ads.googleads.v6.resources.ExtensionFeedItem;
import com.google.ads.googleads.v6.services.AdGroupExtensionSettingOperation;
import com.google.ads.googleads.v6.services.AdGroupExtensionSettingServiceClient;
import com.google.ads.googleads.v6.services.CampaignExtensionSettingOperation;
import com.google.ads.googleads.v6.services.CampaignExtensionSettingServiceClient;
import com.google.ads.googleads.v6.services.CustomerExtensionSettingOperation;
import com.google.ads.googleads.v6.services.CustomerExtensionSettingServiceClient;
import com.google.ads.googleads.v6.services.ExtensionFeedItemOperation;
import com.google.ads.googleads.v6.services.ExtensionFeedItemServiceClient;
import com.google.ads.googleads.v6.services.MutateAdGroupExtensionSettingsResponse;
import com.google.ads.googleads.v6.services.MutateCampaignExtensionSettingsResponse;
import com.google.ads.googleads.v6.services.MutateCustomerExtensionSettingsResponse;
import com.google.ads.googleads.v6.services.MutateExtensionFeedItemsResponse;
import com.google.ads.googleads.v6.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
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 = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
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);
}
System.exit(1);
}
}
/** 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(calloutText)
.setLanguageCode(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(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(campaignResourceName)
.addExtensionFeedItems(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(adGroupResourceName)
.addExtensionFeedItems(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);
}
}
}
C#
// Copyright 2020 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 System;
using System.Linq;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V6.Common;
using Google.Ads.GoogleAds.V6.Errors;
using Google.Ads.GoogleAds.V6.Resources;
using Google.Ads.GoogleAds.V6.Services;
using static Google.Ads.GoogleAds.V6.Enums.ExtensionTypeEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V6
{
/// <summary>
/// This example adds a hotel callout extension to a specific account, campaign within the
/// account, and ad group within the campaign.
/// </summary>
public class AddHotelCallout : ExampleBase
{
/// <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)
{
AddHotelCallout codeExample = new AddHotelCallout();
Console.WriteLine(codeExample.Description);
// The customer ID for which the call is made.
int customerId = int.Parse("INSERT_CUSTOMER_ID_HERE");
// ID of the campaign to which the hotel callout extension will be added.
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
// ID of the ad group to which the hotel callout extension will be added.
long adGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE");
// Callout text for the extension.
string calloutText = "INSERT_CALLOUT_TEXT_HERE";
// The language code for the text. See supported languages at:
// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.
string languageCode = "INSERT_LANGUAGE_CODE_HERE";
codeExample.Run(new GoogleAdsClient(), customerId, campaignId, adGroupId,
calloutText, languageCode);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This example adds a hotel callout extension to a specific account, campaign within " +
"the account, and ad group within the campaign.";
/// <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="campaignId">ID of the campaign to which the hotel callout extension will be
/// added.</param>
/// <param name="adGroupId">ID of the ad group to which the hotel callout extension will be
/// added.</param>
/// <param name="calloutText">Callout text for the extension.</param>
/// <param name="languageCode">The language code for the text. See supported languages at:
/// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.</param>
public void Run(GoogleAdsClient client, long customerId, long campaignId, long adGroupId,
string calloutText, string languageCode)
{
try
{
// Creates an extension feed item as hotel callout.
string extensionFeedItemResourceName = AddExtensionFeedItem(client, customerId,
calloutText, languageCode);
// Adds the extension feed item to the account.
AddExtensionToAccount(client, customerId, extensionFeedItemResourceName);
// Adds the extension feed item to the campaign.
AddExtensionToCampaign(client, customerId, campaignId,
extensionFeedItemResourceName);
// Adds the extension feed item to the ad group.
AddExtensionToAdGroup(client, customerId, adGroupId, extensionFeedItemResourceName);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Creates a new extension feed item for the callout extension.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The client customer ID.</param>
/// <param name="calloutText">Callout text for the extension.</param>
/// <param name="languageCode">The language code for the text.</param>
/// <returns>The created extension feed item's resource name.</returns>
private string AddExtensionFeedItem(GoogleAdsClient client, in long customerId,
string calloutText, string languageCode)
{
// Gets the ExtensionFeedItemService client.
ExtensionFeedItemServiceClient extensionFeedItemService =
client.GetService(Services.V6.ExtensionFeedItemService);
// Creates the callout extension with the specified text and language.
HotelCalloutFeedItem hotelCalloutFeedItem = new HotelCalloutFeedItem
{
Text = calloutText,
LanguageCode = languageCode
};
// Creates a feed item from the hotel callout extension.
ExtensionFeedItem extensionFeedItem = new ExtensionFeedItem
{
HotelCalloutFeedItem = hotelCalloutFeedItem
};
// Creates an extension feed item operation.
ExtensionFeedItemOperation extensionFeedItemOperation = new ExtensionFeedItemOperation
{
Create = extensionFeedItem
};
// Issues a mutate request to add the extension feed item and print its information.
MutateExtensionFeedItemsResponse response =
extensionFeedItemService.MutateExtensionFeedItems(customerId.ToString(),
new[] {extensionFeedItemOperation});
string extensionFeedItemResourceName = response.Results.First().ResourceName;
Console.WriteLine("Created an extension feed item with resource name " +
$"'{extensionFeedItemResourceName}'.");
return extensionFeedItemResourceName;
}
/// <summary>
/// Adds the extension feed item to the customer account.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The client customer ID.</param>
/// <param name="extensionFeedItemResourceName">The extension feed item's resource
/// name.</param>
private void AddExtensionToAccount(GoogleAdsClient client, in long customerId,
string extensionFeedItemResourceName)
{
// Gets the CustomerExtensionSettingService client.
CustomerExtensionSettingServiceClient customerExtensionSettingService =
client.GetService(Services.V6.CustomerExtensionSettingService);
// Creates a customer extension setting, sets its type to HOTEL_CALLOUT, and attaches
// the feed item.
CustomerExtensionSetting customerExtensionSetting = new CustomerExtensionSetting
{
ExtensionType = ExtensionType.HotelCallout,
};
customerExtensionSetting.ExtensionFeedItems.Add(extensionFeedItemResourceName);
// Creates a customer extension setting operation.
CustomerExtensionSettingOperation customerExtensionSettingOperation =
new CustomerExtensionSettingOperation
{
Create = customerExtensionSetting
};
// Issues a mutate request to add the customer extension setting and prints its
// information.
MutateCustomerExtensionSettingsResponse response =
customerExtensionSettingService.MutateCustomerExtensionSettings(
customerId.ToString(), new[] {customerExtensionSettingOperation});
Console.WriteLine("Created a customer extension setting with resource name " +
$"'{response.Results.First().ResourceName}'");
}
/// <summary>
/// Adds the extension feed item to the specified campaign.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The client customer ID.</param>
/// <param name="campaignId">The campaign ID to which to add the extension.</param>
/// <param name="extensionFeedItemResourceName">The extension feed item's resource
/// name.</param>
private void AddExtensionToCampaign(GoogleAdsClient client, in long customerId,
in long campaignId, string extensionFeedItemResourceName)
{
// Gets the CampaignExtensionSettingService client.
CampaignExtensionSettingServiceClient campaignExtensionSettingService =
client.GetService(Services.V6.CampaignExtensionSettingService);
// Creates a campaign extension setting, sets its type to HOTEL_CALLOUT, and attaches
// the feed item.
CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting
{
Campaign = ResourceNames.Campaign(customerId, campaignId),
ExtensionType = ExtensionType.HotelCallout
};
campaignExtensionSetting.ExtensionFeedItems.Add(extensionFeedItemResourceName);
// Creates a campaign extension setting operation.
CampaignExtensionSettingOperation campaignExtensionSettingOperation =
new CampaignExtensionSettingOperation
{
Create = campaignExtensionSetting
};
// Issues a mutate request to add the campaign extension setting and prints its
// information.
MutateCampaignExtensionSettingsResponse response =
campaignExtensionSettingService.MutateCampaignExtensionSettings(
customerId.ToString(), new[] {campaignExtensionSettingOperation});
Console.WriteLine("Created a campaign extension setting with resource name " +
$"'{response.Results.First().ResourceName}'");
}
/// <summary>
/// Adds the extension feed item to the specified ad group.
/// </summary>
/// <param name="client">The Google Ads API client.</param>
/// <param name="customerId">The client customer ID.</param>
/// <param name="adGroupId">The ad group ID to which to add the extension.</param>
/// <param name="extensionFeedItemResourceName">The extension feed item's resource
/// name.</param>
private void AddExtensionToAdGroup(GoogleAdsClient client, in long customerId,
in long adGroupId, string extensionFeedItemResourceName)
{
// Gets the AdGroupExtensionSettingService client.
AdGroupExtensionSettingServiceClient adGroupExtensionSettingService =
client.GetService(Services.V6.AdGroupExtensionSettingService);
// Creates an ad group extension setting, sets its type to HOTEL_CALLOUT, and attaches
// the feed item.
AdGroupExtensionSetting adGroupExtensionSetting = new AdGroupExtensionSetting
{
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
ExtensionType = ExtensionType.HotelCallout
};
adGroupExtensionSetting.ExtensionFeedItems.Add(extensionFeedItemResourceName);
// Creates an ad group extension setting operation.
AdGroupExtensionSettingOperation adGroupExtensionSettingOperation =
new AdGroupExtensionSettingOperation
{
Create = adGroupExtensionSetting
};
// Issues a mutate request to add the ad group extension setting and prints its
// information.
MutateAdGroupExtensionSettingsResponse response =
adGroupExtensionSettingService.MutateAdGroupExtensionSettings(
customerId.ToString(), new[] {adGroupExtensionSettingOperation});
Console.WriteLine("Created an ad group extension setting with resource name " +
$"'{response.Results.First().ResourceName}'");
}
}
}
PHP
<?php
/**
* Copyright 2020 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\Extensions;
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\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V6\ResourceNames;
use Google\Ads\GoogleAds\V6\Common\HotelCalloutFeedItem;
use Google\Ads\GoogleAds\V6\Enums\ExtensionTypeEnum\ExtensionType;
use Google\Ads\GoogleAds\V6\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V6\Resources\AdGroupExtensionSetting;
use Google\Ads\GoogleAds\V6\Resources\CampaignExtensionSetting;
use Google\Ads\GoogleAds\V6\Resources\CustomerExtensionSetting;
use Google\Ads\GoogleAds\V6\Resources\ExtensionFeedItem;
use Google\Ads\GoogleAds\V6\Services\AdGroupExtensionSettingOperation;
use Google\Ads\GoogleAds\V6\Services\CampaignExtensionSettingOperation;
use Google\Ads\GoogleAds\V6\Services\CustomerExtensionSettingOperation;
use Google\Ads\GoogleAds\V6\Services\ExtensionFeedItemOperation;
use Google\ApiCore\ApiException;
/**
* This example adds a hotel callout extension to a specific account, campaign within the account,
* and ad group within the campaign.
*/
class AddHotelCallout
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
private const CALLOUT_TEXT = 'INSERT_CALLOUT_TEXT_HERE';
// See supported languages at:
// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.
private const LANGUAGE_CODE = 'INSERT_LANGUAGE_CODE_HERE';
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::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
ArgumentNames::AD_GROUP_ID => GetOpt::REQUIRED_ARGUMENT,
ArgumentNames::CALLOUT_TEXT => GetOpt::REQUIRED_ARGUMENT,
ArgumentNames::LANGUAGE_CODE => GetOpt::REQUIRED_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::CAMPAIGN_ID] ?: self::CAMPAIGN_ID,
$options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_ID,
$options[ArgumentNames::CALLOUT_TEXT] ?: self::CALLOUT_TEXT,
$options[ArgumentNames::LANGUAGE_CODE] ?: self::LANGUAGE_CODE
);
} 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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
* @param int $adGroupId the ad group ID
* @param string $calloutText the callout text
* @param string $languageCode the language code
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
int $adGroupId,
string $calloutText,
string $languageCode
) {
// Creates an extension feed item as hotel callout.
$extensionFeedItemResourceName =
self::addExtensionFeedItem($googleAdsClient, $customerId, $calloutText, $languageCode);
// Adds the extension feed item to the account.
self::addExtensionToAccount($googleAdsClient, $customerId, $extensionFeedItemResourceName);
// Adds the extension feed item to the campaign.
self::addExtensionToCampaign(
$googleAdsClient,
$customerId,
$campaignId,
$extensionFeedItemResourceName
);
// Adds the extension feed item to the ad group.
self::addExtensionToAdGroup(
$googleAdsClient,
$customerId,
$adGroupId,
$extensionFeedItemResourceName
);
}
/**
* Creates a new extension feed item for the callout extension.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param string $calloutText the callout text to be created
* @param string $languageCode the language code for the callout text
* @return string the created extension feed item's resource name
*/
private static function addExtensionFeedItem(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $calloutText,
string $languageCode
): string {
// Creates the callout extension with the specified text and language.
$hotelCalloutFeedItem = new HotelCalloutFeedItem([
'text' => $calloutText,
'language_code' => $languageCode
]);
// Creates a feed item from the hotel callout extension.
$extensionFeedItem =
new ExtensionFeedItem(['hotel_callout_feed_item' => $hotelCalloutFeedItem]);
// Creates an extension feed item operation.
$extensionFeedItemOperation = new ExtensionFeedItemOperation();
$extensionFeedItemOperation->setCreate($extensionFeedItem);
// Issues a mutate request to add the extension feed item and print its information.
$extensionFeedItemServiceClient = $googleAdsClient->getExtensionFeedItemServiceClient();
$response = $extensionFeedItemServiceClient->mutateExtensionFeedItems(
$customerId,
[$extensionFeedItemOperation]
);
$extensionFeedItemResourceName = $response->getResults()[0]->getResourceName();
printf(
"Created an extension feed item with resource name: '%s'.%s",
$extensionFeedItemResourceName,
PHP_EOL
);
return $extensionFeedItemResourceName;
}
/**
* Adds the extension feed item to the customer account.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param string $extensionFeedItemResourceName the extension feed item resource name
*/
private static function addExtensionToAccount(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $extensionFeedItemResourceName
): void {
// Creates a customer extension setting, sets its type to HOTEL_CALLOUT, and attaches the
// feed item.
$customerExtensionSetting = new CustomerExtensionSetting([
'extension_type' => ExtensionType::HOTEL_CALLOUT,
'extension_feed_items' => [$extensionFeedItemResourceName]
]);
// Creates a customer extension setting operation.
$customerExtensionSettingOperation = new CustomerExtensionSettingOperation();
$customerExtensionSettingOperation->setCreate($customerExtensionSetting);
// Issues a mutate request to add the customer extension setting and prints its information.
$customerExtensionSettingServiceClient =
$googleAdsClient->getCustomerExtensionSettingServiceClient();
$response = $customerExtensionSettingServiceClient->mutateCustomerExtensionSettings(
$customerId,
[$customerExtensionSettingOperation]
);
printf(
"Created a customer extension setting with resource name: '%s'.%s",
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
/**
* Adds the extension feed item to the specified campaign.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $campaignId the campaign ID
* @param string $extensionFeedItemResourceName the extension feed item resource name
*/
private static function addExtensionToCampaign(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $campaignId,
string $extensionFeedItemResourceName
): void {
// Creates a campaign extension setting, sets its type to HOTEL_CALLOUT, and attaches the
// feed item.
$campaignExtensionSetting = new CampaignExtensionSetting([
'campaign' => ResourceNames::forCampaign($customerId, $campaignId),
'extension_type' => ExtensionType::HOTEL_CALLOUT,
'extension_feed_items' => [$extensionFeedItemResourceName]
]);
// Creates a campaign extension setting operation.
$campaignExtensionSettingOperation = new CampaignExtensionSettingOperation();
$campaignExtensionSettingOperation->setCreate($campaignExtensionSetting);
// Issues a mutate request to add the campaign extension setting and prints its information.
$campaignExtensionSettingServiceClient =
$googleAdsClient->getCampaignExtensionSettingServiceClient();
$response = $campaignExtensionSettingServiceClient->mutateCampaignExtensionSettings(
$customerId,
[$campaignExtensionSettingOperation]
);
printf(
"Created a campaign extension setting with resource name: '%s'.%s",
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
/**
* Adds the extension feed item to the specified ad group.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
* @param int $adGroupId the ad group ID
* @param string $extensionFeedItemResourceName the extension feed item resource name
*/
private static function addExtensionToAdGroup(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $adGroupId,
string $extensionFeedItemResourceName
): void {
// Creates an ad group extension setting, sets its type to HOTEL_CALLOUT, and attaches the
// feed item.
$adGroupExtensionSetting = new AdGroupExtensionSetting([
'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
'extension_type' => ExtensionType::HOTEL_CALLOUT,
'extension_feed_items' => [$extensionFeedItemResourceName]
]);
// Creates an ad group extension setting operation.
$adGroupExtensionSettingOperation = new AdGroupExtensionSettingOperation();
$adGroupExtensionSettingOperation->setCreate($adGroupExtensionSetting);
// Issues a mutate request to add the ad group extension setting and prints its information.
$adGroupExtensionSettingServiceClient =
$googleAdsClient->getAdGroupExtensionSettingServiceClient();
$response = $adGroupExtensionSettingServiceClient->mutateAdGroupExtensionSettings(
$customerId,
[$adGroupExtensionSettingOperation]
);
printf(
"Created an ad group extension setting with resource name: '%s'.%s",
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
}
AddHotelCallout::main();
Python
#!/usr/bin/env python
# Copyright 2020 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 callout extension to a specific account.
It also adds the hotel callout extension to a campaign and an ad group under
the account.
"""
import argparse
import sys
from google.api_core import protobuf_helpers
from google.ads.google_ads.client import GoogleAdsClient
from google.ads.google_ads.errors import GoogleAdsException
def main(
client, customer_id, campaign_id, ad_group_id, callout_text, language_code
):
"""The main method that creates all necessary entities for the example.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
campaign_id: a str of a campaign ID.
ad_group_id: a str of an ad_group ID.
callout_text: a str of text for a hotel callout feed item.
language_code: the language of the hotel callout feed item text.
"""
try:
# Creates an extension feed item as hotel callout.
extension_feed_item_resource_name = _add_extension_feed_item(
client, customer_id, callout_text, language_code
)
# Adds the extension feed item to the account.
_add_extension_to_account(
client, customer_id, extension_feed_item_resource_name
)
# Adds the extension feed item to the campaign.
_add_extension_to_campaign(
client, customer_id, campaign_id, extension_feed_item_resource_name
)
# Adds the extension feed item to the ad group.
_add_extension_to_ad_group(
client, customer_id, ad_group_id, extension_feed_item_resource_name
)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
def _add_extension_feed_item(client, customer_id, callout_text, language_code):
"""Creates a new extension feed item for the callout extension.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
callout_text: a str of text for a hotel callout feed item.
language_code: the language of the hotel callout feed item text.
Returns:
a str resource name of the newly created extension feed item.
"""
extension_feed_item_operation = client.get_type(
"ExtensionFeedItemOperation", version="v6"
)
extension_feed_item = extension_feed_item_operation.create
extension_feed_item.hotel_callout_feed_item.text = callout_text
extension_feed_item.hotel_callout_feed_item.language_code = language_code
extension_feed_item_service = client.get_service(
"ExtensionFeedItemService", version="v6"
)
response = extension_feed_item_service.mutate_extension_feed_items(
customer_id, [extension_feed_item_operation]
)
resource_name = response.results[0].resource_name
print(
f"Created an extension feed item with resource name: "
"'{resource_name}'"
)
return resource_name
def _add_extension_to_account(
client, customer_id, extension_feed_item_resource_name
):
"""Adds the extension feed item to the customer account.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
extension_feed_item_resource_name: a str resource name of an extension
feed item.
"""
customer_extension_setting_operation = client.get_type(
"CustomerExtensionSettingOperation", version="v6"
)
customer_extension_setting = customer_extension_setting_operation.create
customer_extension_setting.extension_type = client.get_type(
"ExtensionTypeEnum", version="v6"
).HOTEL_CALLOUT
customer_extension_setting.extension_feed_items.append(
extension_feed_item_resource_name
)
customer_extension_setting_service = client.get_service(
"CustomerExtensionSettingService", version="v6"
)
response = customer_extension_setting_service.mutate_customer_extension_settings(
customer_id, [customer_extension_setting_operation]
)
print(
"Created a customer extension setting with resource name: "
f"'{response.results[0].resource_name}'"
)
def _add_extension_to_campaign(
client, customer_id, campaign_id, extension_feed_item_resource_name
):
"""Adds the extension feed item to the specified campaign.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
campaign_id: a str of a campaign ID.
extension_feed_item_resource_name: a str resource name of an extension
feed item.
"""
campaign_extension_setting_operation = client.get_type(
"CampaignExtensionSettingOperation", version="v6"
)
campaign_extension_setting = campaign_extension_setting_operation.create
campaign_extension_setting.campaign = client.get_service(
"CampaignService", version="v6"
).campaign_path(customer_id, campaign_id)
campaign_extension_setting.extension_type = client.get_type(
"ExtensionTypeEnum", version="v6"
).HOTEL_CALLOUT
campaign_extension_setting.extension_feed_items.append(
extension_feed_item_resource_name
)
campaign_extension_setting_service = client.get_service(
"CampaignExtensionSettingService", version="v6"
)
response = campaign_extension_setting_service.mutate_campaign_extension_settings(
customer_id, [campaign_extension_setting_operation]
)
print(
"Created a campaign extension setting with resource name: "
f"'{response.results[0].resource_name}'"
)
def _add_extension_to_ad_group(
client, customer_id, ad_group_id, extension_feed_item_resource_name
):
"""Adds the extension feed item to the specified ad group.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
ad_group_id: a str of an ad_group ID.
extension_feed_item_resource_name: a str resource name of an extension
feed item.
"""
ad_group_extension_setting_operation = client.get_type(
"AdGroupExtensionSettingOperation", version="v6"
)
ad_group_extension_setting = ad_group_extension_setting_operation.create
ad_group_extension_setting.ad_group = client.get_service(
"AdGroupService", version="v6"
).ad_group_path(customer_id, ad_group_id)
ad_group_extension_setting.extension_type = client.get_type(
"ExtensionTypeEnum", version="v6"
).HOTEL_CALLOUT
ad_group_extension_setting.extension_feed_items.append(
extension_feed_item_resource_name
)
ad_group_extension_setting_service = client.get_service(
"AdGroupExtensionSettingService", version="v6"
)
response = ad_group_extension_setting_service.mutate_ad_group_extension_settings(
customer_id, [ad_group_extension_setting_operation]
)
print(
"Created a ad_group extension setting with resource name: "
f"'{response.results[0].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 = GoogleAdsClient.load_from_storage()
parser = argparse.ArgumentParser(
description="Adds a hotel callout extension to the given account."
)
# The following argument(s) should be provided to run the example.
parser.add_argument(
"-c",
"--customer_id",
type=str,
required=True,
help="The Google Ads customer ID",
)
parser.add_argument(
"-i", "--campaign_id", type=str, required=True, help="The campaign ID.",
)
parser.add_argument(
"-a",
"--ad_group_id",
type=str,
required=False,
help="The ad group ID. ",
)
parser.add_argument(
"-t",
"--callout_text",
type=str,
required=True,
help=(
"The text of the hotel callout feed item. This text has a maximum "
"length of 25 characters."
),
)
parser.add_argument(
"-l",
"--language_code",
type=str,
required=True,
help=(
"The language of the text on the hotel callout feed item. For a "
"list of supported languages see: "
"https://developers.google.com/hotels/hotel-ads/api-reference/language-codes."
),
)
args = parser.parse_args()
main(
google_ads_client,
args.customer_id,
args.campaign_id,
args.ad_group_id,
args.callout_text,
args.language_code,
)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 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 callout extension to a specific account, campaign
# within the account, and ad group within the campaign.
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_hotel_callout(
customer_id,
campaign_id,
ad_group_id,
callout_text,
language_code)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
# Creates an extension feed item as hotel callout.
extension_feed_item_resource_name = add_extension_feed_item(
client,
customer_id,
callout_text,
language_code,
)
# Adds the extension feed item to the account.
add_extension_to_account(
client,
customer_id,
extension_feed_item_resource_name,
)
# Adds the extension feed item to the campaign.
add_extension_to_campaign(
client,
customer_id,
campaign_id,
extension_feed_item_resource_name,
)
# Adds the extension feed item to the ad group.
add_extension_to_ad_group(
client,
customer_id,
ad_group_id,
extension_feed_item_resource_name,
)
end
# Creates a new extension feed item for the callout extension.
def add_extension_feed_item(
client,
customer_id,
callout_text,
language_code)
# Creates a feed item from the hotel callout extension.
operation = client.operation.create_resource.extension_feed_item do |efi|
# Creates the callout extension with the specified text and language.
efi.hotel_callout_feed_item = client.resource.hotel_callout_feed_item do |f|
f.text = callout_text
f.language_code = language_code
end
end
# Issues a mutate request to add the extension feed item and print its information.
response = client.service.extension_feed_item.mutate_extension_feed_items(
customer_id: customer_id,
operations: [operation],
)
extension_feed_item_resource_name = response.results.first.resource_name
puts "Created an extension feed item with resource name: " \
"#{extension_feed_item_resource_name}"
extension_feed_item_resource_name
end
# Adds the extension feed item to the customer account.
def add_extension_to_account(
client,
customer_id,
extension_feed_item_resource_name)
# Creates a customer extension setting, sets its type to HOTEL_CALLOUT, and
# attaches the feed item.
operation = client.operation.create_resource.customer_extension_setting do |s|
s.extension_type = :HOTEL_CALLOUT
s.extension_feed_items << extension_feed_item_resource_name
end
# Issues a mutate request to add the customer extension setting and prints
# its information.
response = client.service.customer_extension_setting.mutate_customer_extension_settings(
customer_id: customer_id,
operations: [operation],
)
puts "Created a customer extension setting with resource name: " \
"#{response.results.first.resource_name}"
end
# Adds the extension feed item to the specified campaign.
def add_extension_to_campaign(
client,
customer_id,
campaign_id,
extension_feed_item_resource_name)
# Creates a campaign extension setting, sets its type to HOTEL_CALLOUT, and
# attaches the feed item.
operation = client.operation.create_resource.campaign_extension_setting do |s|
s.campaign = client.path.campaign(customer_id, campaign_id)
s.extension_type = :HOTEL_CALLOUT
s.extension_feed_items << extension_feed_item_resource_name
end
# Issues a mutate request to add the campaign extension setting and prints
# its information.
response = client.service.campaign_extension_setting.mutate_campaign_extension_settings(
customer_id: customer_id,
operations: [operation],
)
puts "Created a campaign extension setting with resource name: " \
"#{response.results.first.resource_name}"
end
# Adds the extension feed item to the specified ad group.
def add_extension_to_ad_group(
client,
customer_id,
ad_group_id,
extension_feed_item_resource_name)
# Creates a ad group extension setting, sets its type to HOTEL_CALLOUT, and
# attaches the feed item.
operation = client.operation.create_resource.ad_group_extension_setting do |s|
s.ad_group = client.path.ad_group(customer_id, ad_group_id)
s.extension_type = :HOTEL_CALLOUT
s.extension_feed_items << extension_feed_item_resource_name
end
# Issues a mutate request to add the ad group extension setting and prints
# its information.
response = client.service.ad_group_extension_setting.mutate_ad_group_extension_settings(
customer_id: customer_id,
operations: [operation],
)
puts "Created an ad group extension setting with resource name: " \
"#{response.results.first.resource_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[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'
options[:callout_text] = 'INSERT_CALLOUT_TEXT_HERE'
# See supported languages at:
# https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.
options[:language_code] = 'INSERT_LANGUAGE_CODE_HERE'
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('-c', '--campaign-id CAMPAIGN-ID', Integer, 'Campaign ID') do |v|
options[:campaign_id] = v
end
opts.on('-A', '--ad-group-id AD-GROUP-ID', Integer, 'Ad Group ID') do |v|
options[:ad_group_id] = v
end
opts.on('-T', '--callout-text CALLOUT-TEXT', String, 'Callout Text') do |v|
options[:callout_text] = v
end
opts.on('-L', '--language-code LANGUAGE-CODE', String, 'Language Code') do |v|
options[:language_code] = 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_callout(
options.fetch(:customer_id).tr("-", ""),
options[:campaign_id],
options[:ad_group_id],
options[:callout_text],
options[:language_code],
)
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
raise
end
end
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::V6::Resources::ExtensionFeedItem;
use Google::Ads::GoogleAds::V6::Resources::CampaignExtensionSetting;
use Google::Ads::GoogleAds::V6::Resources::AdGroupExtensionSetting;
use Google::Ads::GoogleAds::V6::Resources::CustomerExtensionSetting;
use Google::Ads::GoogleAds::V6::Common::HotelCalloutFeedItem;
use Google::Ads::GoogleAds::V6::Enums::ExtensionTypeEnum qw(HOTEL_CALLOUT);
use
Google::Ads::GoogleAds::V6::Services::ExtensionFeedItemService::ExtensionFeedItemOperation;
use
Google::Ads::GoogleAds::V6::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation;
use
Google::Ads::GoogleAds::V6::Services::AdGroupExtensionSettingService::AdGroupExtensionSettingOperation;
use
Google::Ads::GoogleAds::V6::Services::CustomerExtensionSettingService::CustomerExtensionSettingOperation;
use Google::Ads::GoogleAds::V6::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::V6::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::V6::Resources::ExtensionFeedItem->new({
hotelCalloutFeedItem => $hotel_callout_feed_item
});
# Create an extension feed item operation.
my $extension_feed_item_operation =
Google::Ads::GoogleAds::V6::Services::ExtensionFeedItemService::ExtensionFeedItemOperation
->new({
create => $extension_feed_item
});
# Issue a mutate request to add the extension feed item.
my $extension_feed_items_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_items_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::V6::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::V6::Services::CustomerExtensionSettingService::CustomerExtensionSettingOperation
->new({
create => $customer_extension_setting
});
# Issue a mutate request to add the customer extension setting.
my $customer_extension_settings_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_settings_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::V6::Resources::CampaignExtensionSetting->new({
extensionType => HOTEL_CALLOUT,
campaign => Google::Ads::GoogleAds::V6::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::V6::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation
->new({
create => $campaign_extension_setting
});
# Issue a mutate request to add the campaign extension setting.
my $campaign_extension_settings_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_settings_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::V6::Resources::AdGroupExtensionSetting->new({
extensionType => HOTEL_CALLOUT,
adGroup => Google::Ads::GoogleAds::V6::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::V6::Services::AdGroupExtensionSettingService::AdGroupExtensionSettingOperation
->new({
create => $ad_group_extension_setting
});
# Issue a mutate request to add the ad group extension setting.
my $ad_group_extension_settings_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_settings_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