広告カスタマイザでレスポンシブ検索広告を追加する

Java

// Copyright 2021 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.advancedoperations;

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.v11.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v11.services.AdGroupAdOperation;
import com.google.ads.googleads.v11.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v11.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v11.utils.ResourceNames;
import com.google.ads.googleads.v11.common.AdTextAsset;
import com.google.ads.googleads.v11.common.CustomizerValue;
import com.google.ads.googleads.v11.common.ResponsiveSearchAdInfo;
import com.google.ads.googleads.v11.enums.CustomizerAttributeTypeEnum.CustomizerAttributeType;
import com.google.ads.googleads.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.resources.Ad;
import com.google.ads.googleads.v11.resources.AdGroupAd;
import com.google.ads.googleads.v11.resources.CustomerCustomizer;
import com.google.ads.googleads.v11.resources.CustomizerAttribute;
import com.google.ads.googleads.v11.services.CustomerCustomizerOperation;
import com.google.ads.googleads.v11.services.CustomerCustomizerServiceClient;
import com.google.ads.googleads.v11.services.CustomizerAttributeOperation;
import com.google.ads.googleads.v11.services.CustomizerAttributeServiceClient;
import com.google.ads.googleads.v11.services.MutateCustomerCustomizersResponse;
import com.google.ads.googleads.v11.services.MutateCustomizerAttributesResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Adds a customizer attribute, links the customizer attribute to a customer, and then adds a
 * responsive search ad with a description using the ad customizer to the specified ad group.
 */
public class AddResponsiveSearchAdWithAdCustomizer {

  private static class AddResponsiveSearchAdWithAdCustomizerParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

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

