جاوا
// 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.
package com.google.ads.googleads.examples.campaignmanagement;
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.v17.common.AdTextAsset;
import com.google.ads.googleads.v17.common.PolicyTopicEntry;
import com.google.ads.googleads.v17.common.ResponsiveSearchAdInfo;
import com.google.ads.googleads.v17.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v17.enums.ServedAssetFieldTypeEnum.ServedAssetFieldType;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.errors.PolicyFindingErrorEnum.PolicyFindingError;
import com.google.ads.googleads.v17.resources.Ad;
import com.google.ads.googleads.v17.resources.AdGroupAd;
import com.google.ads.googleads.v17.services.AdGroupAdOperation;
import com.google.ads.googleads.v17.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v17.services.MutateAdGroupAdsRequest;
import com.google.ads.googleads.v17.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v17.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;
/**
* Shows how to use the validateOnly request parameter to validate a responsive search ad. No ads
* will be created, but exceptions will still be thrown.
*/
public class ValidateAd {
private static class ValidateAdParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
private Long adGroupId;
}
public static void main(String[] args) {
ValidateAdParams params = new ValidateAdParams();
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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_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 ValidateAd().runExample(googleAdsClient, params.customerId, params.adGroupId);
} 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.
* @param customerId the client customer ID.
* @param adGroupId the ad group ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {
String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);
// Creates the responsive search ad info.
ResponsiveSearchAdInfo responsiveSearchAdInfo =
ResponsiveSearchAdInfo.newBuilder()
.addAllHeadlines(
ImmutableList.of(
AdTextAsset.newBuilder()
.setText("Visit the Red Planet in style.")
.setPinnedField(ServedAssetFieldType.HEADLINE_1)
.build(),
AdTextAsset.newBuilder().setText("Low-gravity fun for everyone!").build(),
AdTextAsset.newBuilder().setText("Book your Cruise to Mars now!").build()))
.addAllDescriptions(
ImmutableList.of(
AdTextAsset.newBuilder().setText("Luxury Cruise to Mars").build(),
AdTextAsset.newBuilder().setText("Book your ticket now").build()))
.build();
// Wraps the info in an Ad object.
Ad ad =
Ad.newBuilder()
.setResponsiveSearchAd(responsiveSearchAdInfo)
.addFinalUrls("https://www.example.com")
.build();
// Builds the final ad group ad representation.
AdGroupAd adGroupAd =
AdGroupAd.newBuilder()
.setAdGroup(adGroupResourceName)
.setStatus(AdGroupAdStatus.PAUSED)
.setAd(ad)
.build();
AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
try (AdGroupAdServiceClient adGroupAdServiceClient =
googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
// Issues the mutate request setting validateOnly=true.
MutateAdGroupAdsResponse response =
adGroupAdServiceClient.mutateAdGroupAds(
MutateAdGroupAdsRequest.newBuilder()
.setCustomerId(String.valueOf(customerId))
.setCustomerId(Long.toString(customerId))
.addOperations(operation)
.setValidateOnly(true)
.build());
// This line will not be executed since the ad will fail validation.
System.out.println("Responsive search ad validated successfully.");
} catch (GoogleAdsException e) {
// This block will be hit if there is a validation error from the server.
System.out.println("There were validation error(s) while adding responsive search ad.");
// Note: Policy violation errors are returned as PolicyFindingErrors. See
// https://developers.google.com/google-ads/api/docs/policy-exemption/overview
// for additional details.
List<GoogleAdsError> policyFindingErrors =
e.getGoogleAdsFailure().getErrorsList().stream()
.filter(
err ->
err.getErrorCode().getPolicyFindingError()
== PolicyFindingError.POLICY_FINDING)
.collect(Collectors.toList());
if (!policyFindingErrors.isEmpty()) {
for (GoogleAdsError policyFindingError : policyFindingErrors) {
int count = 1;
if (policyFindingError.getDetails().hasPolicyFindingDetails()) {
List<PolicyTopicEntry> policyTopicEntries =
policyFindingError
.getDetails()
.getPolicyFindingDetails()
.getPolicyTopicEntriesList();
for (PolicyTopicEntry policyTopicEntry : policyTopicEntries) {
System.out.printf(
"%d Policy topic entries with topic '%s' and type '%s' found.%n",
count, policyTopicEntry.getTopic(), policyTopicEntry.getType());
}
count++;
}
}
}
} catch (Exception e) {
System.out.printf("Failure: Message '%s'.%n", e.getMessage());
System.exit(1);
}
}
}
سی شارپ
// 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.V17.Common;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V17.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.ServedAssetFieldTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Errors.PolicyFindingErrorEnum.Types;
namespace Google.Ads.GoogleAds.Examples.V17
{
/// <summary>
/// This code example shows how to use the validateOnly request parameter to validate a
/// responsive search ad.
/// No objects will be created, but exceptions will still be thrown.
/// </summary>
public class ValidateAd : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="ValidateAd"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the ad group to which ads are added.
/// </summary>
[Option("adGroupId", Required = true, HelpText =
"ID of the ad group to which ads are added.")]
public long AdGroupId { 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);
ValidateAd codeExample = new ValidateAd();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example shows how to use the validateOnly request parameter to validate " +
"a responsive search ad. No objects will be created, but exceptions will still be thrown.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
/// <param name="adGroupId">ID of the ad group to which ads are added.</param>
public void Run(GoogleAdsClient client, long customerId, long adGroupId)
{
// Get the AdGroupAdService.
AdGroupAdServiceClient adGroupAdService = client.GetService(
Services.V17.AdGroupAdService);
// Create the ad group ad object.
AdGroupAd adGroupAd = new AdGroupAd
{
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
// Optional: Set the status.
Status = AdGroupAdStatus.Paused,
Ad = new Ad
{
ResponsiveSearchAd = new ResponsiveSearchAdInfo
{
Headlines =
{
new AdTextAsset() {
Text = "Visit the Red Planet in style.",
PinnedField = ServedAssetFieldType.Headline1
},
new AdTextAsset() { Text = "Low-gravity fun for everyone!!" },
new AdTextAsset() { Text = "Book your Cruise to Mars now" }
},
Descriptions =
{
new AdTextAsset() { Text = "Luxury Cruise to Mars" },
new AdTextAsset() { Text = "Book your ticket now" }
}
},
FinalUrls = { "https://www.example.com/" },
}
};
// Create the operation.
AdGroupAdOperation operation = new AdGroupAdOperation
{
Create = adGroupAd
};
try
{
// Create the ads, while setting validateOnly = true.
MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
new MutateAdGroupAdsRequest()
{
CustomerId = customerId.ToString(),
Operations = { operation },
PartialFailure = false,
ValidateOnly = true
});
// This line will not be executed since the ad will fail validation.
Console.WriteLine("Responsive search ad validated successfully.");
}
catch (GoogleAdsException e)
{
// This block will be hit if there is a validation error from the server.
Console.WriteLine(
"There were validation error(s) while adding a responsive search ad.");
// Note: Policy violation errors are returned as PolicyFindingErrors. See
// https://developers.google.com/google-ads/api/docs/policy-exemption/overview
// for additional details.
List<GoogleAdsError> policyFindingErrors = e.Failure.Errors
.Where(
err => err.ErrorCode.PolicyFindingError == PolicyFindingError.PolicyFinding)
.ToList();
if (policyFindingErrors.Any())
{
policyFindingErrors.ForEach(delegate (GoogleAdsError err)
{
int count = 1;
if (err.Details.PolicyFindingDetails != null)
{
foreach (PolicyTopicEntry entry in
err.Details.PolicyFindingDetails.PolicyTopicEntries)
{
Console.WriteLine($"{count}) Policy topic entry with topic = " +
$"\"{entry.Topic}\" and type = \"{entry.Type}\" " +
$"found.");
count++;
}
}
});
}
else
{
// There were unexpected validation errors, rethrowing the exception
throw;
}
}
}
}
}
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\CampaignManagement;
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\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Common\AdTextAsset;
use Google\Ads\GoogleAds\V17\Common\PolicyTopicEntry;
use Google\Ads\GoogleAds\V17\Common\ResponsiveSearchAdInfo;
use Google\Ads\GoogleAds\V17\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V17\Enums\PolicyTopicEntryTypeEnum\PolicyTopicEntryType;
use Google\Ads\GoogleAds\V17\Enums\ServedAssetFieldTypeEnum\ServedAssetFieldType;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Errors\PolicyFindingErrorEnum\PolicyFindingError;
use Google\Ads\GoogleAds\V17\Resources\Ad;
use Google\Ads\GoogleAds\V17\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V17\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupAdsRequest;
use Google\ApiCore\ApiException;
/**
* This code example shows how to use the validateOnly header to validate
* a responsive search ad. No objects will be created, but exceptions will
* still be thrown.
*/
class ValidateAd
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_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::AD_GROUP_ID => 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::AD_GROUP_ID] ?: self::AD_GROUP_ID
);
} 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 customer ID
* @param int $adGroupId the ad group ID to validate the ad against
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $adGroupId
) {
// Creates the responsive search ad info.
$responsiveSearchAdInfo = new ResponsiveSearchAdInfo([
'headlines' => [
new AdTextAsset([
'text' => 'Visit the Red Planet in style.',
'pinned_field' => ServedAssetFieldType::HEADLINE_1
]),
// Adds a headline that will trigger a policy violation to demonstrate error
// handling.
new AdTextAsset(['text' => 'Low-gravity fun for everyone!!']),
new AdTextAsset(['text' => 'Book your Cruise to Mars now'])
],
'descriptions' => [
new AdTextAsset(['text' => 'Luxury Cruise to Mars']),
new AdTextAsset(['text' => 'Book your ticket now'])
]
]);
// Sets the responsive search ad info on an ad.
$ad = new Ad([
'responsive_search_ad' => $responsiveSearchAdInfo,
'final_urls' => ['https://www.example.com']
]);
// Creates an ad group ad to hold the above ad.
$adGroupAd = new AdGroupAd([
'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
// Optional: Set the status.
'status' => AdGroupAdStatus::PAUSED,
'ad' => $ad
]);
// Creates the ad group ad operation.
$adGroupAdOperation = new AdGroupAdOperation();
$adGroupAdOperation->setCreate($adGroupAd);
$adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
try {
// Try sending a mutate request to add the ad group ad.
$adGroupAdServiceClient->mutateAdGroupAds(
MutateAdGroupAdsRequest::build($customerId, [$adGroupAdOperation])
->setValidateOnly(true)
);
// This line will not be executed since the ad will fail validation.
printf("Responsive search ad validated successfully.%s", PHP_EOL);
} catch (GoogleAdsException $googleAdsException) {
// This block will be hit if there is a validation error from the server.
printf("There were validation error(s) while adding responsive search ad.%s", PHP_EOL);
// Note: Policy violation errors are returned as PolicyFindingErrors. See
// https://developers.google.com/google-ads/api/docs/policy-exemption/overview
// for additional details.
/** @var GoogleAdsError $googleAdsError */
$filteredGoogleAdsErrors = array_filter(
iterator_to_array($googleAdsException->getGoogleAdsFailure()->getErrors()),
function ($googleAdsError) {
/** @var GoogleAdsError $googleAdsError */
return $googleAdsError->getErrorCode()->getPolicyFindingError()
== PolicyFindingError::POLICY_FINDING;
}
);
if (!empty($filteredGoogleAdsErrors)) {
$count = 1;
foreach ($filteredGoogleAdsErrors as $googleAdsError) {
if (
$googleAdsError->getErrorCode()->getPolicyFindingError()
== PolicyFindingError::POLICY_FINDING
) {
$details = $googleAdsError->getDetails()->getPolicyFindingDetails();
if ($details) {
foreach ($details->getPolicyTopicEntries() as $entry) {
/** @var PolicyTopicEntry $entry */
printf(
"%d) Policy topic entry with topic '%s' and type '%s'"
. " was found.%s",
$count,
$entry->getTopic(),
PolicyTopicEntryType::name($entry->getType()),
PHP_EOL
);
$count++;
}
}
}
}
} else {
// There were unexpected validation errors, rethrowing the exception.
throw $googleAdsException;
}
}
}
}
ValidateAd::main();
پایتون
#!/usr/bin/env python
# Copyright 2022 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 shows use of the validate_only header when creating an ad.
Here we use a responsive search ad, but this approach can be used for any ad
type. No objects will be created in the given customer account, but exceptions
will still be thrown.
"""
import argparse
import sys
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, ad_group_id):
ad_group_ad_operation = client.get_type("AdGroupAdOperation")
ad_group_ad = ad_group_ad_operation.create
ad_group_service = client.get_service("AdGroupService")
ad_group_ad.ad_group = ad_group_service.ad_group_path(
customer_id, ad_group_id
)
ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED
ad_group_ad.ad.final_urls.append("http://www.example.com/")
# Create a responsive search ad.
headline_1 = client.get_type("AdTextAsset")
headline_1.text = "Visit the Red Planet in style."
headline_1.pinned_field = client.enums.ServedAssetFieldTypeEnum.HEADLINE_1
ad_group_ad.ad.responsive_search_ad.headlines.append(headline_1)
headline_2 = client.get_type("AdTextAsset")
headline_2.text = "An interplanetary adventure"
ad_group_ad.ad.responsive_search_ad.headlines.append(headline_2)
# Adds a headline that will trigger a policy violation to demonstrate
# error handling.
headline_3 = client.get_type("AdTextAsset")
headline_3.text = "Low-gravity fun for everyone!!"
ad_group_ad.ad.responsive_search_ad.headlines.append(headline_3)
description_1 = client.get_type("AdTextAsset")
description_1.text = "Luxury Cruise to Mars"
ad_group_ad.ad.responsive_search_ad.descriptions.append(description_1)
description_2 = client.get_type("AdTextAsset")
description_2.text = "Book your ticket now"
ad_group_ad.ad.responsive_search_ad.descriptions.append(description_2)
ad_group_ad_service = client.get_service("AdGroupAdService")
# Attempt the mutate with validate_only=True.
try:
request = client.get_type("MutateAdGroupAdsRequest")
request.customer_id = customer_id
request.operations.append(ad_group_ad_operation)
request.partial_failure = False
request.validate_only = True
# This request will trigger a POLICY_FINDING error, which is handled
# in the below except block.
ad_group_ad_service.mutate_ad_group_ads(request=request)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}".'
)
print(
"There may have been validation error(s) while adding responsive "
"search ad."
)
policy_error_enum = client.get_type(
"PolicyFindingErrorEnum"
).PolicyFindingError.POLICY_FINDING
count = 1
for error in ex.failure.errors:
# Note: Policy violation errors are returned as PolicyFindingErrors.
# For additional details, see
# https://developers.google.com/google-ads/api/docs/policy-exemption/overview
if error.error_code.policy_finding_error == policy_error_enum:
if error.details.policy_finding_details:
details = (
error.details.policy_finding_details.policy_topic_entries
)
for entry in details:
print(f"{count}) Policy topic entry: \n{entry}\n")
count += 1
else:
print(
f"\tNon-policy finding error with message "
f'"{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)
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Shows how to use the validate_only header to validate a "
"responsive search ad. No objects will be created, but exceptions "
"will still be thrown."
)
)
# 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(
"-a", "--ad_group_id", type=str, required=True, help="The Ad Group ID."
)
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="v17")
main(googleads_client, args.customer_id, args.ad_group_id)
روبی
#!/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 shows use of the validate_only header for a responsive search
# ad. No objects will be created, but exceptions will still be thrown.
require 'optparse'
require 'google/ads/google_ads'
def validate_ad(customer_id, ad_group_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
operation = client.operation.create_resource.ad_group_ad do |aga|
aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
aga.status = :PAUSED
aga.ad = client.resource.ad do |ad|
ad.final_urls << "http://www.example.com"
ad.responsive_search_ad = client.resource.responsive_search_ad_info do |rsa|
rsa.headlines += [
client.resource.ad_text_asset do |ata|
ata.text = "Visit the Red Planet in style."
ata.pinned_field = :HEADLINE_1
end,
client.resource.ad_text_asset do |ata|
# This field will produce a violation for excessive exclamation marks.
ata.text = "Low-gravity fun for everyone!!"
end,
client.resource.ad_text_asset do |ata|
ata.text = "Book your cruise to Mars now."
end,
]
rsa.descriptions += [
client.resource.ad_text_asset do |ata|
ata.text = "Luxury cruise to Mars."
end,
client.resource.ad_text_asset do |ata|
ata.text = "Book your ticket now"
end,
]
end
ad.final_urls << "https://www.example.com"
end
end
begin
response = client.service.ad_group_ad.mutate_ad_group_ads(
customer_id: customer_id,
operations: [operation],
validate_only: true,
)
puts "Responsive search ad validated successfully."
rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
# This code path will be reached if there is a validation error from the server.
e.failure.errors.each do |error|
if error.error_code.policy_finding_error == :POLICY_FINDING
error.details.policy_finding_details&.
policy_topic_entries.each_with_index do |entry, i|
puts "#{i + 1}) #{entry.to_json}"
end
else
puts "Non-policy finding with message: #{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
end
end
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[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'
OptionParser.new do |opts|
opts.banner = sprintf('Usage: add_campaigns.rb [options]')
opts.separator ''
opts.separator 'Options:'
opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
options[:customer_id] = v
end
opts.on('-A','--ad-group-id AD-GROUP-ID', String, 'Ad Group ID') do |v|
options[:ad_group_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
validate_ad(
options.fetch(:customer_id).tr("-", ""),
options.fetch(:ad_group_id),
)
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
پرل
#!/usr/bin/perl -w
#
# Copyright 2022, 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 shows how to use the validateOnly field to validate a responsive
# search ad. No objects will be created, but exceptions will still be returned.
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::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V17::Resources::Ad;
use Google::Ads::GoogleAds::V17::Common::AdTextAsset;
use Google::Ads::GoogleAds::V17::Common::ResponsiveSearchAdInfo;
use Google::Ads::GoogleAds::V17::Enums::AdGroupAdStatusEnum qw(PAUSED);
use Google::Ads::GoogleAds::V17::Enums::ServedAssetFieldTypeEnum qw(HEADLINE_1);
use Google::Ads::GoogleAds::V17::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
sub validate_ad {
my ($api_client, $customer_id, $ad_group_id) = @_;
# Create an ad group ad object.
my $ad_group_ad = Google::Ads::GoogleAds::V17::Resources::AdGroupAd->new({
adGroup => Google::Ads::GoogleAds::V17::Utils::ResourceNames::ad_group(
$customer_id, $ad_group_id
),
# Optional: Set the status.
status => PAUSED,
ad => Google::Ads::GoogleAds::V17::Resources::Ad->new({
responsiveSearchAd =>
Google::Ads::GoogleAds::V17::Common::ResponsiveSearchAdInfo->new({
headlines => [
Google::Ads::GoogleAds::V17::Common::AdTextAsset->new({
text => "Visit the Red Planet in style.",
pinnedField => HEADLINE_1
}
),
Google::Ads::GoogleAds::V17::Common::AdTextAsset->new({
text => "Low-gravity fun for everyone!!"
}
),
Google::Ads::GoogleAds::V17::Common::AdTextAsset->new({
text => "Book your Cruise to Mars now"
}
),
],
descriptions => [
Google::Ads::GoogleAds::V17::Common::AdTextAsset->new({
text => "Luxury Cruise to Mars"
}
),
Google::Ads::GoogleAds::V17::Common::AdTextAsset->new({
text => "Book your ticket now"
}
),
]}
),
finalUrls => ["https://www.example.com/"]})});
# Create an ad group ad operation.
my $ad_group_ad_operation =
Google::Ads::GoogleAds::V17::Services::AdGroupAdService::AdGroupAdOperation
->new({create => $ad_group_ad});
# Add the ad group ad, while setting validateOnly to "true".
my $response = $api_client->AdGroupAdService()->mutate({
customerId => $customer_id,
operations => [$ad_group_ad_operation],
partialFailure => "false",
validateOnly => "true"
});
if (not $response->isa("Google::Ads::GoogleAds::GoogleAdsException")) {
# This line will not be executed since the ad will fail validation.
print "Responsive search ad validated successfully.\n";
} else {
# This block will be hit if there is a validation error from the server.
print "There were validation error(s) while adding responsive search ad.\n";
# Note: Policy violation errors are returned as PolicyFindingErrors. See
# https://developers.google.com/google-ads/api/docs/policy-exemption/overview
# for additional details.
my $errors = $response->get_google_ads_failure()->{errors};
my @policy_violations = grep {
$_->{errorCode}{policyFindingError}
and $_->{errorCode}{policyFindingError} eq "POLICY_FINDING"
} @{$errors};
if (@policy_violations) {
my $count = 1;
foreach my $error (@policy_violations) {
foreach my $entry (
@{$error->{details}{policyFindingDetails}{policyTopicEntries}})
{
printf "%d) Policy topic entry with topic = '%s' and type = '%s' " .
"was found.\n", $count, $entry->{topic}, $entry->{type};
$count++;
}
}
} else {
# Die if there were unexpected validation errors.
die $response->get_message();
}
}
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(0);
my $customer_id = undef;
my $ad_group_id = undef;
# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id, "ad_group_id=i" => \$ad_group_id);
# 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, $ad_group_id);
# Call the example.
validate_ad($api_client, $customer_id =~ s/-//gr, $ad_group_id);
=pod
=head1 NAME
validate_ad
=head1 DESCRIPTION
This example shows how to use the validateOnly field to validate a responsive
search ad. No objects will be created, but exceptions will still be returned.
=head1 SYNOPSIS
validate_ad.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-ad_group_id The ad group ID to which ads are added.
=cut