إضافة مادة عرض خلاصة صفحة ديناميكية

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.CodeSampleHelper;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v17.common.PageFeedAsset;
import com.google.ads.googleads.v17.common.WebpageConditionInfo;
import com.google.ads.googleads.v17.common.WebpageInfo;
import com.google.ads.googleads.v17.enums.AssetSetTypeEnum.AssetSetType;
import com.google.ads.googleads.v17.enums.WebpageConditionOperandEnum.WebpageConditionOperand;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.AdGroupCriterion;
import com.google.ads.googleads.v17.resources.Asset;
import com.google.ads.googleads.v17.resources.AssetSet;
import com.google.ads.googleads.v17.resources.AssetSetAsset;
import com.google.ads.googleads.v17.resources.CampaignAssetSet;
import com.google.ads.googleads.v17.services.AdGroupCriterionOperation;
import com.google.ads.googleads.v17.services.AdGroupCriterionServiceClient;
import com.google.ads.googleads.v17.services.AssetOperation;
import com.google.ads.googleads.v17.services.AssetServiceClient;
import com.google.ads.googleads.v17.services.AssetSetAssetOperation;
import com.google.ads.googleads.v17.services.AssetSetAssetServiceClient;
import com.google.ads.googleads.v17.services.AssetSetOperation;
import com.google.ads.googleads.v17.services.AssetSetServiceClient;
import com.google.ads.googleads.v17.services.CampaignAssetSetOperation;
import com.google.ads.googleads.v17.services.CampaignAssetSetServiceClient;
import com.google.ads.googleads.v17.services.MutateAdGroupCriteriaResponse;
import com.google.ads.googleads.v17.services.MutateAssetResult;
import com.google.ads.googleads.v17.services.MutateAssetSetAssetsResponse;
import com.google.ads.googleads.v17.services.MutateAssetSetsResponse;
import com.google.ads.googleads.v17.services.MutateAssetsResponse;
import com.google.ads.googleads.v17.services.MutateCampaignAssetSetsResponse;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/** Adds a page feed with URLs for a Dynamic Search Ads campaign. */
public class AddDynamicPageFeedAsset {