    // The name of the customizer attribute to be used in the ad customizer, which must be unique.
    // To run this example multiple times, change this value or specify its corresponding argument.
    // Note that there is a limit for the number of enabled customizer attributes in one account,
    // so you shouldn't run this example more than necessary.
    // Visit
    // https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads?hl=en#rules_and_limitations
    // for details.
    //
    // Specify the customizer attribute name here or the default specified below will be used.
    @Parameter(names = ArgumentNames.CUSTOMIZER_ATTRIBUTE_NAME)
    private String customizerAttributeName = "Price";
  }

  public static void main(String[] args) {
    AddResponsiveSearchAdWithAdCustomizerParams params =
        new AddResponsiveSearchAdWithAdCustomizerParams();
    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");
      // Optional: To use a different customizer attribute name from the default ("Price"),
      // uncomment the line below and insert the desired customizer attribute name.
      // params.customizerAttributeName = "INSERT_CUSTOMIZER_ATTRIBUTE_NAME_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 AddResponsiveSearchAdWithAdCustomizer()
          .runExample(
              googleAdsClient, params.customerId, params.adGroupId, params.customizerAttributeName);
    } 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.
   * @param customizerAttributeName the customizer attribute name.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long adGroupId,
      String customizerAttributeName) {
    String customizerAttributeResourceName =
        createCustomizerAttribute(googleAdsClient, customerId, customizerAttributeName);
    linkCustomizerAttributeToCustomer(googleAdsClient, customerId, customizerAttributeResourceName);
    createResponsiveSearchAdWithCustomization(
        googleAdsClient, customerId, adGroupId, customizerAttributeName);
  }

  /** Creates a customizer attribute with the specified customizer attribute name. */
  private static String createCustomizerAttribute(
      GoogleAdsClient googleAdsClient, long customerId, String customizerAttributeName) {
    // Creates a customizer attribute with the specified name.
    CustomizerAttribute customizerAttribute =
        CustomizerAttribute.newBuilder()
            .setName(customizerAttributeName)
            // Specifies the type to be 'PRICE' so that we can dynamically customize the part of the
            // ad's description that is a price of a product/service we advertise.
            .setType(CustomizerAttributeType.PRICE)
            .build();
    // Creates a customizer attribute operation for creating a customizer attribute.
    CustomizerAttributeOperation operation =
        CustomizerAttributeOperation.newBuilder().setCreate(customizerAttribute).build();

    try (CustomizerAttributeServiceClient customizerAttributeServiceClient =
        googleAdsClient.getLatestVersion().createCustomizerAttributeServiceClient()) {
      // Issues a mutate request to add the customizer attribute and prints its information.
      MutateCustomizerAttributesResponse response =
          customizerAttributeServiceClient.mutateCustomizerAttributes(
              Long.toString(customerId), ImmutableList.of(operation));
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Added a customizer with resource name '%s'.%n", resourceName);
      return resourceName;
    }
  }

  /**
   * Links the customizer attribute to the customer by providing a value to be used in a responsive
   * search ad that will be created in a later step.
   */
  private static void linkCustomizerAttributeToCustomer(
      GoogleAdsClient googleAdsClient, long customerId, String customizerAttributeResourceName) {
    // Creates a customer customizer with the value to be used in the responsive search ad.
    CustomerCustomizer customerCustomizer =
        CustomerCustomizer.newBuilder()
            .setCustomizerAttribute(customizerAttributeResourceName)
            // Specify '100USD' as a text value. The ad customizer will dynamically replace the
            // placeholder with this value when the ad serves.
            .setValue(
                CustomizerValue.newBuilder()
                    .setType(CustomizerAttributeType.PRICE)
                    .setStringValue("100USD")
                    .build())
            .build();

    // Creates a customer customizer operation.
    CustomerCustomizerOperation operation =
        CustomerCustomizerOperation.newBuilder().setCreate(customerCustomizer).build();

    try (CustomerCustomizerServiceClient customerCustomizerServiceClient =
        googleAdsClient.getLatestVersion().createCustomerCustomizerServiceClient()) {
      // Issues a mutate request to add the customer customizer and prints its information.
      MutateCustomerCustomizersResponse response =
          customerCustomizerServiceClient.mutateCustomerCustomizers(
              Long.toString(customerId), ImmutableList.of(operation));
      System.out.printf(
          "Added a customer customizer with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }

  /** Creates a responsive search ad that uses the specified customizer attribute. */
  private static void createResponsiveSearchAdWithCustomization(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long adGroupId,
      String customizerAttributeName) {
    List<String> headlines =
        ImmutableList.of("Cruise to Mars", "Best Space Cruise Line", "Experience the Stars");
    List<AdTextAsset> headlineAssets =
        headlines.stream()
            .map(headline -> AdTextAsset.newBuilder().setText(headline).build())
            .collect(Collectors.toList());
    List<String> descriptions =
        ImmutableList.of(
            "Buy your tickets now",
            // Creates this particular description using the ad customizer.
            // Visit
            // https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
            // for details about the placeholder format.
            // The ad customizer replaces the placeholder with the value we previously
            // created and linked to the customer using CustomerCustomizer.
            String.format("Just {CUSTOMIZER.%s:10USD}", customizerAttributeName));
    List<AdTextAsset> descriptionAssets =
        descriptions.stream()
            .map(description -> AdTextAsset.newBuilder().setText(description).build())
            .collect(Collectors.toList());

    // Creates an ad and sets responsive search ad info.
    Ad ad =
        Ad.newBuilder()
            .setResponsiveSearchAd(
                ResponsiveSearchAdInfo.newBuilder()
                    .addAllHeadlines(headlineAssets)
                    .addAllDescriptions(descriptionAssets)
                    .setPath1("all-inclusive")
                    .setPath2("deals")
                    .build())
            .addAllFinalUrls(ImmutableList.of("http://www.example.com"))
            .build();

    // Creates an ad group ad to hold the above ad.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(ResourceNames.adGroup(customerId, adGroupId))
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(ad)
            .build();

    // Creates an ad group ad operation.
    AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      // Issues a mutate request to add the ad group ad and prints its information.
      MutateAdGroupAdsResponse response =
          adGroupAdServiceClient.mutateAdGroupAds(
              Long.toString(customerId), ImmutableList.of(operation));
      System.out.printf(
          "Created a responsive search ad with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

C#

// Copyright 2021 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.Util;
using Google.Ads.GoogleAds.V11.Common;
using Google.Ads.GoogleAds.V11.Enums;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using Google.Protobuf;
using System.Collections.Generic;
using System.Linq;
using System;
using static Google.Ads.GoogleAds.V11.Enums.AdGroupTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AdvertisingChannelSubTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AssetFieldTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AssetGroupStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AssetTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.BiddingStrategyTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.BudgetTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.CriterionTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.CustomizerAttributeTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.MediaTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Services.SmartCampaignSuggestionInfo.Types;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// Adds a customizer attribute, links the customizer attribute to a customer, and then adds
    /// a responsive search ad with a description using the ad customizer to the specified ad group.
    /// </summary>
    public class AddResponsiveSearchAdWithAdCustomizer : ExampleBase
    {
        /// <summary>
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The Google Ads ad group ID.
            /// </summary>
            [Option("adGroupId", Required = true, HelpText =
                "The Google Ads ad group ID.")]
            public long AdGroupId { get; set; }

            /// <summary>
            /// The Google Ads customizer attribute name ID.
            /// </summary>
            [Option("customizerAttributeName", Required = false, HelpText =
                "The Google Ads customizer attribute name.", Default = CUSTOMIZER_ATTRIBUTE_NAME)]
            public string CustomizerAttributeName { 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);

            AddResponsiveSearchAdWithAdCustomizer codeExample =
                new AddResponsiveSearchAdWithAdCustomizer();

            Console.WriteLine(codeExample.Description);

            codeExample.Run(
                new GoogleAdsClient(),
                options.CustomerId,
                options.AdGroupId,
                options.CustomizerAttributeName
            );
        }

        // The name of the customizer attribute to be used in the ad customizer must be unique for a
        // given client account. To run this example multiple times, change this value or specify its
        // corresponding argument. Note that there is a limit for the number of enabled customizer
        // attributes in one account, so you shouldn't run this example more than necessary.
        //
        // Visit the following link for more details:
        // https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#rules_and_limitations
        private const string CUSTOMIZER_ATTRIBUTE_NAME = "Price";

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "Adds a customizer attribute, links the customizer attribute to a customer, and then " +
            "adds a responsive search ad with a description using the ad customizer to the " +
            "specified ad group.";

        /// <summary>
        /// Runs the example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="adGroupId">The Google Ads ad group ID.</param>
        /// <param name="customizerAttributeName">The customizer attribute name.</param>
        public void Run(
                GoogleAdsClient client,
                long customerId,
                long adGroupId,
                string customizerAttributeName)
        {
            string customizerAttributeResourceName = CreateCustomizerAttribute(
                client,
                customerId,
                customizerAttributeName
            );

            LinkCustomizerAttributeToCustomer(client, customerId, customizerAttributeResourceName);

            CreateResponsiveSearchAdWithCustomization(
                client,
                customerId,
                adGroupId,
                customizerAttributeName
            );
        }

        /// <summary>
        /// Creates a customizer attribute with the specified customizer attribute name.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The customer ID.</param>
        /// <param name="customizerAttributeName">The name of the customizer attribute.</param>
        /// <returns>The created customizer attribute resource name.</returns>
        private string CreateCustomizerAttribute(
            GoogleAdsClient client,
            long customerId,
            string customizerAttributeName)
        {
            // Creates a customizer attribute operation for creating a customizer attribute.
            CustomizerAttributeOperation operation = new CustomizerAttributeOperation() {
                // Creates a customizer attribute with the specified name.
                Create = new CustomizerAttribute() {
                    Name = customizerAttributeName,

                    // Specifies the type to be 'PRICE' so that we can dynamically customize the part of
                    // the ad's description that is a price of a product/service we advertise.
                    Type = CustomizerAttributeType.Price
                }
            };

            CustomizerAttributeServiceClient serviceClient =
                client.GetService(Services.V11.CustomizerAttributeService);

            // Issues a mutate request to add the customizer attribute and prints its information.
            MutateCustomizerAttributesResponse response =
                serviceClient.MutateCustomizerAttributes(
                    customerId.ToString(),
                    new [] { operation }.ToList()
                );

            string resourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Added a customizer attribute with resource name '{resourceName}'.");

            return resourceName;
        }

        /// <summary>
        /// Links the customizer attribute to the customer by providing a value to be used in a
        /// responsive search ad that will be created in a later step.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The customer ID.</param>
        /// <param name="customizerAttributeResourceName">The resource name of the customizer
        /// attribute.</param>
        private void LinkCustomizerAttributeToCustomer(
            GoogleAdsClient client,
            long customerId,
            string customizerAttributeResourceName)
        {
            // Creates a customer customizer operation.
            CustomerCustomizerOperation operation = new CustomerCustomizerOperation() {
                // Creates a customer customizer with the value to be used in the responsive search
                // ad.
                Create = new CustomerCustomizer() {
                    CustomizerAttribute = customizerAttributeResourceName,

                    Value = new CustomizerValue() {
                        Type = CustomizerAttributeType.Price,

                        // Specify '100USD' as a text value. The ad customizer will dynamically
                        // replace the placeholder with this value when the ad serves.
                        StringValue = "100USD"
                    }
                }
            };

            CustomerCustomizerServiceClient serviceClient =
                client.GetService(Services.V11.CustomerCustomizerService);

            // Issues a mutate request to add the customer customizer and prints its information.
            MutateCustomerCustomizersResponse response =
                serviceClient.MutateCustomerCustomizers(
                    customerId.ToString(),
                    new [] { operation }.ToList()
                );

            string resourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Added a customer customizer with resource name '{resourceName}'.");
        }

        /// <summary>
        /// Creates a responsive search ad that uses the specified customizer attribute.
        /// </summary>
        /// <param name="client">The Google Ads API client.</param>
        /// <param name="customerId">The customer ID.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <param name="customizerAttributeName">The name of the customizer attribute.</param>
        private void CreateResponsiveSearchAdWithCustomization(
            GoogleAdsClient client,
            long customerId,
            long adGroupId,
            string customizerAttributeName)
        {
            // Creates an ad group ad operation.
            AdGroupAdOperation operation = new AdGroupAdOperation() {

                // Creates an ad group ad to hold the ad.
                Create = new AdGroupAd() {

                    AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                    Status = AdGroupAdStatus.Paused,

                    // Creates an ad and sets responsive search ad info.
                    Ad = new Ad() {

                        ResponsiveSearchAd = new ResponsiveSearchAdInfo() {
                            Headlines =
                            {
                                // Sets a pinning to always choose this asset for HEADLINE_1. Pinning is
                                // optional; if no pinning is set, then headlines and descriptions will be
                                // rotated and the ones that perform best will be used more often.
                                new AdTextAsset() { Text = "Cruise to Mars" },
                                new AdTextAsset() { Text = "Best Space Cruise Line" },
                                new AdTextAsset() { Text = "Experience the Stars" }
                            },

                            Descriptions =
                            {
                                new AdTextAsset() { Text = "Buy your tickets now" },

                                // Creates this particular description using the ad customizer. For
                                // details about the placeholder format, visit the following:
                                // https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
                                //
                                // The ad customizer replaces the placeholder with the value we
                                // previously created and linked to the customer using
                                // `CustomerCustomizer`.
                                new AdTextAsset()
                                {
                                    Text = $"Just {{CUSTOMIZER.{customizerAttributeName}:10USD}}"
                                }
                            },

                            Path1 = "all-inclusive",
                            Path2 = "deals"
                        },

                        FinalUrls = { "http://www.example.com" }
                    }
                }
            };

            // Issues a mutate request to add the ad group ad and prints its information.
            AdGroupAdServiceClient serviceClient = client.GetService(Services.V11.AdGroupAdService);

            MutateAdGroupAdsResponse response = serviceClient.MutateAdGroupAds(
                customerId.ToString(),
                new [] { operation }.ToList()
            );

            string resourceName = response.Results[0].ResourceName;

            Console.WriteLine($"Created responsive search ad with resource name '{resourceName}'.");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2021 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\AdvancedOperations;

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\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V11\ResourceNames;
use Google\Ads\GoogleAds\V11\Common\AdTextAsset;
use Google\Ads\GoogleAds\V11\Common\CustomizerValue;
use Google\Ads\GoogleAds\V11\Common\ResponsiveSearchAdInfo;
use Google\Ads\GoogleAds\V11\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V11\Enums\CustomizerAttributeTypeEnum\CustomizerAttributeType;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Resources\Ad;
use Google\Ads\GoogleAds\V11\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V11\Resources\CustomerCustomizer;
use Google\Ads\GoogleAds\V11\Resources\CustomizerAttribute;
use Google\Ads\GoogleAds\V11\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V11\Services\CustomerCustomizerOperation;
use Google\Ads\GoogleAds\V11\Services\CustomizerAttributeOperation;
use Google\ApiCore\ApiException;

/**
 * Adds a customizer attribute, links the customizer attribute to a customer, and then adds
 * a responsive search ad with a description using the ad customizer to the specified ad group.
 */
class AddResponsiveSearchAdWithAdCustomizer
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

    // The name of the customizer attribute to be used in the ad customizer, which must be unique.
    // To run this example multiple times, change this value or specify its corresponding argument.
    // Note that there is a limit for the number of enabled customizer attributes in one account,
    // so you shouldn't run this example more than necessary.
    // Visit https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#rules_and_limitations
    // for details.
    private const CUSTOMIZER_ATTRIBUTE_NAME = 'Price';

    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,
            ArgumentNames::CUSTOMIZER_ATTRIBUTE_NAME => 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)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_ID,
                $options[ArgumentNames::CUSTOMIZER_ATTRIBUTE_NAME]
                    ?: self::CUSTOMIZER_ATTRIBUTE_NAME
            );
        } 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
     * @param string $customizerAttributeName the customizer attribute name
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId,
        string $customizerAttributeName
    ) {
        $customizerAttributeResourceName = self::createCustomizerAttribute(
            $googleAdsClient,
            $customerId,
            $customizerAttributeName
        );
        self::linkCustomizerAttributeToCustomer(
            $googleAdsClient,
            $customerId,
            $customizerAttributeResourceName
        );
        self::createResponsiveSearchAdWithCustomization(
            $googleAdsClient,
            $customerId,
            $adGroupId,
            $customizerAttributeName
        );
    }

    /**
     * Creates a customizer attribute with the specified customizer attribute name.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $customizerAttributeName the name of the customizer attribute
     * @return string the created customizer attribute resource name
     */
    private static function createCustomizerAttribute(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $customizerAttributeName
    ) {
        // Creates a customizer attribute with the specified name.
        $customizerAttribute = new CustomizerAttribute([
            'name' => $customizerAttributeName,
            // Specifies the type to be 'PRICE' so that we can dynamically customize the part of
            // the ad's description that is a price of a product/service we advertise.
            'type' => CustomizerAttributeType::PRICE
        ]);

        // Creates a customizer attribute operation for creating a customizer attribute.
        $operation = new CustomizerAttributeOperation();
        $operation->setCreate($customizerAttribute);

        // Issues a mutate request to add the customizer attribute and prints its information.
        $customizerAttributeServiceClient = $googleAdsClient->getCustomizerAttributeServiceClient();
        $response = $customizerAttributeServiceClient->mutateCustomizerAttributes(
            $customerId,
            [$operation]
        );
        $customizerAttributeResourceName = $response->getResults()[0]->getResourceName();
        printf(
            "Added a customizer attribute with resource name '%s'.%s",
            $customizerAttributeResourceName,
            PHP_EOL
        );

        return $customizerAttributeResourceName;
    }

    /**
     * Links the customizer attribute to the customer by providing a value to be used in a
     * responsive search ad that will be created in a later step.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $customizerAttributeResourceName the customizer attribute resource name
     */
    private static function linkCustomizerAttributeToCustomer(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $customizerAttributeResourceName
    ) {
        // Creates a customer customizer with the value to be used in the responsive search ad.
        $customerCustomizer = new CustomerCustomizer([
            'customizer_attribute' => $customizerAttributeResourceName,
            // Specify '100USD' as a text value. The ad customizer will dynamically replace the
            // placeholder with this value when the ad serves.
            'value' => new CustomizerValue([
                'type' => CustomizerAttributeType::PRICE,
                'string_value' => '100USD'
            ])
        ]);

        // Creates a customer customizer operation.
        $operation = new CustomerCustomizerOperation();
        $operation->setCreate($customerCustomizer);

        // Issues a mutate request to add the customer customizer and prints its information.
        $customerCustomizerServiceClient = $googleAdsClient->getCustomerCustomizerServiceClient();
        $response = $customerCustomizerServiceClient->mutateCustomerCustomizers(
            $customerId,
            [$operation]
        );
        printf(
            "Added a customer customizer with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Creates a responsive search ad that uses the specified customizer attribute.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param int $adGroupId the ad group ID in which to create the ad
     * @param string $customizerAttributeName the name of the customizer attribute
     */
    private static function createResponsiveSearchAdWithCustomization(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId,
        string $customizerAttributeName
    ) {
        // Creates an ad and sets responsive search ad info.
        $ad = new Ad([
            'responsive_search_ad' => new ResponsiveSearchAdInfo([
                'headlines' => [
                    new AdTextAsset(['text' => 'Cruise to Mars']),
                    new AdTextAsset(['text' => 'Best Space Cruise Line']),
                    new AdTextAsset(['text' => 'Experience the Stars'])
                ],
                'descriptions' => [
                    new AdTextAsset(['text' => 'Buy your tickets now']),
                    // Creates this particular description using the ad customizer.
                    // Visit https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
                    // for details about the placeholder format.
                    // The ad customizer replaces the placeholder with the value we previously
                    // created and linked to the customer using `CustomerCustomizer`.
                    new AdTextAsset(['text' => "Just {CUSTOMIZER.$customizerAttributeName:10USD}"])
                ],
                'path1' => 'all-inclusive',
                'path2' => 'deals'
            ]),
            'final_urls' => ['http://www.example.com']
        ]);

        // Creates an ad group ad to hold the above ad.
        $adGroupAd = new AdGroupAd([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            'status' => AdGroupAdStatus::PAUSED,
            'ad' => $ad
        ]);

        // Creates an ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);

        // Issues a mutate request to add the ad group ad and prints its information.
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
        $response = $adGroupAdServiceClient->mutateAdGroupAds($customerId, [$adGroupAdOperation]);
        printf(
            "Created responsive search ad with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

AddResponsiveSearchAdWithAdCustomizer::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.
"""Adds a customizer attribute.

Also links the customizer attribute to a customer, and then adds a responsive
search ad with a description using the ad customizer to the specified ad group.

Customizer attributes and ad group customizers are created for business data
customizers. For more information about responsive search ad customization see:
https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads?hl=en
"""


import argparse
from datetime import date, timedelta
import sys
from uuid import uuid4

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

# The name of the customizer attribute to be used in the ad customizer, which
# must be unique for a given customer account. To run this example multiple
# times, specify a unique value as a command line argument. Note that there is
# a limit for the number of enabled customizer attributes in one account, so
# you shouldn't run this example more than necessary. For more details visit:
# https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#rules_and_limitations
_CUSTOMIZER_ATTRIBUTE_NAME = "Price"


def main(client, customer_id, ad_group_id, customizer_attribute_name):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        ad_group_id: an ad group ID.
        customizer_attribute_name: the name for the customizer attribute.
    """
    customizer_attribute_resource_name = _create_customizer_attribute(
        client, customer_id, customizer_attribute_name
    )

    _link_customizer_attribute_to_customer(
        client, customer_id, customizer_attribute_resource_name
    )

    _create_responsive_search_ad_with_customization(
        client, customer_id, ad_group_id, customizer_attribute_name
    )


def _create_customizer_attribute(
    client, customer_id, customizer_attribute_name
):
    """Creates a customizer attribute with the given customizer attribute name.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        customizer_attribute_name: the name for the customizer attribute.

    Returns:
        A resource name for a customizer attribute.
    """
    # Creates a customizer attribute operation for creating a customizer
    # attribute.
    operation = client.get_type("CustomizerAttributeOperation")
    # Creates a customizer attribute with the specified name.
    customizer_attribute = operation.create
    customizer_attribute.name = customizer_attribute_name
    # Specifies the type to be 'PRICE' so that we can dynamically customize the
    # part of the ad's description that is a price of a product/service we
    # advertise.
    customizer_attribute.type_ = client.enums.CustomizerAttributeTypeEnum.PRICE

    # Issues a mutate request to add the customizer attribute and prints its
    # information.
    customizer_attribute_service = client.get_service(
        "CustomizerAttributeService"
    )
    response = customizer_attribute_service.mutate_customizer_attributes(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name

    print(f"Added a customizer attribute with resource name: '{resource_name}'")

    return resource_name


def _link_customizer_attribute_to_customer(
    client, customer_id, customizer_attribute_resource_name
):
    """Links the customizer attribute to the customer.

    This is done by providing a value to be used in a responsive search ad
    that will be created in a later step.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        customizer_attribute_resource_name: a resource name for  customizer
            attribute.
    """
    # Creates a customer customizer operation.
    operation = client.get_type("CustomerCustomizerOperation")
    # Creates a customer customizer with the value to be used in the responsive
    # search ad.
    customer_customizer = operation.create
    customer_customizer.customizer_attribute = (
        customizer_attribute_resource_name
    )
    customer_customizer.value.type_ = (
        client.enums.CustomizerAttributeTypeEnum.PRICE
    )
    # Specify '100USD' as a text value. The ad customizer will dynamically
    # replace the placeholder with this value when the ad serves.
    customer_customizer.value.string_value = "100USD"

    customer_customizer_service = client.get_service(
        "CustomerCustomizerService"
    )
    # Issues a mutate request to add the customer customizer and prints its
    # information.
    response = customer_customizer_service.mutate_customer_customizers(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name

    print(f"Added a customer customizer with resource name: '{resource_name}'")


def _create_responsive_search_ad_with_customization(
    client, customer_id, ad_group_id, customizer_attribute_name
):
    """Creates a responsive search ad using the specified customizer attribute.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        ad_group_id: an ad group ID.
        customizer_attribute_name: the name for the customizer attribute.
    """
    # Creates an ad group ad operation.
    operation = client.get_type("AdGroupAdOperation")
    # Creates an 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
    #  Creates an ad and sets responsive search ad info.
    ad = ad_group_ad.ad
    ad.final_urls.append("http://www.example.com")

    headline_1 = client.get_type("AdTextAsset")
    headline_1.text = "Cruise to Mars"
    headline_2 = client.get_type("AdTextAsset")
    headline_2.text = "Best Space Cruise Line"
    headline_3 = client.get_type("AdTextAsset")
    headline_3.text = "Experience the Stars"
    ad.responsive_search_ad.headlines.extend(
        [headline_1, headline_2, headline_3]
    )

    description_1 = client.get_type("AdTextAsset")
    description_1.text = "Buy your tickets now"
    # Creates this particular description using the ad customizer. Visit
    # https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
    # for details about the placeholder format. The ad customizer replaces the
    # placeholder with the value we previously created and linked to the
    # customer using CustomerCustomizer.
    description_2 = client.get_type("AdTextAsset")
    description_2.text = (
        f"Just {{CUSTOMIZER.{customizer_attribute_name}:10USD}}"
    )
    ad.responsive_search_ad.descriptions.extend([description_1, description_2])

    ad.responsive_search_ad.path1 = "all-inclusive"
    ad.responsive_search_ad.path2 = "deals"

    # Issues a mutate request to add the ad group ad and prints its information.
    ad_group_ad_service = client.get_service("AdGroupAdService")
    response = ad_group_ad_service.mutate_ad_group_ads(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name

    print(f"Created responsive search ad with resource name: '{resource_name}'")


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="v11")

    parser = argparse.ArgumentParser(
        description=(
            "Creates ad customizers and applies them to a responsive search ad."
        )
    )
    # 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="An ad group ID.",
    )
    parser.add_argument(
        "-n",
        "--customizer_attribute_name",
        type=str,
        default=_CUSTOMIZER_ATTRIBUTE_NAME,
        help=(
            "The name of the customizer attribute to be created. The name must "
            "be unique across a single client account, so be sure not to use "
            "the same value more than once."
        ),
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.ad_group_id,
            args.customizer_attribute_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'Error 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 2021 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.
#
# Adds a customizer attribute, links the customizer attribute to a customer,
# and then adds a responsive search ad with a description using the ad
# customizer to the specified ad group.

require 'google/ads/google_ads'
require 'optparse'

def add_responsive_search_ad_with_ad_customizer(customer_id,
      ad_group_id, customizer_attribute_name)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  customizer_attribute_resource_name = create_customizer_attribute(
    client,
    customer_id,
    customizer_attribute_name,
  )

  link_customizer_attribute_to_customer(
    client,
    customer_id,
    customizer_attribute_resource_name,
  )

  create_responsive_search_ad_with_customization(
    client,
    customer_id,
    ad_group_id,
    customizer_attribute_name,
  )
end

def create_customizer_attribute(client, customer_id, attribute_name)
  operation = client.operation.create_resource.customizer_attribute do |ca|
    ca.name = attribute_name
    ca.type = :PRICE
  end

  response = client.service.customizer_attribute.mutate_customizer_attributes(
    customer_id: customer_id,
    operations: [operation],
  )

  resource_name = response.results.first.resource_name
  puts "Created a customizer attribute with resource name #{resource_name}."

  resource_name
end

def link_customizer_attribute_to_customer(client, customer_id, resource_name)
  operation = client.operation.create_resource.customer_customizer do |cc|
    cc.customizer_attribute = resource_name
    cc.value = client.resource.customizer_value do |cv|
      cv.type = :PRICE
      cv.string_value = '100USD'
    end
  end

  response = client.service.customer_customizer.mutate_customer_customizers(
    customer_id: customer_id,
    operations: [operation],
  )

  puts "Created a customer customizer with resource name #{response.results.first.resource_name}."
end

def create_responsive_search_ad_with_customization(client, customer_id, ad_group_id, attribute_name)
  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.responsive_search_ad = client.resource.responsive_search_ad_info do |rsa|
        rsa.headlines << client.resource.ad_text_asset do |asset|
          asset.text = 'Cruise to Mars'
        end
        rsa.headlines << client.resource.ad_text_asset do |asset|
          asset.text = 'Best Space Cruise Line'
        end
        rsa.headlines << client.resource.ad_text_asset do |asset|
          asset.text = 'Experience the Stars'
        end

        rsa.descriptions << client.resource.ad_text_asset do |asset|
          asset.text = 'Buy your tickets now'
        end
        rsa.descriptions << client.resource.ad_text_asset do |asset|
          # Creates this particular description using the ad customizer.  Visit
          # https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
          # for details about the placeholder format.  The ad customizer
          # replaces the placeholder with the value we previously created and
          # linked to the customer using `CustomerCustomizer`.
          asset.text = "Just {CUSTOMIZER.#{attribute_name}:10USD}"
        end

        rsa.path1 = 'all-inclusive'
        rsa.path2 = 'deals'
      end

      ad.final_urls << 'http://www.example.com'
    end
  end

  response = client.service.ad_group_ad.mutate_ad_group_ads(
    customer_id: customer_id,
    operations: [operation],
  )

  puts "Created responsive search ad with resource name #{response.results.first.resource_name}."
end

if __FILE__ == $0
  options = {}
  DEFAULT_CUSTOMIZER_ATTRIBUTE_NAME = 'Price'

  # 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'
  options[:customizer_attribute_name] = nil

  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('-A', '--ad-group-id AD-GROUP-ID', String, "AdGroup ID") do |v|
      options[:ad_group_id] = v
    end

    opts.on('-n', '--customizer-attribute-name CUSTOMIZER-ATTRIBUTE-NAME',
            String, "Customizer Attribute Name") do |v|
      options[:customizer_attribute_name] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!
  if options[:customizer_attribute_name].nil?
    options[:customizer_attribute_name] = DEFAULT_CUSTOMIZER_ATTRIBUTE_NAME
  end

  begin
    add_responsive_search_ad_with_ad_customizer(
      options.fetch(:customer_id).tr("-", ""),
      options[:ad_group_id],
      options[:customizer_attribute_name],
    )
  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 2021, 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.
#
# Adds a customizer attribute, links the customizer attribute to a customer, and
# then adds a responsive search ad with a description using the ad customizer to
# the specified ad group.

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::V11::Resources::CustomizerAttribute;
use Google::Ads::GoogleAds::V11::Resources::CustomerCustomizer;
use Google::Ads::GoogleAds::V11::Resources::Ad;
use Google::Ads::GoogleAds::V11::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V11::Common::CustomizerValue;
use Google::Ads::GoogleAds::V11::Common::ResponsiveSearchAdInfo;
use Google::Ads::GoogleAds::V11::Common::TextAsset;
use Google::Ads::GoogleAds::V11::Enums::CustomizerAttributeTypeEnum qw(PRICE);
use Google::Ads::GoogleAds::V11::Enums::AdGroupAdStatusEnum qw(PAUSED);
use
  Google::Ads::GoogleAds::V11::Services::CustomizerAttributeService::CustomizerAttributeOperation;
use
  Google::Ads::GoogleAds::V11::Services::CustomerCustomizerService::CustomerCustomizerOperation;
use Google::Ads::GoogleAds::V11::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V11::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 $ad_group_id = "INSERT_AD_GROUP_ID_HERE";
# The name of the customizer attribute to be used in the ad customizer, which must
# be unique. To run this example multiple times, change this value or specify its
# corresponding argument.
# Note that there is a limit for the number of enabled customizer attributes in
# one account, so you shouldn't run this example more than necessary.
# Visit https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#rules_and_limitations
# for details.
my $customizer_attribute_name = "Price";

sub add_responsive_search_ad_with_ad_customizer {
  my ($api_client, $customer_id, $ad_group_id, $customizer_attribute_name) = @_;

  my $customizer_attribute_resource_name =
    create_customizer_attribute($api_client, $customer_id,
    $customizer_attribute_name);

  link_customizer_attribute_to_customer($api_client, $customer_id,
    $customizer_attribute_resource_name);

  create_responsive_search_ad_with_customization($api_client, $customer_id,
    $ad_group_id, $customizer_attribute_name);

  return 1;
}

# Creates a customizer attribute with the specified customizer attribute name.
sub create_customizer_attribute {
  my ($api_client, $customer_id, $customizer_attribute_name) = @_;

  # Create a customizer attribute with the specified name.
  my $customizer_attribute =
    Google::Ads::GoogleAds::V11::Resources::CustomizerAttribute->new({
      name => $customizer_attribute_name,
      # Specify the type to be 'PRICE' so that we can dynamically customize the part
      # of the ad's description that is a price of a product/service we advertise.
      type => PRICE
    });

  # Create a customizer attribute operation for creating a customizer attribute.
  my $operation =
    Google::Ads::GoogleAds::V11::Services::CustomizerAttributeService::CustomizerAttributeOperation
    ->new({
      create => $customizer_attribute
    });

  # Issue a mutate request to add the customizer attribute and print its information.
  my $response = $api_client->CustomizerAttributeService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});
  my $customizer_attribute_resource_name =
    $response->{results}[0]{resourceName};
  printf "Added a customizer attribute with resource name '%s'.\n",
    $customizer_attribute_resource_name;

  return $customizer_attribute_resource_name;
}

# Links the customizer attribute to the customer by providing a value to be used
# in a responsive search ad that will be created in a later step.
sub link_customizer_attribute_to_customer {
  my ($api_client, $customer_id, $customizer_attribute_resource_name) = @_;

  # Create a customer customizer with the value to be used in the responsive search ad.
  my $customer_customizer =
    Google::Ads::GoogleAds::V11::Resources::CustomerCustomizer->new({
      customizerAttribute => $customizer_attribute_resource_name,
      # Specify '100USD' as a text value. The ad customizer will dynamically replace
      # the placeholder with this value when the ad serves.
      value => Google::Ads::GoogleAds::V11::Common::CustomizerValue->new({
          type        => PRICE,
          stringValue => "100USD"
        })});

  # Create a customer customizer operation.
  my $operation =
    Google::Ads::GoogleAds::V11::Services::CustomerCustomizerService::CustomerCustomizerOperation
    ->new({
      create => $customer_customizer
    });

  # Issue a mutate request to add the customer customizer and print its information.
  my $response = $api_client->CustomerCustomizerService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});
  printf "Added a customer customizer with resource name '%s'.\n",
    $response->{results}[0]{resourceName};
}

# Creates a responsive search ad that uses the specified customizer attribute.
sub create_responsive_search_ad_with_customization {
  my ($api_client, $customer_id, $ad_group_id, $customizer_attribute_name) = @_;

  # Create an ad and set responsive search ad info.
  my $ad = Google::Ads::GoogleAds::V11::Resources::Ad->new({
      responsiveSearchAd =>
        Google::Ads::GoogleAds::V11::Common::ResponsiveSearchAdInfo->new({
          headlines => [
            Google::Ads::GoogleAds::V11::Common::TextAsset->new({
                text => "Cruise to Mars"
              }
            ),
            Google::Ads::GoogleAds::V11::Common::TextAsset->new({
                text => "Best Space Cruise Line"
              }
            ),
            Google::Ads::GoogleAds::V11::Common::TextAsset->new({
                text => "Experience the Stars"
              })
          ],
          descriptions => [
            Google::Ads::GoogleAds::V11::Common::TextAsset->new({
                text => "Buy your tickets now"
              }
            ),
            # Create this particular description using the ad customizer.
            # Visit https://developers.google.com/google-ads/api/docs/ads/customize-responsive-search-ads#ad_customizers_in_responsive_search_ads
            # for details about the placeholder format.
            # The ad customizer replaces the placeholder with the value we previously
            # created and linked to the customer using `CustomerCustomizer`.
            Google::Ads::GoogleAds::V11::Common::TextAsset->new({
                text => "Just {CUSTOMIZER.$customizer_attribute_name:10USD}"
              })
          ],
          path1 => "all-inclusive",
          path2 => "deals"
        }
        ),
      finalUrls => ["http://www.example.com"]});

  # Create an ad group ad to hold the above ad.
  my $ad_group_ad = Google::Ads::GoogleAds::V11::Resources::AdGroupAd->new({
      adGroup => Google::Ads::GoogleAds::V11::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      status => PAUSED,
      ad     => $ad
    });

  # Create an ad group ad operation.
  my $operation =
    Google::Ads::GoogleAds::V11::Services::AdGroupAdService::AdGroupAdOperation
    ->new({
      create => $ad_group_ad
    });

  # Issue a mutate request to add the ad group ad and print its information.
  my $response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});
  printf "Created responsive search ad with resource name '%s'.\n",
    $response->{results}[0]{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,
  "ad_group_id=i"               => \$ad_group_id,
  "customizer_attribute_name=s" => \$customizer_attribute_name,
);

# 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, $customizer_attribute_name);

# Call the example.
add_responsive_search_ad_with_ad_customizer(
  $api_client,  $customer_id =~ s/-//gr,
  $ad_group_id, $customizer_attribute_name
);

=pod

=head1 NAME

add_responsive_search_ad_with_ad_customizer

=head1 DESCRIPTION

Adds a customizer attribute, links the customizer attribute to a customer, and
then adds a responsive search ad with a description using the ad customizer to
the specified ad group.

=head1 SYNOPSIS

add_responsive_search_ad_with_ad_customizer.pl [options]

    -help                           Show the help message.
    -customer_id                    The Google Ads customer ID.
    -ad_group_id                    The ad group ID.
    -customizer_attribute_name      [optional] The name of the customizer attribute.

=cut