자바
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.ads.googleads.examples.targeting; import com.google.ads.googleads.lib.GoogleAdsClient; import com.google.ads.googleads.v17.errors.GoogleAdsError; import com.google.ads.googleads.v17.errors.GoogleAdsException; import com.google.ads.googleads.v17.services.GeoTargetConstantServiceClient; import com.google.ads.googleads.v17.services.GeoTargetConstantSuggestion; import com.google.ads.googleads.v17.services.SuggestGeoTargetConstantsRequest; import com.google.ads.googleads.v17.services.SuggestGeoTargetConstantsResponse; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; /** Gets GeoTargetConstants by given location names. */ public class GetGeoTargetConstantsByNames { public static void main(String[] args) { 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 GetGeoTargetConstantsByNames().runExample(googleAdsClient); } 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. * * @param googleAdsClient the Google Ads API client. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void runExample(GoogleAdsClient googleAdsClient) { try (GeoTargetConstantServiceClient geoTargetClient = googleAdsClient.getLatestVersion().createGeoTargetConstantServiceClient()) { SuggestGeoTargetConstantsRequest.Builder requestBuilder = SuggestGeoTargetConstantsRequest.newBuilder(); // Locale is using ISO 639-1 format. If an invalid locale is given, 'en' is used by default. requestBuilder.setLocale("en"); // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets requestBuilder.setCountryCode("FR"); requestBuilder .getLocationNamesBuilder() .addAllNames(ImmutableList.of("Paris", "Quebec", "Spain", "Deutschland")); SuggestGeoTargetConstantsResponse response = geoTargetClient.suggestGeoTargetConstants(requestBuilder.build()); for (GeoTargetConstantSuggestion suggestion : response.getGeoTargetConstantSuggestionsList()) { System.out.printf( "%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d) for search term (%s).%n", suggestion.getGeoTargetConstant().getResourceName(), suggestion.getGeoTargetConstant().getName(), suggestion.getGeoTargetConstant().getCountryCode(), suggestion.getGeoTargetConstant().getTargetType(), suggestion.getGeoTargetConstant().getStatus().name(), suggestion.getLocale(), suggestion.getReach(), suggestion.getSearchTerm()); } } } }
C#
// 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. using CommandLine; using Google.Ads.Gax.Examples; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V17.Errors; using Google.Ads.GoogleAds.V17.Services; using System; using System.Collections.Generic; namespace Google.Ads.GoogleAds.Examples.V17 { /// <summary> /// This code example illustrates getting GeoTargetConstants by given location names. /// </summary> public class GetGeoTargetConstantsByNames : ExampleBase { /// <summary> /// Command line options for running the <see cref="GetGeoTargetConstantsByNames"/> example. /// </summary> public class Options : OptionsBase { } /// <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); GetGeoTargetConstantsByNames codeExample = new GetGeoTargetConstantsByNames(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient()); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example illustrates getting GeoTargetConstants by given location names."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> public void Run(GoogleAdsClient client) { // Get the GeoTargetConstantServiceClient. GeoTargetConstantServiceClient geoService = client.GetService(Services.V17.GeoTargetConstantService); // Locale is using ISO 639-1 format. If an invalid locale is given, // 'en' is used by default. string locale = "en"; // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets string countryCode = "FR"; string[] locations = { "Paris", "Quebec", "Spain", "Deutschland" }; SuggestGeoTargetConstantsRequest request = new SuggestGeoTargetConstantsRequest() { Locale = locale, CountryCode = countryCode, LocationNames = new SuggestGeoTargetConstantsRequest.Types.LocationNames() }; request.LocationNames.Names.AddRange(locations); try { SuggestGeoTargetConstantsResponse response = geoService.SuggestGeoTargetConstants(request); foreach (GeoTargetConstantSuggestion suggestion in response.GeoTargetConstantSuggestions) { Console.WriteLine( $"{suggestion.GeoTargetConstant.ResourceName} " + $"({suggestion.GeoTargetConstant.Name}, " + $"{suggestion.GeoTargetConstant.CountryCode}, " + $"{suggestion.GeoTargetConstant.TargetType}, " + $"{suggestion.GeoTargetConstant.Status}) is found in locale " + $"({suggestion.Locale}) with reach ({suggestion.Reach}) " + $"for search term ({suggestion.SearchTerm})."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } } }
PHP
<?php /** * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Google\Ads\GoogleAds\Examples\Targeting; 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\V17\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\V17\Enums\GeoTargetConstantStatusEnum\GeoTargetConstantStatus; use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V17\Services\GeoTargetConstantSuggestion; use Google\Ads\GoogleAds\V17\Services\SuggestGeoTargetConstantsRequest; use Google\Ads\GoogleAds\V17\Services\SuggestGeoTargetConstantsRequest\LocationNames; use Google\ApiCore\ApiException; /** * This code example gets geo target constants by given location names. */ class GetGeoTargetConstantsByNames { // Locale is using ISO 639-1 format. If an invalid locale is given, 'en' will be used by // default. private const LOCALE = 'en'; // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets. private const COUNTRY_CODE = 'FR'; // The location names to get suggested geo target constants. private static $LOCATION_NAMES = ['Paris', 'Quebec', 'Spain', 'Deutschland']; 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::LOCATION_NAMES => GetOpt::MULTIPLE_ARGUMENT, ArgumentNames::LOCALE => GetOpt::OPTIONAL_ARGUMENT, ArgumentNames::COUNTRY_CODE => GetOpt::OPTIONAL_ARGUMENT ]); // Generate a refreshable OAuth2 credential for authentication. $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClient = (new GoogleAdsClientBuilder()) ->fromFile() ->withOAuth2Credential($oAuth2Credential) // We set this value to true to show how to use GAPIC v2 source code. You can remove the // below line if you wish to use the old-style source code. Note that in that case, you // probably need to modify some parts of the code below to make it work. // For more information, see // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic. ->usingGapicV2Source(true) ->build(); try { self::runExample( $googleAdsClient, $options[ArgumentNames::LOCATION_NAMES] ?: self::$LOCATION_NAMES, $options[ArgumentNames::LOCALE] ?: self::LOCALE, $options[ArgumentNames::COUNTRY_CODE] ?: self::COUNTRY_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 array $locationNames the list of location names to get suggested geo target constants * @param string $locale the locale of the geo target constant to be retrieved * @param string $countryCode the country code of the geo target constant to be retrieved */ public static function runExample( GoogleAdsClient $googleAdsClient, array $locationNames, string $locale, string $countryCode ) { $geoTargetConstantServiceClient = $googleAdsClient->getGeoTargetConstantServiceClient(); $response = $geoTargetConstantServiceClient->suggestGeoTargetConstants( new SuggestGeoTargetConstantsRequest([ 'locale' => $locale, 'country_code' => $countryCode, 'location_names' => new LocationNames(['names' => $locationNames]) ]) ); // Iterates over all geo target constant suggestion objects and prints the requested field // values for each one. foreach ($response->getGeoTargetConstantSuggestions() as $geoTargetConstantSuggestion) { /** @var GeoTargetConstantSuggestion $geoTargetConstantSuggestion */ printf( "Found '%s' ('%s','%s','%s',%s) in locale '%s' with reach %d" . " for the search term '%s'.%s", $geoTargetConstantSuggestion->getGeoTargetConstant()->getResourceName(), $geoTargetConstantSuggestion->getGeoTargetConstant()->getName(), $geoTargetConstantSuggestion->getGeoTargetConstant()->getCountryCode(), $geoTargetConstantSuggestion->getGeoTargetConstant()->getTargetType(), GeoTargetConstantStatus::name( $geoTargetConstantSuggestion->getGeoTargetConstant()->getStatus() ), $geoTargetConstantSuggestion->getLocale(), $geoTargetConstantSuggestion->getReach(), $geoTargetConstantSuggestion->getSearchTerm(), PHP_EOL ); } } } GetGeoTargetConstantsByNames::main();
Python
#!/usr/bin/env python # Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This example illustrates getting GeoTargetConstants by given location names. """ import sys from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException # Locale is using ISO 639-1 format. If an invalid locale is given, # 'en' is used by default. LOCALE = "en" # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets COUNTRY_CODE = "FR" def main(client): gtc_service = client.get_service("GeoTargetConstantService") gtc_request = client.get_type("SuggestGeoTargetConstantsRequest") gtc_request.locale = LOCALE gtc_request.country_code = COUNTRY_CODE # The location names to get suggested geo target constants. gtc_request.location_names.names.extend( ["Paris", "Quebec", "Spain", "Deutschland"] ) results = gtc_service.suggest_geo_target_constants(gtc_request) for suggestion in results.geo_target_constant_suggestions: geo_target_constant = suggestion.geo_target_constant print( f"{geo_target_constant.resource_name} " f"({geo_target_constant.name}, " f"{geo_target_constant.country_code}, " f"{geo_target_constant.target_type}, " f"{geo_target_constant.status.name}) " f"is found in locale ({suggestion.locale}) " f"with reach ({suggestion.reach}) " f"from search term ({suggestion.search_term})." ) if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v17") try: main(googleads_client) 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:: Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This code example illustrates getting GeoTargetConstants by given # location names require 'optparse' require 'google/ads/google_ads' def get_geo_target_constants_by_names # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new gtc_service = client.service.geo_target_constant location_names = client.resource.location_names do |ln| ['Paris', 'Quebec', 'Spain', 'Deutschland'].each do |name| ln.names << name end end # Locale is using ISO 639-1 format. If an invalid locale is given, # 'en' is used by default. locale = 'en' # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets country_code = 'FR' response = gtc_service.suggest_geo_target_constants( locale: locale, country_code: country_code, location_names: location_names ) response.geo_target_constant_suggestions.each do |suggestion| puts sprintf("%s (%s,%s,%s,%s) is found in locale (%s) with reach (%d)" \ " from search term (%s).", suggestion.geo_target_constant.resource_name, suggestion.geo_target_constant.name, suggestion.geo_target_constant.country_code, suggestion.geo_target_constant.target_type, suggestion.geo_target_constant.status, suggestion.locale, suggestion.reach, suggestion.search_term) end end if __FILE__ == $PROGRAM_NAME options = {} # Running the example with -h will print the command line usage. OptionParser.new do |opts| opts.banner = sprintf('Usage: ruby %s ', File.basename(__FILE__)) opts.separator '' opts.separator 'Help:' opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end end.parse! begin get_geo_target_constants_by_names 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 gets geo target constants by given location names. 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::V17::Services::GeoTargetConstantService::LocationNames; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); # Locale is using ISO 639-1 format. If an invalid locale is given, 'en' will be # used by default. my $locale = "en"; # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets. my $country_code = "FR"; # The location names to get suggested geo target constants. my $location_names = ["Paris", "Quebec", "Spain", "Deutschland"]; sub get_geo_target_constants_by_names { my ($api_client, $location_names, $locale, $country_code) = @_; my $suggest_response = $api_client->GeoTargetConstantService()->suggest({ locale => $locale, countryCode => $country_code, locationNames => Google::Ads::GoogleAds::V17::Services::GeoTargetConstantService::LocationNames ->new({ names => $location_names })}); # Iterate over all geo target constant suggestion objects and print the requested # field values for each one. foreach my $geo_target_constant_suggestion ( @{$suggest_response->{geoTargetConstantSuggestions}}) { printf "Found '%s' ('%s','%s','%s',%s) in locale '%s' with reach %d" . " for the search term '%s'.\n", $geo_target_constant_suggestion->{geoTargetConstant}{resourceName}, $geo_target_constant_suggestion->{geoTargetConstant}{name}, $geo_target_constant_suggestion->{geoTargetConstant}{countryCode}, $geo_target_constant_suggestion->{geoTargetConstant}{targetType}, $geo_target_constant_suggestion->{geoTargetConstant}{status}, $geo_target_constant_suggestion->{locale}, $geo_target_constant_suggestion->{reach}, $geo_target_constant_suggestion->{searchTerm}; } return 1; } # 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); # Call the example. get_geo_target_constants_by_names($api_client, $location_names, $locale, $country_code); =pod =head1 NAME get_geo_target_constants_by_names =head1 DESCRIPTION This example gets geo target constants by given location names. =head1 SYNOPSIS get_geo_target_constants_by_names.pl [options] -help Show the help message. =cut