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.assets; 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.v18.common.HotelCalloutAsset; import com.google.ads.googleads.v18.enums.AssetFieldTypeEnum.AssetFieldType; import com.google.ads.googleads.v18.errors.GoogleAdsError; import com.google.ads.googleads.v18.errors.GoogleAdsException; import com.google.ads.googleads.v18.resources.Asset; import com.google.ads.googleads.v18.resources.CustomerAsset; import com.google.ads.googleads.v18.services.AssetOperation; import com.google.ads.googleads.v18.services.AssetServiceClient; import com.google.ads.googleads.v18.services.CustomerAssetOperation; import com.google.ads.googleads.v18.services.CustomerAssetServiceClient; import com.google.ads.googleads.v18.services.MutateAssetResult; import com.google.ads.googleads.v18.services.MutateAssetsResponse; import com.google.ads.googleads.v18.services.MutateCustomerAssetResult; import com.google.ads.googleads.v18.services.MutateCustomerAssetsResponse; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** Adds a hotel callout asset and adds the asset to the given account. */ public class AddHotelCallout { private static class AddHotelCalloutParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; // 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.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.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, String languageCode) { // Creates assets for the hotel callouts. List<String> assetResourceNames = addHotelCalloutAssets(googleAdsClient, customerId, languageCode); // Links the assets at the account level, so they will serve in all eligible campaigns. linkAssetsToAccount(googleAdsClient, customerId, assetResourceNames); } /** Creates new hotel callout assets. */ private List<String> addHotelCalloutAssets( GoogleAdsClient googleAdsClient, long customerId, String languageCode) { List<HotelCalloutAsset> hotelCalloutAssets = new ArrayList<>(); // Creates the callouts with text and specified language. hotelCalloutAssets.add( HotelCalloutAsset.newBuilder().setText("Activities").setLanguageCode(languageCode).build()); hotelCalloutAssets.add( HotelCalloutAsset.newBuilder().setText("Facilities").setLanguageCode(languageCode).build()); // Wraps the HotelCalloutAsset in an Asset and creates an AssetOperation to add the Asset. List<AssetOperation> operations = hotelCalloutAssets.stream() .map(callout -> Asset.newBuilder().setHotelCalloutAsset(callout).build()) .map(asset -> AssetOperation.newBuilder().setCreate(asset).build()) .collect(Collectors.toList()); // Issues the create request to create the assets. try (AssetServiceClient assetClient = googleAdsClient.getLatestVersion().createAssetServiceClient()) { MutateAssetsResponse response = assetClient.mutateAssets(String.valueOf(customerId), operations); List<String> resourceNames = response.getResultsList().stream() .map(MutateAssetResult::getResourceName) .collect(Collectors.toList()); // Prints some information about the result. for (String resName : resourceNames) { System.out.printf("Created hotel call out asset with resource name %s.%n", resName); } return resourceNames; } } /** Links Asset at the Customer level to serve in all eligible campaigns. */ private void linkAssetsToAccount( GoogleAdsClient googleAdsClient, long customerId, List<String> assetResourceNames) { // Creates a CustomerAsset link for each Asset resource name provided, then converts this into a // CustomerAssetOperation to create the Asset. List<CustomerAssetOperation> customerAssetsOperations = assetResourceNames.stream() .map( asset -> CustomerAsset.newBuilder() .setAsset(asset) .setFieldType(AssetFieldType.HOTEL_CALLOUT) .build()) .map( customerAsset -> CustomerAssetOperation.newBuilder().setCreate(customerAsset).build()) .collect(Collectors.toList()); // Issues the create request to add the callout. try (CustomerAssetServiceClient customerAssetClient = googleAdsClient.getLatestVersion().createCustomerAssetServiceClient()) { MutateCustomerAssetsResponse response = customerAssetClient.mutateCustomerAssets( String.valueOf(customerId), customerAssetsOperations); List<String> resourceNames = response.getResultsList().stream() .map(MutateCustomerAssetResult::getResourceName) .collect(Collectors.toList()); for (String resName : resourceNames) { System.out.printf("Added an account asset with resource name: '%s'.%n", resName); } } } }
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 CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V18.Common; using Google.Ads.GoogleAds.V18.Errors; using Google.Ads.GoogleAds.V18.Resources; using Google.Ads.GoogleAds.V18.Services; using System; using System.Collections.Generic; using System.Linq; using static Google.Ads.GoogleAds.V18.Enums.AssetFieldTypeEnum.Types; namespace Google.Ads.GoogleAds.Examples.V18 { /// <summary> /// This example adds a hotel callout asset to a specific account, campaign within the /// account, and ad group within the campaign. /// </summary> public class AddHotelCallout : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddHotelCallout"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// The language code for the text. See supported languages at: /// https://developers.google.com/hotels/hotel-ads/api-reference/language-codes. /// </summary> [Option("languageCode", Required = true, HelpText = "The language code for the text. See supported languages at: " + "https://developers.google.com/hotels/hotel-ads/api-reference/language-codes.")] public string LanguageCode { get; set; } } /// <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) { Options options = ExampleUtilities.ParseCommandLine<Options>(args); AddHotelCallout codeExample = new AddHotelCallout(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.LanguageCode); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This example adds a hotel callout asset to a specific account."; /// <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="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, string languageCode) { try { // Creates assets for the hotel callout asset. List<string> assetResourceNames = AddHotelCalloutAsset(client, customerId, languageCode); // Adds the asset at the account level, so these will serve in all eligible // campaigns. LinkAssetToAccount(client, customerId, assetResourceNames); } 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 asset for the callout. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="languageCode">The language code for the text.</param> /// <returns>The created asset resource name.</returns> private List<string> AddHotelCalloutAsset(GoogleAdsClient client, in long customerId, string languageCode) { List<HotelCalloutAsset> hotelCalloutAssets = new List<HotelCalloutAsset>(); // Creates the callouts with text and specified language. hotelCalloutAssets.Add( new HotelCalloutAsset { Text = "Activities", LanguageCode = languageCode, }); hotelCalloutAssets.Add( new HotelCalloutAsset { Text = "Facilities", LanguageCode = languageCode, }); // Wraps the HotelCalloutAsset in an Asset and creates an AssetOperation to add the // Asset. List<AssetOperation> operations = new List<AssetOperation>(); foreach (HotelCalloutAsset asset in hotelCalloutAssets) { operations.Add(new AssetOperation { Create = new Asset { HotelCalloutAsset = asset, }, }); } // Issues the create request to create the assets. AssetServiceClient assetClient = client.GetService(Services.V18.AssetService); MutateAssetsResponse response = assetClient.MutateAssets(customerId.ToString(), operations); List<MutateAssetResult> results = response.Results.ToList(); List<string> resourceNames = new List<string>(); // Prints some information about the result. foreach (MutateAssetResult result in results) { resourceNames.Add(result.ResourceName); Console.WriteLine("Created hotel call out asset with resource name " + result.ResourceName); } return resourceNames; } /// <summary> /// Link asset to customer. /// </summary> /// <param name="client">The Google Ads API client.</param> /// <param name="customerId">The client customer ID.</param> /// <param name="assetResourceNames">The asset resource names.</param> private void LinkAssetToAccount(GoogleAdsClient client, in long customerId, List<string> assetResourceNames) { // Creates a CustomerAsset link for each Asset resource name provided, then converts // this into a CustomerAssetOperation to create the Asset. List<CustomerAssetOperation> customerAssetOperations = new List<CustomerAssetOperation>(); foreach (string asset in assetResourceNames) { customerAssetOperations.Add( new CustomerAssetOperation { Create = new CustomerAsset { Asset = asset, FieldType = AssetFieldType.HotelCallout, }, }); } // Issues the create request to add the callout. CustomerAssetServiceClient customerAssetServiceClient = client.GetService(Services.V18.CustomerAssetService); MutateCustomerAssetsResponse response = customerAssetServiceClient.MutateCustomerAssets(customerId.ToString(), customerAssetOperations); foreach (MutateCustomerAssetResult result in response.Results) { Console.WriteLine("Added an account asset with resource name: " + result.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\V18\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V18\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V18\GoogleAdsException; use Google\Ads\GoogleAds\V18\Common\HotelCalloutAsset; use Google\Ads\GoogleAds\V18\Enums\AssetFieldTypeEnum\AssetFieldType; use Google\Ads\GoogleAds\V18\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V18\Resources\Asset; use Google\Ads\GoogleAds\V18\Resources\CustomerAsset; use Google\Ads\GoogleAds\V18\Services\AssetOperation; use Google\Ads\GoogleAds\V18\Services\CustomerAssetOperation; use Google\Ads\GoogleAds\V18\Services\MutateAssetResult; use Google\Ads\GoogleAds\V18\Services\MutateAssetsRequest; use Google\Ads\GoogleAds\V18\Services\MutateCustomerAssetResult; use Google\Ads\GoogleAds\V18\Services\MutateCustomerAssetsRequest; use Google\ApiCore\ApiException; /** * This example adds a hotel callout asset to a specific account. */ class AddHotelCallout { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_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::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::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 string $languageCode the language code */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, string $languageCode ) { // Creates assets for the hotel callout assets. $assetResourceNames = self::addHotelCalloutAsset($googleAdsClient, $customerId, $languageCode); // Adds the assets at the account level, so these will serve in all eligible campaigns. self::linkAssetsToAccount($googleAdsClient, $customerId, $assetResourceNames); } /** * Creates new assets for the callout. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the client customer ID * @param string $languageCode the language code for the callout text * @return string[] the resource names of created hotel callout assets */ private static function addHotelCalloutAsset( GoogleAdsClient $googleAdsClient, int $customerId, string $languageCode ): array { // Creates the hotel callouts with text and specified language. $hotelCalloutAssets = [ new HotelCalloutAsset(['text' => 'Activities', 'language_code' => $languageCode]), new HotelCalloutAsset(['text' => 'Facilities', 'language_code' => $languageCode]) ]; // For each HotelCalloutAsset, wraps it in an Asset and creates an AssetOperation to add the // Asset. $assetOperations = array_map(function (HotelCalloutAsset $hotelCalloutAsset) { return new AssetOperation([ 'create' => new Asset(['hotel_callout_asset' => $hotelCalloutAsset]) ]); }, $hotelCalloutAssets); // Issues a mutate request to add the assets and print its information. $assetServiceClient = $googleAdsClient->getAssetServiceClient(); $response = $assetServiceClient->mutateAssets( MutateAssetsRequest::build($customerId, $assetOperations) ); $createdAssetResourceNames = []; foreach ($response->getResults() as $result) { /** @var MutateAssetResult $result */ printf( "Created a hotel callout asset with resource name: '%s'.%s", $result->getResourceName(), PHP_EOL ); $createdAssetResourceNames[] = $result->getResourceName(); } return $createdAssetResourceNames; } /** * Links the hotel callout assets at the account level to serve in all eligible campaigns. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the client customer ID * @param string[] $assetResourceNames the resource names of the hotel callout assets */ private static function linkAssetsToAccount( GoogleAdsClient $googleAdsClient, int $customerId, array $assetResourceNames ): void { // Creates a CustomerAssetOperation for each asset resource name by linking it to a newly // created CustomerAsset. $customerAssetOperations = array_map(function (string $assetResourceName) { return new CustomerAssetOperation(['create' => new CustomerAsset([ 'asset' => $assetResourceName, 'field_type' => AssetFieldType::HOTEL_CALLOUT ])]); }, $assetResourceNames); // Issues a mutate request to add the customer assets and prints its information. $customerAssetServiceClient = $googleAdsClient->getCustomerAssetServiceClient(); $response = $customerAssetServiceClient->mutateCustomerAssets( MutateCustomerAssetsRequest::build($customerId, $customerAssetOperations) ); foreach ($response->getResults() as $result) { /** @var MutateCustomerAssetResult $result */ printf( "Created a customer asset with resource name: '%s'.%s", $result->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 asset to a specific account.""" import argparse import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException def main(client, customer_id, 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. language_code: the language of the hotel callout feed item text. """ # Creates assets for the hotel callout assets. asset_resource_names = add_hotel_callout_assets( client, customer_id, language_code ) # Adds the assets at the account level, so these will serve in all eligible # campaigns. link_asset_to_account(client, customer_id, asset_resource_names) def add_hotel_callout_assets(client, customer_id, language_code): """Creates new assets for the hotel callout. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. language_code: the language of the hotel callout feed item text. Returns: a list of asset resource names. """ operations = [] # Create a hotel callout asset operation for each of the below texts. for text in ["Activities", "Facilities"]: operation = client.get_type("AssetOperation") asset = operation.create asset.hotel_callout_asset.text = text asset.hotel_callout_asset.language_code = language_code operations.append(operation) asset_service = client.get_service("AssetService") # Issues the create request to create the assets. response = asset_service.mutate_assets( customer_id=customer_id, operations=operations ) resource_names = [result.resource_name for result in response.results] # Prints information about the result. for resource_name in resource_names: print( "Created hotel callout asset with resource name " f"'{resource_name}'." ) return resource_names def link_asset_to_account(client, customer_id, resource_names): """Links Asset at the Customer level to serve in all eligible campaigns. Args: client: an initialized GoogleAdsClient instance. customer_id: a client customer ID. resource_names: a list of asset resource names. """ # Creates a CustomerAsset link for each Asset resource name provided. operations = [] for resource_name in resource_names: operation = client.get_type("CustomerAssetOperation") asset = operation.create asset.asset = resource_name asset.field_type = client.enums.AssetFieldTypeEnum.HOTEL_CALLOUT operations.append(operation) customer_asset_service = client.get_service("CustomerAssetService") response = customer_asset_service.mutate_customer_assets( customer_id=customer_id, operations=operations ) for result in response.results: print( "Added a customer asset with resource name " f"'{result.resource_name}'." ) if __name__ == "__main__": parser = argparse.ArgumentParser( description=( "Adds a hotel callout asset and adds the asset 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( "-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() # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v18") try: main(googleads_client, args.customer_id, args.language_code) 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)
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 asset to a specific account. require 'optparse' require 'google/ads/google_ads' require 'date' def add_hotel_callout(customer_id, 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 a hotel callout asset. asset_resource_names = add_hotel_callout_assets(client, customer_id, language_code) # Adds the asset at the account level, so it will serve in all eligible campaigns. link_assets_to_account(client, customer_id, asset_resource_names) end # Creates a new asset. def add_hotel_callout_assets(client, customer_id, language_code) operations = [ client.resource.hotel_callout_asset do |hca| hca.text = 'Activities' hca.language_code = language_code end, client.resource.hotel_callout_asset do |hca| hca.text = 'Facilities' hca.language_code = language_code end ].map do |hca| client.operation.create_resource.asset do |asset| asset.hotel_callout_asset = hca end end response = client.service.asset.mutate_assets( customer_id: customer_id, operations: operations, ) response.results.map do |result| puts "Created hotel callout asset with resource name #{result.resource_name}" result.resource_name end end # Adds the asset to the customer account. def link_assets_to_account(client, customer_id, asset_resource_names) operations = asset_resource_names.map do |asset_resource_name| client.operation.create_resource.customer_asset do |ca| ca.asset = asset_resource_name ca.field_type = :HOTEL_CALLOUT end end response = client.service.customer_asset.mutate_customer_assets( customer_id: customer_id, operations: operations, ) response.results.each do |result| puts "Created customer asset link with resource name #{result.resource_name}" end 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[:language_code] = 'INSERT_LANGUAGE_CODE_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('-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[: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 hotel callout assets to a specific account. 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::V18::Resources::Asset; use Google::Ads::GoogleAds::V18::Resources::CustomerAsset; use Google::Ads::GoogleAds::V18::Common::HotelCalloutAsset; use Google::Ads::GoogleAds::V18::Enums::AssetFieldTypeEnum qw(HOTEL_CALLOUT); use Google::Ads::GoogleAds::V18::Services::AssetService::AssetOperation; use Google::Ads::GoogleAds::V18::Services::CustomerAssetService::CustomerAssetOperation; 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"; # 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, $language_code) = @_; # Create assets for the hotel callout assets. my $hotel_callout_asset_resource_names = add_hotel_callout_assets($api_client, $customer_id, $language_code); # Add the assets at the account level, so these will serve in all eligible campaigns. link_assets_to_account($api_client, $customer_id, $hotel_callout_asset_resource_names); return 1; } # Creates new assets for the callout. sub add_hotel_callout_assets { my ($api_client, $customer_id, $language_code) = @_; my $hotel_callout_assets = []; # Create the callouts with text and specified language. push @$hotel_callout_assets, Google::Ads::GoogleAds::V18::Common::HotelCalloutAsset->new({ text => "Activities", languageCode => $language_code }); push @$hotel_callout_assets, Google::Ads::GoogleAds::V18::Common::HotelCalloutAsset->new({ text => "Facilities", languageCode => $language_code }); my $operations = []; # Wrap the HotelCalloutAsset in an Asset and create an AssetOperation to add the Asset. foreach my $hotel_callout_asset (@$hotel_callout_assets) { push @$operations, Google::Ads::GoogleAds::V18::Services::AssetService::AssetOperation->new({ create => Google::Ads::GoogleAds::V18::Resources::Asset->new({ hotelCalloutAsset => $hotel_callout_asset })}); } # Issue the create request to create the assets. my $response = $api_client->AssetService()->mutate({ customerId => $customer_id, operations => $operations }); # Print some information about the result. my $resource_names = []; foreach my $result (@{$response->{results}}) { push @$resource_names, $result->{resourceName}; printf "Created hotel callout asset with resource name '%s'.\n", $result->{resourceName}; } return $resource_names; } # Links the assets at the Customer level to serve in all eligible campaigns. sub link_assets_to_account { my ($api_client, $customer_id, $hotel_callout_asset_resource_names) = @_; # Create a CustomerAsset link for each Asset resource name provided, then # convert this into a CustomerAssetOperation to create the Asset. my $operations = []; foreach my $hotel_callout_asset_resource_name (@$hotel_callout_asset_resource_names) { push @$operations, Google::Ads::GoogleAds::V18::Services::CustomerAssetService::CustomerAssetOperation ->new({ create => Google::Ads::GoogleAds::V18::Resources::CustomerAsset->new({ asset => $hotel_callout_asset_resource_name, fieldType => HOTEL_CALLOUT })}); } # Send the mutate request. my $response = $api_client->CustomerAssetService()->mutate({ customerId => $customer_id, operations => $operations }); # Print some information about the result. foreach my $result (@{$response->{results}}) { printf "Added a account asset with resource name '%s'.\n", $result->{resourceName}; } } # 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, "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, $language_code); # Call the example. add_hotel_callout($api_client, $customer_id =~ s/-//gr, $language_code); =pod =head1 NAME add_hotel_callout =head1 DESCRIPTION This example adds hotel callout assets to a specific account. =head1 SYNOPSIS add_hotel_callout.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. -language_code The hotel callout language code, e.g. specify 'en' for English. =cut