  private static class AddDynamicPageFeedParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true)
    private Long campaignId;

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

  public static void main(String[] args) {
    AddDynamicPageFeedParams params = new AddDynamicPageFeedParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.campaignId = Long.parseLong("INSERT_CAMPAIGN_ID_HERE");
      params.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
    }

    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 AddDynamicPageFeedAsset().runExample(googleAdsClient, params);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /** Runs the example. */
  private void runExample(GoogleAdsClient googleAdsClient, AddDynamicPageFeedParams params) {
    // The label for the DSA page URLs.
    String dsaPageUrlLabel = "discounts";
    // Creates an Asset.
    List<String> assetResourceNames =
        createAssets(googleAdsClient, dsaPageUrlLabel, params.customerId);
    // Creates an AssetSet - this is a collection of assets that can be associated with a campaign.
    // Note: do not confuse this with an AssetGroup. An AssetGroup replaces AdGroups in some types
    // of campaigns.
    String assetSetResourceName = createAssetSet(googleAdsClient, params);
    // Adds the Assets to the AssetSet.
    addAssetsToAssetSet(googleAdsClient, assetResourceNames, assetSetResourceName, params);
    // Links the AssetSet to the Campaign.
    linkAssetSetToCampaign(googleAdsClient, assetSetResourceName, params);
    // Optional: Targets web pages matching the feed's label in the ad group.
    addDsaTarget(googleAdsClient, dsaPageUrlLabel, params);
    System.out.printf(
        "Dynamic page feed setup is complete for campaign with ID %d.%n", params.campaignId);
  }

  /** Creates Assets to be used in a DSA page feed. */
  private static List<String> createAssets(GoogleAdsClient googleAdsClient,
      String dsaPageUrlLabel, long customerId) {
    List<String> urls =
        ImmutableList.of(
            "http://www.example.com/discounts/rental-cars",
            "http://www.example.com/discounts/hotel-deals",
            "http://www.example.com/discounts/flight-deals");

    // Creates one operation per URL.
    List<AssetOperation> assetOperations = new ArrayList<>();
    for (String url : urls) {
      PageFeedAsset pageFeedAsset =
          PageFeedAsset.newBuilder()
              // Sets the URL of the page to include.
              .setPageUrl(url)
              // Recommended: adds labels to the asset. These labels can be used later in ad group
              // targeting to restrict the set of pages that can serve.
              .addLabels(dsaPageUrlLabel)
              .build();
      Asset asset = Asset.newBuilder().setPageFeedAsset(pageFeedAsset).build();
      assetOperations.add(AssetOperation.newBuilder().setCreate(asset).build());
    }

    // Creates the service client.
    try (AssetServiceClient assetServiceClient =
        googleAdsClient.getLatestVersion().createAssetServiceClient()) {
      // Adds the assets.
      MutateAssetsResponse response =
          assetServiceClient.mutateAssets(String.valueOf(customerId), assetOperations);
      // Prints some information about the result.
      List<String> resourceNames =
          response.getResultsList().stream()
              .map(MutateAssetResult::getResourceName)
              .collect(Collectors.toList());
      resourceNames.forEach(r -> System.out.printf("Created asset with resource name %s.%n", r));
      return resourceNames;
    }
  }

  /** Creates an AssetSet. */
  private String createAssetSet(GoogleAdsClient googleAdsClient, AddDynamicPageFeedParams params) {
    // Creates an AssetSet which will be used to link the dynamic page feed assets to a campaign.
    AssetSet assetSet =
        AssetSet.newBuilder()
            .setName("My dynamic page feed " + CodeSampleHelper.getPrintableDateTime())
            .setType(AssetSetType.PAGE_FEED)
            .build();
    // Creates an operation to add the AssetSet.
    AssetSetOperation operation = AssetSetOperation.newBuilder().setCreate(assetSet).build();
    try (AssetSetServiceClient serviceClient =
        googleAdsClient.getLatestVersion().createAssetSetServiceClient()) {
      // Sends the mutate request.
      MutateAssetSetsResponse response =
          serviceClient.mutateAssetSets(
              String.valueOf(params.customerId), ImmutableList.of(operation));
      // Prints some information about the response.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created asset set with resource name %s.%n", resourceName);
      return resourceName;
    }
  }

  /** Adds an Asset to an AssetSet by creating an AssetSetAsset link. */
  private void addAssetsToAssetSet(
      GoogleAdsClient googleAdsClient,
      List<String> assetResourceNames,
      String assetSetResourceName,
      AddDynamicPageFeedParams params) {
    List<AssetSetAssetOperation> operations = new ArrayList<>();
    for (String assetResourceName : assetResourceNames) {
      AssetSetAsset assetSetAsset =
          AssetSetAsset.newBuilder()
              .setAsset(assetResourceName)
              .setAssetSet(assetSetResourceName)
              .build();
      // Creates an operation to add the link.
      AssetSetAssetOperation operation =
          AssetSetAssetOperation.newBuilder().setCreate(assetSetAsset).build();
      operations.add(operation);
    }
    try (AssetSetAssetServiceClient client =
        googleAdsClient.getLatestVersion().createAssetSetAssetServiceClient()) {
      // Sends the mutate request.
      MutateAssetSetAssetsResponse response =
          client.mutateAssetSetAssets(String.valueOf(params.customerId), operations);
      // Prints some information about the response.
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created AssetSetAsset link with resource name %s.%n", resourceName);
    }
  }

  /** Links an AssetSet to a Campaign by creating a CampaignAssetSet. */
  private void linkAssetSetToCampaign(
      GoogleAdsClient googleAdsClient,
      String assetSetResourceName,
      AddDynamicPageFeedParams params) {
    // Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
    CampaignAssetSet campaignAssetSet =
        CampaignAssetSet.newBuilder()
            .setCampaign(ResourceNames.campaign(params.customerId, params.campaignId))
            .setAssetSet(assetSetResourceName)
            .build();
    // Creates an operation to add the CampaignAssetSet.
    CampaignAssetSetOperation operation =
        CampaignAssetSetOperation.newBuilder().setCreate(campaignAssetSet).build();
    // Creates the service client.
    try (CampaignAssetSetServiceClient client =
        googleAdsClient.getLatestVersion().createCampaignAssetSetServiceClient()) {
      // Issues the mutate request.
      MutateCampaignAssetSetsResponse response =
          client.mutateCampaignAssetSets(
              String.valueOf(params.customerId), ImmutableList.of(operation));
      String resourceName = response.getResults(0).getResourceName();
      System.out.printf("Created a CampaignAssetSet with resource name %s.%n", resourceName);
    }
  }

  /** Creates an ad group criterion targeting the DSA label. */
  private static void addDsaTarget(
      GoogleAdsClient googleAdsClient, String dsaPageUrlLabel, AddDynamicPageFeedParams params) {
    String adGroupResourceName = ResourceNames.adGroup(params.customerId, params.adGroupId);

    // Creates the webpage condition info that targets an advertiser's webpages based on the
    // custom label specified by the dsaPageUrlLabel (e.g. "discounts").
    WebpageConditionInfo webpageConditionInfo =
        WebpageConditionInfo.newBuilder()
            .setOperand(WebpageConditionOperand.CUSTOM_LABEL)
            .setArgument(dsaPageUrlLabel)
            .build();

    // Creates the webpage info, or criterion for targeting webpages of an advertiser's website.
    WebpageInfo webpageInfo =
        WebpageInfo.newBuilder()
            .setCriterionName("Test Criterion")
            .addAllConditions(ImmutableList.of(webpageConditionInfo))
            .build();

    // Creates the ad group criterion.
    AdGroupCriterion adGroupCriterion =
        AdGroupCriterion.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setWebpage(webpageInfo)
            .setCpcBidMicros(1_500_000)
            .build();

    // Creates the operation.
    AdGroupCriterionOperation operation =
        AdGroupCriterionOperation.newBuilder().setCreate(adGroupCriterion).build();

    // Creates the service client.
    try (AdGroupCriterionServiceClient adGroupCriterionServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupCriterionServiceClient()) {
      // Adds the ad group criterion.
      MutateAdGroupCriteriaResponse response =
          adGroupCriterionServiceClient.mutateAdGroupCriteria(
              Long.toString(params.customerId), ImmutableList.of(operation));

      // Displays the results.
      System.out.printf(
          "Created ad group criterion with resource name '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

#C

// 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.

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.AdCustomizerPlaceholderFieldEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.AssetSetTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.FeedAttributeTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.PlaceholderTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.WebpageConditionOperandEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example adds a page feed with URLs for a Dynamic Search Ads campaign.
    /// </summary>
    public class AddDynamicPageFeedAsset : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddDynamicPageFeedAsset"/> 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>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("campaignId", Required = true, HelpText =
                "ID of the campaign to which the asset is linked.")]
            public long CampaignId { get; set; }

            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("adGroupId", Required = true, HelpText =
                "ID of the ad group to which DSA label targeting is 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);

            AddDynamicPageFeedAsset codeExample = new AddDynamicPageFeedAsset();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId,
                options.AdGroupId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds a page feed with URLs for a Dynamic Search Ads campaign.";

        /// <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="campaignId">ID of the campaign to which the asset is linked.</param>
        /// <param name="adGroupId">ID of the ad group to which DSA label targeting is
        /// added.</param>
        public void Run(GoogleAdsClient client, long customerId, long campaignId, long adGroupId)
        {
            // The label for the DSA page URLs.
            String dsaPageUrlLabel = "discounts";
            try
            {
                // Creates an Asset.
                List<string> assetResourceNames = CreateAssets(client, customerId,
                    dsaPageUrlLabel);
                // Creates an AssetSet - this is a collection of assets that can be associated
                // with a campaign.
                // Note: do not confuse this with an AssetGroup. An AssetGroup replaces
                // AdGroups in some types of campaigns.
                string assetSetResourceName = CreateAssetSet(client, customerId);
                // Adds the Assets to the AssetSet.
                AddAssetsToAssetSet(client, customerId, assetResourceNames, assetSetResourceName);
                // Links the AssetSet to the Campaign.
                LinkAssetSetToCampaign(client, customerId, campaignId, assetSetResourceName);
                // Optional: Targets web pages matching the feed's label in the ad group.
                AddDsaTarget(client, customerId, adGroupId, dsaPageUrlLabel);
                Console.WriteLine($"Dynamic page feed setup is complete for campaign with " +
                    $"ID {campaignId}.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates Assets to be used in a DSA page feed.
        /// </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="dsaPageUrlLabel">The DSA page URL label.</param>
        /// <returns>The list of asset resource names.</returns>
        private static List<string> CreateAssets(GoogleAdsClient client, long customerId,
            string dsaPageUrlLabel)
        {
            AssetServiceClient assetService = client.GetService(Services.V17.AssetService);

            string[] urls = new[]
            {
                "http://www.example.com/discounts/rental-cars",
                "http://www.example.com/discounts/hotel-deals",
                "http://www.example.com/discounts/flight-deals"
            };

            // Creates one operation per URL.
            List<AssetOperation> assetOperations = new List<AssetOperation>();
            foreach (string url in urls)
            {
                PageFeedAsset pageFeedAsset = new PageFeedAsset()
                {
                    // Sets the URL of the page to include.
                    PageUrl = url,

                    // Recommended: adds labels to the asset. These labels can be used later in
                    // ad group targeting to restrict the set of pages that can serve.
                    Labels = { dsaPageUrlLabel }
                };

                assetOperations.Add(
                    new AssetOperation()
                    {
                        Create = new Asset()
                        {
                            PageFeedAsset = pageFeedAsset
                        }
                    });
            }

            // Adds the assets.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), assetOperations);

            // Prints some information about the result.
            List<string> resourceNames = response.Results.Select(
                assetResult => assetResult.ResourceName).ToList();
            foreach (string resourceName in resourceNames)
            {
                Console.Write($"Created asset with resource name {resourceName}.");
            }
            return resourceNames;
        }

        /// <summary>
        /// Creates an AssetSet.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The resource name of the asset set.</returns>
        private string CreateAssetSet(GoogleAdsClient client, long customerId)
        {
            AssetSetServiceClient assetSetService = client.GetService(
                Services.V17.AssetSetService);

            // Creates an AssetSet which will be used to link the dynamic page feed assets
            // to a campaign.
            AssetSet assetSet = new AssetSet()
            {
                Name = "My dynamic page feed " + ExampleUtilities.GetRandomString(),
                Type = AssetSetType.PageFeed
            };

            // Creates an operation to add the AssetSet.
            AssetSetOperation operation = new AssetSetOperation()
            {
                Create = assetSet
            };

            // Sends the mutate request.
            MutateAssetSetsResponse response =
                assetSetService.MutateAssetSets(
                    customerId.ToString(), new[] { operation });
            // Prints some information about the response.
            string resourceName = response.Results[0].ResourceName;
            Console.WriteLine($"Created asset set with resource name {resourceName}.");
            return resourceName;
        }

        /// <summary>
        /// Adds an Asset to an AssetSet by creating an AssetSetAsset link.
        /// </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="assetResourceNames">The asset resource names.</param>
        /// <param name="assetSetResourceName">Resource name of the asset set.</param>
        private void AddAssetsToAssetSet(GoogleAdsClient client, long customerId,
            List<string> assetResourceNames, string assetSetResourceName)
        {
            AssetSetAssetServiceClient assetSetAssetService = client.GetService(
                Services.V17.AssetSetAssetService);

            List<AssetSetAssetOperation> operations = new List<AssetSetAssetOperation>();
            foreach (string assetResourceName in assetResourceNames)
            {
                AssetSetAsset assetSetAsset = new AssetSetAsset()
                {
                    Asset = assetResourceName,
                    AssetSet = assetSetResourceName
                };

                // Creates an operation to add the link.
                AssetSetAssetOperation operation = new AssetSetAssetOperation()
                {
                    Create = assetSetAsset
                };

                operations.Add(operation);
            }
            // Sends the mutate request.
            MutateAssetSetAssetsResponse response =
                assetSetAssetService.MutateAssetSetAssets(customerId.ToString(), operations);
            // Prints some information about the response.
            string resourceName = response.Results[0].ResourceName;
            Console.WriteLine($"Created AssetSetAsset link with resource name {resourceName}.");
        }

        /// <summary>
        /// Links an AssetSet to a Campaign by creating a CampaignAssetSet.
        /// </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="campaignId">ID of the campaign to which the asset is linked.</param>
        /// <param name="assetSetResourceName">Resource name of the asset set.</param>
        private void LinkAssetSetToCampaign(GoogleAdsClient client, long customerId,
            long campaignId, string assetSetResourceName)
        {
            CampaignAssetSetServiceClient campaignAssetSetService = client.GetService(
                Services.V17.CampaignAssetSetService);

            // Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
            CampaignAssetSet campaignAssetSet = new CampaignAssetSet()
            {
                Campaign = ResourceNames.Campaign(customerId, campaignId),
                AssetSet = assetSetResourceName,
            };

            // Creates an operation to add the CampaignAssetSet.
            CampaignAssetSetOperation operation = new CampaignAssetSetOperation()
            {
                Create = campaignAssetSet
            };
            // Issues the mutate request.
            MutateCampaignAssetSetsResponse response =
                campaignAssetSetService.MutateCampaignAssetSets(
                    customerId.ToString(), new[] { operation });
            string resourceName = response.Results[0].ResourceName;
            Console.WriteLine($"Created a CampaignAssetSet with resource name {resourceName}.");
        }

        /// <summary>
        /// Adds the DSA target.
        /// </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">The ad group to which DSA label targeting is added.</param>
        /// <param name="dsaPageUrlLabel">The DSA page URL label.</param>
        private static void AddDsaTarget(
            GoogleAdsClient client, long customerId, long adGroupId, string dsaPageUrlLabel)
        {
            AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(
                Services.V17.AdGroupCriterionService);

            string adGroupResourceName = ResourceNames.AdGroup(customerId, adGroupId);

            // Creates the webpage condition info that targets an advertiser's webpages
            // based on the custom label specified by the dsaPageUrlLabel (e.g. "discounts").
            WebpageConditionInfo webpageConditionInfo = new WebpageConditionInfo()
            {
                Operand = WebpageConditionOperand.CustomLabel,
                Argument = dsaPageUrlLabel
            };

            // Creates the webpage info, or criterion for targeting webpages of an
            // advertiser's website.
            WebpageInfo webpageInfo = new WebpageInfo()
            {
                CriterionName = "Test Criterion",
                Conditions = { webpageConditionInfo }
            };

            // Creates the ad group criterion.
            AdGroupCriterion adGroupCriterion = new AdGroupCriterion()
            {
                AdGroup = adGroupResourceName,
                Webpage = webpageInfo,
                CpcBidMicros = 1_500_000
            };

            // Creates the operation.
            AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
            {
                Create = adGroupCriterion
            };

            // Adds the ad group criterion.
            MutateAdGroupCriteriaResponse response =
                adGroupCriterionService.MutateAdGroupCriteria(
                    customerId.ToString(), new[] { operation });

            string resourceName = response.Results[0].ResourceName;
            // Displays the results.
            Console.WriteLine($"Created ad group criterion with resource " +
                $"name '{resourceName}'.");
        }
    }
}

      

PHP

<?php

/**
 * 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.
 */

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\Examples\Utils\Helper;
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\DynamicEducationAsset;
use Google\Ads\GoogleAds\V17\Common\PageFeedAsset;
use Google\Ads\GoogleAds\V17\Common\WebpageConditionInfo;
use Google\Ads\GoogleAds\V17\Common\WebpageInfo;
use Google\Ads\GoogleAds\V17\Enums\AssetSetTypeEnum\AssetSetType;
use Google\Ads\GoogleAds\V17\Enums\WebpageConditionOperandEnum\WebpageConditionOperand;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\AdGroupCriterion;
use Google\Ads\GoogleAds\V17\Resources\Asset;
use Google\Ads\GoogleAds\V17\Resources\AssetSet;
use Google\Ads\GoogleAds\V17\Resources\AssetSetAsset;
use Google\Ads\GoogleAds\V17\Resources\CampaignAssetSet;
use Google\Ads\GoogleAds\V17\Services\AdGroupCriterionOperation;
use Google\Ads\GoogleAds\V17\Services\AssetOperation;
use Google\Ads\GoogleAds\V17\Services\AssetSetAssetOperation;
use Google\Ads\GoogleAds\V17\Services\AssetSetOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignAssetSetOperation;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupCriteriaRequest;
use Google\Ads\GoogleAds\V17\Services\MutateAssetSetAssetsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateAssetSetsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateAssetsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignAssetSetsRequest;
use Google\ApiCore\ApiException;

/** Adds a page feed with URLs for a Dynamic Search Ads campaign. */
class AddDynamicPageFeedAsset
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CAMPAIGN_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::AD_GROUP_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::CAMPAIGN_ID] ?: self::CAMPAIGN_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 client customer ID
     * @param int $campaignId the campaign ID
     * @param int $adGroupId the ad group ID
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $campaignId,
        int $adGroupId
    ) {
        // The label for the DSA page URLs.
        $dsaPageUrlLabel = 'discounts';
        // Creates assets.
        $assetResourceNames = self::createAssets($googleAdsClient, $customerId, $dsaPageUrlLabel);
        // Creates an asset set - this is a collection of assets that can be associated with a
        // campaign.
        // Note: do not confuse this with an asset group. An asset group replaces ad groups in some
        // types of campaigns.
        $assetSetResourceName = self::createAssetSet($googleAdsClient, $customerId);
        // Adds the assets to the asset set.
        self::addAssetsToAssetSet(
            $googleAdsClient,
            $customerId,
            $assetResourceNames,
            $assetSetResourceName
        );
        // Links the asset set to the specified campaign.
        self::linkAssetSetToCampaign(
            $googleAdsClient,
            $assetSetResourceName,
            $customerId,
            $campaignId
        );
        // Optional: Targets web pages matching the feed's label in the ad group.
        self::addDsaTarget($googleAdsClient, $customerId, $adGroupId, $dsaPageUrlLabel);
        printf(
            "Dynamic page feed setup is complete for campaign with ID %d.%s",
            $campaignId,
            PHP_EOL
        );
    }

    /**
     * Creates assets to be used in a DSA page feed.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $dsaPageUrlLabel the DSA page URL label
     * @return string[] the created assets' resource names
     */
    private static function createAssets(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $dsaPageUrlLabel
    ): array {
        $urls = [
            'http://www.example.com/discounts/rental-cars',
            'http://www.example.com/discounts/hotel-deals',
            'http://www.example.com/discounts/flight-deals'
        ];
        $operations = [];
        // Creates one asset per URL.
        foreach ($urls as $url) {
            $pageFeedAsset = new PageFeedAsset([
                'page_url' => $url,
                // Recommended: adds labels to the asset. These labels can be used later in ad group
                // targeting to restrict the set of pages that can serve.
                'labels' => [$dsaPageUrlLabel]
            ]);

            // Wraps the page feed asset in an asset.
            $asset = new Asset(['page_feed_asset' => $pageFeedAsset]);

            // Creates an asset operation and adds it to the list of operations.
            $assetOperation = new AssetOperation();
            $assetOperation->setCreate($asset);
            $operations[] = $assetOperation;
        }

        // Issues a mutate request to add the assets and prints its information.
        $assetServiceClient = $googleAdsClient->getAssetServiceClient();
        $response = $assetServiceClient->mutateAssets(MutateAssetsRequest::build(
            $customerId,
            $operations
        ));
        $assetResourceNames = [];
        printf("Added %d assets:%s", $response->getResults()->count(), PHP_EOL);
        foreach ($response->getResults() as $addedAsset) {
            /** @var Asset $addedAsset */
            $assetResourceName = $addedAsset->getResourceName();
            printf(
                "Created an asset with resource name: '%s'.%s",
                $assetResourceName,
                PHP_EOL
            );
            $assetResourceNames[] = $assetResourceName;
        }
        return $assetResourceNames;
    }

    /**
     * Creates an asset set.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @return string the created asset set's resource name
     */
    private static function createAssetSet(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ): string {
        // Creates an asset set which will be used to link the dynamic page feed assets to a
        // campaign.
        $assetSet = new AssetSet([
            'name' => 'My dynamic page feed ' . Helper::getPrintableDatetime(),
            'type' => AssetSetType::PAGE_FEED
        ]);

        // Creates an asset set operation.
        $assetSetOperation = new AssetSetOperation();
        $assetSetOperation->setCreate($assetSet);

        // Issues a mutate request to add the asset set and prints its information.
        $assetSetServiceClient = $googleAdsClient->getAssetSetServiceClient();
        $response = $assetSetServiceClient->mutateAssetSets(MutateAssetSetsRequest::build(
            $customerId,
            [$assetSetOperation]
        ));
        $assetSetResourceName = $response->getResults()[0]->getResourceName();
        printf(
            "Created an asset set with resource name: '%s'.%s",
            $assetSetResourceName,
            PHP_EOL
        );

        return $assetSetResourceName;
    }

    /**
     * Adds assets to an asset set by creating an asset set asset link.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string[] $assetResourceNames the asset resource names
     * @param string $assetSetResourceName the asset set resource name
     */
    private static function addAssetsToAssetSet(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        array $assetResourceNames,
        string $assetSetResourceName
    ): void {
        $operations = [];
        foreach ($assetResourceNames as $assetResourceName) {
            // Creates an asset set asset.
            $assetSetAsset = new AssetSetAsset([
                'asset' => $assetResourceName,
                'asset_set' => $assetSetResourceName
            ]);

            // Creates an asset set asset operation and adds it to the list of operations.
            $assetSetAssetOperation = new AssetSetAssetOperation();
            $assetSetAssetOperation->setCreate($assetSetAsset);
            $operations[] = $assetSetAssetOperation;
        }

        // Issues a mutate request to add the asset set assets and prints its information.
        $assetSetAssetServiceClient = $googleAdsClient->getAssetSetAssetServiceClient();
        $response = $assetSetAssetServiceClient->mutateAssetSetAssets(
            MutateAssetSetAssetsRequest::build($customerId, $operations)
        );
        printf("Added %d asset set assets:%s", $response->getResults()->count(), PHP_EOL);
        foreach ($response->getResults() as $addedAssetSetAsset) {
            /** @var AssetSetAsset $addedAssetSetAsset */
            printf(
                "Created an asset set asset link with resource name: '%s'.%s",
                $addedAssetSetAsset->getResourceName(),
                PHP_EOL
            );
        }
    }

    /**
     * Links the specified asset set to the specified campaign by creating a campaign asset set.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param string $assetSetResourceName the asset set's resource name to link
     * @param int $customerId the customer ID
     * @param int $campaignId the campaign ID to link the asset set to
     */
    private static function linkAssetSetToCampaign(
        GoogleAdsClient $googleAdsClient,
        string $assetSetResourceName,
        int $customerId,
        int $campaignId
    ): void {
        // Creates a campaign asset set representing the link between an asset set and a campaign.
        $campaignAssetSet = new CampaignAssetSet([
            'asset_set' => $assetSetResourceName,
            'campaign' => ResourceNames::forCampaign($customerId, $campaignId)
        ]);

        // Creates a campaign asset set operation.
        $campaignAssetSetOperation = new CampaignAssetSetOperation();
        $campaignAssetSetOperation->setCreate($campaignAssetSet);

        // Issues a mutate request to add the campaign asset set and prints its information.
        $campaignAssetSetServiceClient = $googleAdsClient->getCampaignAssetSetServiceClient();
        $response = $campaignAssetSetServiceClient->mutateCampaignAssetSets(
            MutateCampaignAssetSetsRequest::build($customerId, [$campaignAssetSetOperation])
        );
        printf(
            "Created a campaign asset set with resource name: '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Creates an ad group criterion targeting the DSA label.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $adGroupId the ad group ID
     * @param string $dsaPageUrlLabel the label for the DSA page URLs
     */
    public static function addDsaTarget(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId,
        string $dsaPageUrlLabel
    ): void {
        // Creates the webpage condition info that targets an advertiser's webpages based on the
        // custom label specified by the DSA page URL label (e.g. "discounts").
        $webpageConditionInfo = new WebpageConditionInfo([
            'operand' => WebpageConditionOperand::CUSTOM_LABEL,
            'argument' => $dsaPageUrlLabel
        ]);

        // Creates the webpage info, or criterion for targeting webpages of an advertiser's website.
        $webpageInfo = new WebpageInfo([
            'criterion_name' => 'Test Criterion',
            'conditions' => [$webpageConditionInfo]
        ]);

        // Creates the ad group criterion.
        $adGroupCriterion = new AdGroupCriterion([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            'webpage' => $webpageInfo,
            'cpc_bid_micros' => 1_500_000
        ]);

        // Creates the ad group criterion operation.
        $adGroupCriterionOperation = new AdGroupCriterionOperation();
        $adGroupCriterionOperation->setCreate($adGroupCriterion);

        // Issues a mutate request to add the ad group criterion and prints its information.
        $adGroupCriterionServiceClient = $googleAdsClient->getAdGroupCriterionServiceClient();
        $response = $adGroupCriterionServiceClient->mutateAdGroupCriteria(
            MutateAdGroupCriteriaRequest::build($customerId, [$adGroupCriterionOperation])
        );
        printf(
            "Created ad group criterion with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

AddDynamicPageFeedAsset::main();

      

Python

#!/usr/bin/env python
# Copyright 2023 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 page feed with URLs for a Dynamic Search Ads campaign."""

import argparse
import resource
import sys

from examples.utils.example_helpers import get_printable_datetime
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


# The label for the DSA page URLs.
DSA_PAGE_URL_LABEL = "discounts"


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

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        campaign_id: the ID for a Campaign.
        ad_group_id: the ID for an Ad Group.
    """
    # Creates assets.
    asset_resource_names = create_assets(
        client, customer_id, DSA_PAGE_URL_LABEL
    )

    # Creates an asset set - this is a collection of assets that can be
    # associated with a campaign.
    # Note: do not confuse this with an asset group. An asset group replaces ad
    # groups in some types of campaigns.
    asset_set_resource_name = create_asset_set(client, customer_id)

    # Adds the assets to the asset set
    add_assets_to_asset_set(
        client, customer_id, asset_resource_names, asset_set_resource_name
    )

    # Links the asset set to the specified campaign.
    link_asset_set_to_campaign(
        client, customer_id, campaign_id, asset_set_resource_name
    )

    # Optional: Targets web pages matching the feed's label in the ad group.
    if ad_group_id:
        add_dsa_target(client, customer_id, ad_group_id, DSA_PAGE_URL_LABEL)


def create_assets(client, customer_id, dsa_page_url_label):
    """Creates assets to be used in a DSA page feed.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        dsa_page_url_label: the label for the DSA page URLs.

    Returns:
        a list of the created assets' resource names.
    """
    urls = [
        "http://www.example.com/discounts/rental-cars",
        "http://www.example.com/discounts/hotel-deals",
        "http://www.example.com/discounts/flight-deals",
    ]
    operations = []

    # Creates one asset per URL.
    for url in urls:
        # Creates an asset operation and adds it to the list of operations.
        operation = client.get_type("AssetOperation")
        asset = operation.create
        page_feed_asset = asset.page_feed_asset
        page_feed_asset.page_url = url
        # Recommended: adds labels to the asset. These labels can be used later
        # in ad group targeting to restrict the set of pages that can serve.
        page_feed_asset.labels.append(dsa_page_url_label)
        operations.append(operation)

    # Issues a mutate request to add the assets and prints its information.
    asset_service = client.get_service("AssetService")
    response = asset_service.mutate_assets(
        customer_id=customer_id, operations=operations
    )

    print(f"Added {len(response.results)} assets:")

    resource_names = []
    for result in response.results:
        resource_name = result.resource_name
        print(f"\tCreated an asset with resource name: '{resource_name}'")
        resource_names.append(resource_name)

    return resource_names


def create_asset_set(client, customer_id):
    """Creates an asset set.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.

    Returns:
        the created asset set's resource name.
    """
    operation = client.get_type("AssetSetOperation")
    # Creates an asset set which will be used to link the dynamic page feed
    # assets to a campaign.
    asset_set = operation.create
    asset_set.name = f"My dynamic page feed {get_printable_datetime()}"
    asset_set.type_ = client.enums.AssetSetTypeEnum.PAGE_FEED

    # Issues a mutate request to add the asset set and prints its information.
    asset_set_service = client.get_service("AssetSetService")
    response = asset_set_service.mutate_asset_sets(
        customer_id=customer_id, operations=[operation]
    )

    resource_name = response.results[0].resource_name
    print(f"Created an asset set with resource name: '{resource_name}'")
    return resource_name


def add_assets_to_asset_set(
    client, customer_id, asset_resource_names, asset_set_resource_name
):
    """Adds assets to an asset set by creating an asset set asset link.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        asset_resource_names: a list of asset resource names.
        asset_set_resource_name: a resource name for an asset set.
    """
    operations = []
    for resource_name in asset_resource_names:
        # Creates an asset set asset operation and adds it to the list of
        # operations.
        operation = client.get_type("AssetSetAssetOperation")
        asset_set_asset = operation.create
        asset_set_asset.asset = resource_name
        asset_set_asset.asset_set = asset_set_resource_name
        operations.append(operation)

    # Issues a mutate request to add the asset set assets and prints its
    # information.
    asset_set_asset_service = client.get_service("AssetSetAssetService")
    response = asset_set_asset_service.mutate_asset_set_assets(
        customer_id=customer_id, operations=operations
    )

    print(f"Added {len(response.results)} asset set assets:")

    for result in response.results:
        print(
            "\tCreated an asset set asset link with resource name "
            f"'{result.resource_name}'"
        )


def link_asset_set_to_campaign(
    client, customer_id, campaign_id, asset_set_resource_name
):
    """Links the asset set to the campaign by creating a campaign asset set.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        campaign_id: the ID for a Campaign.
        asset_set_resource_name: a resource name for an asset set.
    """
    googleads_service = client.get_service("GoogleAdsService")
    # Creates a campaign asset set representing the link between an asset set
    # and a campaign.
    operation = client.get_type("CampaignAssetSetOperation")
    campaign_asset_set = operation.create
    campaign_asset_set.asset_set = asset_set_resource_name
    campaign_asset_set.campaign = googleads_service.campaign_path(
        customer_id, campaign_id
    )

    campaign_asset_set_service = client.get_service("CampaignAssetSetService")
    response = campaign_asset_set_service.mutate_campaign_asset_sets(
        customer_id=customer_id, operations=[operation]
    )

    resource_name = response.results[0].resource_name
    print(f"Created a campaign asset set with resource name: '{resource_name}'")


def add_dsa_target(client, customer_id, ad_group_id, dsa_page_url_label):
    """Creates an ad group criterion targeting the DSA label.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        ad_group_id: the ID for an Ad Group.
        dsa_page_url_label: the label for the DSA page URLs.
    """
    googleads_service = client.get_service("GoogleAdsService")
    # Creates the ad group criterion.
    operation = client.get_type("AdGroupCriterionOperation")
    criterion = operation.create
    criterion.ad_group = googleads_service.ad_group_path(
        customer_id, ad_group_id
    )
    criterion.cpc_bid_micros = 1500000
    # Creates the webpage info, or criterion for targeting webpages of an
    # advertiser's website.
    criterion.webpage.criterion_name = "Test Criterion"
    # Creates the webpage condition info that targets an advertiser's webpages
    # based on the custom label specified by the DSA page URL label
    # (e.g. "discounts").
    webpage_condition = client.get_type("WebpageConditionInfo")
    webpage_condition.operand = (
        client.enums.WebpageConditionOperandEnum.CUSTOM_LABEL
    )
    webpage_condition.argument = dsa_page_url_label
    criterion.webpage.conditions.append(webpage_condition)

    # Issues a mutate request to add the ad group criterion and prints its
    # information.
    ad_group_criterion_service = client.get_service("AdGroupCriterionService")
    response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id=customer_id, operations=[operation]
    )

    print(
        "Created ad group criterion with resource name: "
        f"'{response.results[0].resource_name}'"
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=(
            "Adds a page feed with URLs for a Dynamic Search Ads campaign"
        )
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )

    parser.add_argument(
        "-i",
        "--campaign_id",
        type=str,
        required=True,
        help="The Google Ads campaign ID.",
    )

    parser.add_argument(
        "-a", "--ad_group_id", type=str, help="The Google Ads 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")

    try:
        main(
            googleads_client,
            args.customer_id,
            args.campaign_id,
            args.ad_group_id,
        )
    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:: Copyright 2022, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
#           you may not use this file except in compliance with the License.
#           You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#           Unless required by applicable law or agreed to in writing, software
#           distributed under the License is distributed on an "AS IS" BASIS,
#           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
#           implied.
#           See the License for the specific language governing permissions and
#           limitations under the License.
#
# This example adds a page feed with URLs for a Dynamic Search Ads campaign.

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

def add_dynamic_page_feed_asset(customer_id, campaign_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

  # The label for the DSA page URLs.
  dsa_page_url_label = "discounts"

  # Creates a list of assets.
  asset_resource_names = create_assets(client, dsa_page_url_label, customer_id)

  # Creates an AssetSet - this is a collection of assets that can be
  # associated with a campaign. Note: do not confuse this with an AssetGroup.
  # An AssetGroup replaces AdGroups in some types of campaigns.
  asset_set_resource_name = create_asset_set(client, customer_id)

  # Adds the Assets to the AssetSet.
  add_assets_to_asset_set(client, asset_resource_names, asset_set_resource_name, customer_id)

  # Links the AssetSet to the Campaign.
  link_asset_set_to_campaign(client, asset_set_resource_name, customer_id, campaign_id)

  # Optional: Targets web pages matching the feed's label in the ad group.
  add_dsa_target(client, dsa_page_url_label, customer_id, ad_group_id)

  puts "Dynamic page feed setup is complete for campaign with ID #{campaign_id}."
end

def create_assets(client, dsa_page_url_label, customer_id)
  urls = [
    'http://www.example.com/discounts/rental-cars',
    'http://www.example.com/discounts/hotel-deals',
    'http://www.example.com/discounts/flight-deals',
  ]

  operations = urls.map do |url|
    client.operation.create_resource.asset do |asset|
      asset.page_feed_asset = client.resource.page_feed_asset do |pfa|
        # Sets the URL of the page to include.
        pfa.page_url = url
        # Recommended: adds labels to the asset. These labels can be used later
        # in ad group targeting to restrict the set of pages that can serve.
        pfa.labels << dsa_page_url_label
      end
    end
  end

  response = client.service.asset.mutate_assets(
    customer_id: customer_id,
    operations: operations,
  )

  resource_names = []
  response.results.each do |result|
    resource_name = result.resource_name
    puts "Created asset with resource name '#{resource_name}'"
    resource_names << resource_name
  end

  resource_names
end

def create_asset_set(client, customer_id)
  # Creates an AssetSet which will be used to link the dynamic page feed assets to a campaign.
  # Creates an operation to add the AssetSet.
  operation = client.operation.create_resource.asset_set do |asset_set|
    asset_set.name = "My dynamic page feed #{Time.now}"
    asset_set.type = :PAGE_FEED
  end

  # Sends the mutate request.
  response = client.service.asset_set.mutate_asset_sets(
    customer_id: customer_id,
    operations: [operation],
  )
  # Prints some information about the response.
  resource_name = response.results.first.resource_name
  puts "Created asset set with resource name '#{resource_name}'"

  resource_name
end

def add_assets_to_asset_set(client, asset_resource_names, asset_set_resource_name, customer_id)
  operations = asset_resource_names.map do |asset_resource_name|
    client.operation.create_resource.asset_set_asset do |asa|
      asa.asset = asset_resource_name
      asa.asset_set = asset_set_resource_name
    end
  end

  response = client.service.asset_set_asset.mutate_asset_set_assets(
    customer_id: customer_id,
    operations: operations,
  )
  resource_name = response.results.first.resource_name
  puts "Created asset set asset with resource name '#{resource_name}'"
end

def link_asset_set_to_campaign(client, asset_set_resource_name, customer_id, campaign_id)
  # Creates a CampaignAssetSet representing the link between an AssetSet and a Campaign.
  # Creates an operation to add the CampaignAssetSet.
  operation = client.operation.create_resource.campaign_asset_set do |cas|
    cas.campaign = client.path.campaign(customer_id, campaign_id)
    cas.asset_set = asset_set_resource_name
  end

  # Issues the mutate request.
  response = client.service.campaign_asset_set.mutate_campaign_asset_sets(
    customer_id: customer_id,
    operations: [operation],
  )
  resource_name = response.results.first.resource_name
  puts "Created a campaign asset set with resource name '#{resource_name}'"
end


def add_dsa_target(client, dsa_page_url_label, customer_id, ad_group_id)
  operation = client.operation.create_resource.ad_group_criterion do |agc|
    agc.ad_group = client.path.ad_group(customer_id, ad_group_id)
    agc.cpc_bid_micros = 1_500_000

    # Creates the webpage info, or criterion for targeting webpages of an
    # advertiser's website.
    agc.webpage = client.resource.webpage_info do |webpage|
      webpage.criterion_name = "Test Criterion"
      # Creates the webpage condition info that targets an advertiser's webpages
      # based on the custom label specified by the dsaPageUrlLabel
      # (e.g. "discounts").
      webpage.conditions << client.resource.webpage_condition_info do |wci|
        wci.operand = :CUSTOM_LABEL
        wci.argument = dsa_page_url_label
      end
    end
  end

  response = client.service.ad_group_criterion.mutate_ad_group_criteria(
    customer_id: customer_id,
    operations: [operation],
  )
  resource_name = response.results.first.resource_name
  puts "Created ad group criterion with resource name '#{resource_name}'"
end

if __FILE__ == $0
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE'
  options[:ad_group_id] = 'INSERT_AD_GROUP_ID_HERE'

  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,
      'The Google Ads customer ID.') do |v|
      options[:customer_id] = v
    end

    opts.on('-c', '--campaign-id CAMPAIGN-ID', String, 'The campaign ID.') do |v|
      options[:campaign_id] = v
    end

    opts.on('-A', '--ad-group-id AD-GROUP-ID', String, 'The 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
    add_dynamic_page_feed_asset(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:campaign_id),
      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

      

Perl

#!/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.
#
# Adds a page feed with URLs for a Dynamic Search Ads campaign.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V17::Resources::Asset;
use Google::Ads::GoogleAds::V17::Resources::AssetSet;
use Google::Ads::GoogleAds::V17::Resources::AssetSetAsset;
use Google::Ads::GoogleAds::V17::Resources::CampaignAssetSet;
use Google::Ads::GoogleAds::V17::Resources::AdGroupCriterion;
use Google::Ads::GoogleAds::V17::Common::PageFeedAsset;
use Google::Ads::GoogleAds::V17::Common::WebpageConditionInfo;
use Google::Ads::GoogleAds::V17::Common::WebpageInfo;
use Google::Ads::GoogleAds::V17::Enums::AssetSetTypeEnum qw(PAGE_FEED);
use Google::Ads::GoogleAds::V17::Enums::WebpageConditionOperandEnum
  qw(CUSTOM_LABEL);
use Google::Ads::GoogleAds::V17::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V17::Services::AssetSetService::AssetSetOperation;
use
  Google::Ads::GoogleAds::V17::Services::AssetSetAssetService::AssetSetAssetOperation;
use
  Google::Ads::GoogleAds::V17::Services::CampaignAssetSetService::CampaignAssetSetOperation;
use
  Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use Data::Uniqid qw(uniqid);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $campaign_id = "INSERT_CAMPAIGN_ID_HERE";
my $ad_group_id = "INSERT_AD_GROUP_ID_HERE";

sub add_dynamic_page_feed_asset {
  my ($api_client, $customer_id, $campaign_id, $ad_group_id) = @_;

  # The label for the DSA page URLs.
  my $dsa_page_url_label = "discounts";

  # Create the Assets.
  my $asset_resource_names =
    create_assets($api_client, $customer_id, $dsa_page_url_label);

  # Create an AssetSet - this is a collection of assets that can be associated
  # with a campaign.
  # Note: do not confuse this with an AssetGroup. An AssetGroup replaces AdGroups
  # in some types of campaigns.
  my $asset_set_resource_name = create_asset_set($api_client, $customer_id);

  # Add the Assets to the AssetSet.
  add_assets_to_asset_set($api_client, $customer_id, $asset_resource_names,
    $asset_set_resource_name);

  # Link the AssetSet to the Campaign.
  link_asset_set_to_campaign($api_client, $customer_id, $campaign_id,
    $asset_set_resource_name);

  # Optional: Target web pages matching the feed's label in the ad group.
  add_dsa_target($api_client, $customer_id, $ad_group_id, $dsa_page_url_label);

  printf "Dynamic page feed setup is complete for campaign with ID %d.\n",
    $campaign_id;

  return 1;
}

# Creates Assets to be used in a DSA page feed.
sub create_assets {
  my ($api_client, $customer_id, $dsa_page_url_label) = @_;

  my $urls = [
    "http://www.example.com/discounts/rental-cars",
    "http://www.example.com/discounts/hotel-deals",
    "http://www.example.com/discounts/flight-deals"
  ];

  # Create one operation per URL.
  my $asset_operations = [];
  foreach my $url (@$urls) {
    my $page_feed_asset =
      Google::Ads::GoogleAds::V17::Common::PageFeedAsset->new({
        # Set the URL of the page to include.
        pageUrl => $url,
        # Recommended: add labels to the asset. These labels can be used later in
        # ad group targeting to restrict the set of pages that can serve.
        labels => [$dsa_page_url_label]});
    my $asset = Google::Ads::GoogleAds::V17::Resources::Asset->new({
      pageFeedAsset => $page_feed_asset
    });

    push @$asset_operations,
      Google::Ads::GoogleAds::V17::Services::AssetService::AssetOperation->new({
        create => $asset
      });
  }

  # Add the assets.
  my $response = $api_client->AssetService()->mutate({
    customerId => $customer_id,
    operations => $asset_operations
  });

  # Print some information about the response.
  my $resource_names = [];
  foreach my $result (@{$response->{results}}) {
    push @$resource_names, $result->{resourceName};
    printf "Created asset with resource name '%s'.\n", $result->{resourceName};
  }
  return $resource_names;
}

# Creates an AssetSet.
sub create_asset_set {
  my ($api_client, $customer_id) = @_;

  # Create an AssetSet which will be used to link the dynamic page feed assets to
  # a campaign.
  my $asset_set = Google::Ads::GoogleAds::V17::Resources::AssetSet->new({
    name => "My dynamic page feed #" . uniqid(),
    type => PAGE_FEED
  });

  # Create an operation to add the AssetSet.
  my $operation =
    Google::Ads::GoogleAds::V17::Services::AssetSetService::AssetSetOperation->
    new({
      create => $asset_set
    });

  # Send the mutate request.
  my $response = $api_client->AssetSetService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  # Print some information about the response.
  my $resource_name = $response->{results}[0]{resourceName};
  printf "Created asset set with resource name '%s'.\n", $resource_name;
  return $resource_name;
}

# Adds the Assets to an AssetSet by creating an AssetSetAsset link.
sub add_assets_to_asset_set {
  my ($api_client, $customer_id, $asset_resource_names,
    $asset_set_resource_name)
    = @_;

  my $operations = [];
  foreach my $asset_resource_name (@$asset_resource_names) {
    my $asset_set_asset =
      Google::Ads::GoogleAds::V17::Resources::AssetSetAsset->new({
        asset    => $asset_resource_name,
        assetSet => $asset_set_resource_name
      });

    # Create an operation to add the link.
    my $operation =
      Google::Ads::GoogleAds::V17::Services::AssetSetAssetService::AssetSetAssetOperation
      ->new({
        create => $asset_set_asset
      });
    push @$operations, $operation;
  }

  # Send the mutate request.
  my $response = $api_client->AssetSetAssetService()->mutate({
    customerId => $customer_id,
    operations => $operations
  });

  # Print some information about the response.
  my $resource_name = $response->{results}[0]{resourceName};
  printf "Created AssetSetAsset link with resource name '%s'.\n",
    $resource_name;
}

# Links an AssetSet to a Campaign by creating a CampaignAssetSet.
sub link_asset_set_to_campaign {
  my ($api_client, $customer_id, $campaign_id, $asset_set_resource_name) = @_;

  # Create a CampaignAssetSet representing the link between an AssetSet and a Campaign.
  my $campaign_asset_set =
    Google::Ads::GoogleAds::V17::Resources::CampaignAssetSet->new({
      campaign => Google::Ads::GoogleAds::V17::Utils::ResourceNames::campaign(
        $customer_id, $campaign_id
      ),
      assetSet => $asset_set_resource_name
    });

  # Create an operation to add the CampaignAssetSet.
  my $operation =
    Google::Ads::GoogleAds::V17::Services::CampaignAssetSetService::CampaignAssetSetOperation
    ->new({
      create => $campaign_asset_set
    });

  # Issue the mutate request.
  my $response = $api_client->CampaignAssetSetService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  # Print some information about the response.
  my $resource_name = $response->{results}[0]{resourceName};
  printf "Created a CampaignAssetSet with resource name '%s'.\n",
    $resource_name;
}

# Creates an ad group criterion targeting the DSA label.
sub add_dsa_target {
  my ($api_client, $customer_id, $ad_group_id, $dsa_page_url_label) = @_;

  my $ad_group_resource_name =
    Google::Ads::GoogleAds::V17::Utils::ResourceNames::ad_group($customer_id,
    $ad_group_id);

  # Create the webpage condition info that targets an advertiser's webpages based
  # on the custom label specified by the $dsa_page_url_label (e.g. "discounts").
  my $webpage_condition_info =
    Google::Ads::GoogleAds::V17::Common::WebpageConditionInfo->new({
      operand  => CUSTOM_LABEL,
      argument => $dsa_page_url_label
    });

  # Create the webpage info, or criterion for targeting webpages of an advertiser's website.
  my $webpage_info = Google::Ads::GoogleAds::V17::Common::WebpageInfo->new({
      criterionName => "Test Criterion",
      conditions    => [$webpage_condition_info]});

  # Create the ad group criterion.
  my $ad_group_criterion =
    Google::Ads::GoogleAds::V17::Resources::AdGroupCriterion->new({
      adGroup      => $ad_group_resource_name,
      webpage      => $webpage_info,
      cpcBidMicros => 1_500_000
    });

  # Create the operation.
  my $operation =
    Google::Ads::GoogleAds::V17::Services::AdGroupCriterionService::AdGroupCriterionOperation
    ->new({
      create => $ad_group_criterion
    });

  # Add the ad group criterion.
  my $response = $api_client->AdGroupCriterionService()->mutate({
      customerId => $customer_id,
      operations => [$operation]});

  # Display the results.
  printf "Created ad group criterion 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,
  "campaign_id=i" => \$campaign_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, $campaign_id, $ad_group_id);

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

=pod

=head1 NAME

add_dynamic_page_feed_asset

=head1 DESCRIPTION

Adds a page feed with URLs for a Dynamic Search Ads campaign.

=head1 SYNOPSIS

add_dynamic_page_feed_asset.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -campaign_id                The campaign ID.
    -ad_group_id                The ad group ID.

=cut