Custom Audiences

Custom audiences help you reach your ideal audience by entering relevant keywords, URLs, and apps. It's the migration of the two previous customizable offerings, Custom Intent and Custom Affinity, into a simplified and assistive workflow of the suite of audience products.

You can set up a custom audience in your Display, Discovery, Gmail, and Video campaigns by adding specific keywords, URLs, and apps related to your product or service. Google Ads will then show ads to users with these interests or purchase intentions on pages, apps, and videos.

How custom audiences work

Custom audiences automatically choose the right audience to best fit the needs of your campaign. For example, rather than reaching the sports fans affinity audience, a running shoe company may want to reach avid marathon runners instead. With custom audiences, the shoe company can define this audience by:

  1. Entering interests like "5K runs" "triathlon athlete," or "long distance runner".

  2. Using URLs of websites with content about running, training schedules, marathon nutrition, and other marathon themes.

  3. Entering apps in the Health & Fitness category that an avid marathon runner may likely be interested in like Google Fit.

Code example

The following code example demonstrates how to create a CustomAudience using the CustomAudienceService:

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.remarketing;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

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.v6.enums.CustomAudienceMemberTypeEnum.CustomAudienceMemberType;
import com.google.ads.googleads.v6.enums.CustomAudienceStatusEnum.CustomAudienceStatus;
import com.google.ads.googleads.v6.enums.CustomAudienceTypeEnum.CustomAudienceType;
import com.google.ads.googleads.v6.errors.GoogleAdsError;
import com.google.ads.googleads.v6.errors.GoogleAdsException;
import com.google.ads.googleads.v6.resources.CustomAudience;
import com.google.ads.googleads.v6.resources.CustomAudienceMember;
import com.google.ads.googleads.v6.services.CustomAudienceOperation;
import com.google.ads.googleads.v6.services.CustomAudienceServiceClient;
import com.google.ads.googleads.v6.services.MutateCustomAudiencesResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Illustrates adding a custom audience. Custom audiences help you reach your ideal audience by
 * entering relevant keywords, URLs and apps. For more information about custom audiences, see:
 * https://support.google.com/google-ads/answer/9805516.
 */
public class AddCustomAudience {

  private static class AddCustomAudienceParams extends CodeSampleParams {

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

  public static void main(String[] args) {
    AddCustomAudienceParams params = new AddCustomAudienceParams();
    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");
    }

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

  /** Runs the example. */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates a CustomAudience object to represent the new audience.
    CustomAudience customAudience =
        CustomAudience.newBuilder()
            .setName("Example CustomAudience #" + getPrintableDateTime())
            .setDescription("Custom audiences who have searched specific terms on Google Search")
            // Matches customers by what they searched on Google Search.
            // Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
            //       of newly created custom audience. Use "AUTO" instead of these 2 options
            //       when creating a new custom audience.
            .setType(CustomAudienceType.SEARCH)
            .setStatus(CustomAudienceStatus.ENABLED)

            // Lists the members that this custom audience is composed of. Customers that meet any
            // of the membership conditions will be reached.

            // Adds Keywords or keyword phrases, which describe the customers' interests or search
            // terms.
            .addMembers(createCustomAudienceMember(CustomAudienceMemberType.KEYWORD, "mars cruise"))
            .addMembers(
                createCustomAudienceMember(CustomAudienceMemberType.KEYWORD, "jupiter cruise"))

            // Adds website URLs that your customers might visit.
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.URL, "http://www.example.com/locations/mars"))
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.URL, "http://www.example.com/locations/jupiter"))

            // Adds package names of Android apps which customers might install.
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.APP, "com.google.android.apps.adwords"))
            .build();

    // Creates an operation to add the CustomAudience.
    CustomAudienceOperation operation =
        CustomAudienceOperation.newBuilder().setCreate(customAudience).build();

    // Creates an API client and send the mutate request.
    try (CustomAudienceServiceClient serviceClient =
        googleAdsClient.getLatestVersion().createCustomAudienceServiceClient()) {
      // Issues the mutate request.
      MutateCustomAudiencesResponse response =
          serviceClient.mutateCustomAudiences(
              String.valueOf(customerId), ImmutableList.of(operation));

      // Prints some information about the result.
      System.out.printf(
          "New custom audience added with resource name: '%s'.\n",
          response.getResults(0).getResourceName());
    }
  }

  /**
   * Constructs a {@link CustomAudienceMember} from a {@link CustomAudienceMemberType} and value for
   * the member type.
   */
  private static CustomAudienceMember createCustomAudienceMember(
      CustomAudienceMemberType memberType, String value) {
    CustomAudienceMember.Builder builder =
        CustomAudienceMember.newBuilder().setMemberType(memberType);
    if (memberType == CustomAudienceMemberType.KEYWORD) {
      builder.setKeyword(value);
    } else if (memberType == CustomAudienceMemberType.URL) {
      builder.setUrl(value);
    } else if (memberType == CustomAudienceMemberType.APP) {
      builder.setApp(value);
    }
    return builder.build();
  }
}

      

C#

This example is not yet available in C#; you can take a look at the other languages.
    

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\Remarketing;

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\V6\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V6\GoogleAdsException;
use Google\Ads\GoogleAds\V6\Enums\CustomAudienceMemberTypeEnum\CustomAudienceMemberType;
use Google\Ads\GoogleAds\V6\Enums\CustomAudienceStatusEnum\CustomAudienceStatus;
use Google\Ads\GoogleAds\V6\Enums\CustomAudienceTypeEnum\CustomAudienceType;
use Google\Ads\GoogleAds\V6\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V6\Resources\CustomAudience;
use Google\Ads\GoogleAds\V6\Resources\CustomAudienceMember;
use Google\Ads\GoogleAds\V6\Services\CustomAudienceOperation;
use Google\ApiCore\ApiException;

/**
 * Illustrates adding a custom audience. Custom audiences help you reach your ideal audience by
 * entering relevant keywords, URLs and apps. For more information about custom audiences, see:
 * https://support.google.com/google-ads/answer/9805516.
 */
class AddCustomAudience
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_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
        ]);

        // 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
            );
        } 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
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a CustomAudience object to represent the new audience.
        $customAudience = new CustomAudience([
            'name' => 'Example CustomAudience #' . Helper::getPrintableDatetime(),
            'description' => 'Custom audiences who have searched specific terms on Google Search',
            // Matches customers by what they searched on Google Search.
            // Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
            //       of newly created custom audience. Use "AUTO" instead of these 2 options
            //       when creating a new custom audience.
            'type' => CustomAudienceType::SEARCH,
            'status' => CustomAudienceStatus::ENABLED,
            // Lists the members that this custom audience is composed of. Customers that meet any
            // of the membership conditions will be reached.
            'members' => [
                // Adds Keywords or keyword phrases, which describe the customers' interests or
                // search terms.
                self::createCustomAudienceMember(CustomAudienceMemberType::KEYWORD, "mars cruise"),
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::KEYWORD,
                    "jupiter cruise"
                ),
                // Adds website URLs that your customers might visit.
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::URL,
                    "http://www.example.com/locations/mars"
                ),
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::URL,
                    "http://www.example.com/locations/jupiter"
                ),
                // Adds package names of Android apps which customers might install.
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::APP,
                    "com.google.android.apps.adwords"
                )
            ]
        ]);

        // Creates the operation.
        $operation = new CustomAudienceOperation();
        $operation->setCreate($customAudience);

        // Issues a mutate request to add the custom audience and prints some information.
        $customAudienceServiceClient = $googleAdsClient->getCustomAudienceServiceClient();
        $response = $customAudienceServiceClient->mutateCustomAudiences($customerId, [$operation]);
        printf(
            "Created custom audience with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Constructs a custom audience member object for a given customer audience member type and
     * value.
     *
     * @param int $memberType the custom audience member type
     * @param string $value the custom audience member value
     * @return CustomAudienceMember the newly constructed customer audience member object
     */
    private static function createCustomAudienceMember(
        int $memberType,
        string $value
    ): CustomAudienceMember {
        $customerAudienceMember = new CustomAudienceMember(['member_type' => $memberType]);
        if ($memberType == CustomAudienceMemberType::KEYWORD) {
            $customerAudienceMember->setKeyword($value);
        } else if ($memberType == CustomAudienceMemberType::URL) {
            $customerAudienceMember->setUrl($value);
        } else if ($memberType == CustomAudienceMemberType::APP) {
            $customerAudienceMember->setApp($value);
        }
        return $customerAudienceMember;
    }
}

AddCustomAudience::main();

      

Python

#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This example illustrates adding a custom audience.

Custom audiences help you reach your ideal audience by entering relevant
keywords, URLs, and apps. For more information about custom audiences, see:
https://support.google.com/google-ads/answer/9805516
"""


import argparse
import sys
from uuid import uuid4

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


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

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    custom_audience_service = client.get_service("CustomAudienceService")

    # Create a custom audience operation.
    custom_audience_operation = client.get_type("CustomAudienceOperation")

    # Create a custom audience
    custom_audience = custom_audience_operation.create
    custom_audience.name = f"Example CustomAudience #{uuid4()}"
    custom_audience.description = (
        "Custom audiences who have searched specific terms on Google Search."
    )
    # Match customers by what they searched on Google Search. Note: "INTEREST"
    # or "PURCHASE_INTENT" is not allowed for the type field of a newly
    # created custom audience. Use "AUTO" instead of these two options when
    # creating a new custom audience.
    custom_audience.type_ = client.get_type(
        "CustomAudienceTypeEnum"
    ).CustomAudienceType.SEARCH
    custom_audience.status = client.get_type(
        "CustomAudienceStatusEnum"
    ).CustomAudienceStatus.ENABLED
    # List of members that this custom audience is composed of. Customers that
    # meet any of the membership conditions will be reached.
    member_type_enum = client.get_type(
        "CustomAudienceMemberTypeEnum"
    ).CustomAudienceMemberType
    member1 = client.get_type("CustomAudienceMember")
    member1.member_type = member_type_enum.KEYWORD
    member1.keyword = "mars cruise"
    member2 = client.get_type("CustomAudienceMember")
    member2.member_type = member_type_enum.KEYWORD
    member2.keyword = "jupiter cruise"
    member3 = client.get_type("CustomAudienceMember")
    member3.member_type = member_type_enum.URL
    member3.keyword = "http://www.example.com/locations/mars"
    member4 = client.get_type("CustomAudienceMember")
    member4.member_type = member_type_enum.URL
    member4.keyword = "http://www.example.com/locations/jupiter"
    custom_audience.members.extend([member1, member2, member3, member4])

    # Add the custom audience.
    custom_audience_response = (
        custom_audience_service.mutate_custom_audiences(
            customer_id=customer_id, operations=[custom_audience_operation]
        )
    )

    print(
        "New custom audience added with resource name: "
        f"'{custom_audience_response.results[0].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="v6")

    parser = argparse.ArgumentParser(
        description="Adds a custom audience for a specified customer."
    )
    # 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.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_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 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example uses Customer Match to create a new user list (a.k.a. audience)
# and adds users to it.
#
# This example illustrates adding a custom audience. Custom audiences help you
# reach your ideal audience by entering relevant keywords, URLs and apps.
# For more information about custom audiences, see:
# https://support.google.com/google-ads/answer/9805516.

require 'optparse'
require 'google/ads/google_ads'
require 'date'
require 'digest'

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

  # Creates a custom audience operation.
  operation = client.operation.create_resource.custom_audience do |ca|
    ca.name = "Example Custom Audience ##{(Time.new.to_f * 1000).to_i}"
    ca.description = "Custom audiences who have searched specific terms on Google Search"
    # Match customers by what they searched on Google Search.
    # Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
    # of newly created custom audience. Use "AUTO" instead of these 2 options
    # when creating a new custom audience.
    ca.type = :SEARCH
    ca.status = :ENABLED
    # List of members that this custom audience is composed of. Customers that
    # meet any of the membership conditions will be reached.
    ca.members += [
      # Keywords or keyword phrases, which describe the customers' interests
      # or search terms.
      create_custom_audience_member(client, :KEYWORD, "Mars Cruise"),
      create_custom_audience_member(client, :KEYWORD, "Jupiter Cruise"),
      # Website URLs that your customers might visit.
      create_custom_audience_member(client, :URL, "http://www.example.com/locations/mars"),
      create_custom_audience_member(client, :URL, "http://www.example.com/locations/jupiter"),
      # Package names of Android apps which customers might install.
      create_custom_audience_member(client, :APP, "com.google.android.apps.adwords"),
    ]
  end

  # Issues a mutate request to add the custom audience.
  response = client.service.custom_audience.mutate_custom_audiences(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "New custom audience added with resource name: " \
    "'#{response.results.first.resource_name}'."
end

# Creates a custom audience member.
def create_custom_audience_member(client, member_type, member_value)
  client.resource.custom_audience_member do |m|
    m.member_type = member_type
    case member_type
    when :KEYWORD
      m.keyword = member_value
    when :URL
      m.url = member_value
    when :APP
      m.app = member_value
    else
      raise "Invalid audience member type."
    end
  end
end

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

  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.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_custom_audience(options.fetch(:customer_id).tr("-", ""))
  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 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example illustrates adding a custom audience. Custom audiences help you
# reach your ideal audience by entering relevant keywords, URLs and apps. For more
# information about custom audiences, see:
# https://support.google.com/google-ads/answer/9805516.

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::V6::Resources::CustomAudience;
use Google::Ads::GoogleAds::V6::Resources::CustomAudienceMember;
use Google::Ads::GoogleAds::V6::Enums::CustomAudienceTypeEnum qw(SEARCH);
use Google::Ads::GoogleAds::V6::Enums::CustomAudienceStatusEnum qw(ENABLED);
use Google::Ads::GoogleAds::V6::Enums::CustomAudienceMemberTypeEnum
  qw(KEYWORD URL APP);
use
  Google::Ads::GoogleAds::V6::Services::CustomAudienceService::CustomAudienceOperation;

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";

sub add_custom_audience {
  my ($api_client, $customer_id) = @_;

  # Create a custom audience.
  my $custom_audience =
    Google::Ads::GoogleAds::V6::Resources::CustomAudience->new({
      name => "Example CustomAudience #" . uniqid(),
      description =>
        "Custom audiences who have searched specific terms on Google Search",
      # Match customers by what they searched on Google Search.
      # Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
      # of newly created custom audience. Use "AUTO" instead of these 2 options
      # when creating a new custom audience.
      type   => SEARCH,
      status => ENABLED,
      # List of members that this custom audience is composed of. Customers that
      # meet any of the membership conditions will be reached.
      members => [
        # Keywords or keyword phrases, which describe the customers' interests
        # or search terms.
        create_custom_audience_member(KEYWORD, "mars cruise"),
        create_custom_audience_member(KEYWORD, "jupiter cruise"),
        # Website URLs that your customers might visit.
        create_custom_audience_member(URL,
          "http://www.example.com/locations/mars"
        ),
        create_custom_audience_member(URL,
          "http://www.example.com/locations/jupiter"
        ),
        # Package names of Android apps which customers might install.
        create_custom_audience_member(APP, "com.google.android.apps.adwords"),
      ]});

  # Create a custom audience operation.
  my $custom_audience_operation =
    Google::Ads::GoogleAds::V6::Services::CustomAudienceService::CustomAudienceOperation
    ->new({create => $custom_audience});

  # Add the custom audience.
  my $custom_audiences_response = $api_client->CustomAudienceService()->mutate({
      customerId => $customer_id,
      operations => [$custom_audience_operation]});

  printf "New custom audience added with resource name: '%s'.\n",
    $custom_audiences_response->{results}[0]{resourceName};

  return 1;
}

# Creates a custom audience member.
sub create_custom_audience_member {
  my ($member_type, $value) = @_;
  my $custom_audience_member =
    Google::Ads::GoogleAds::V6::Resources::CustomAudienceMember->new({
      memberType => $member_type
    });

  if ($member_type eq KEYWORD) {
    $custom_audience_member->{keyword} = $value;
  } elsif ($member_type eq URL) {
    $custom_audience_member->{url} = $value;
  } elsif ($member_type eq APP) {
    $custom_audience_member->{app} = $value;
  }

  return $custom_audience_member;
}

# 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);

# 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);

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

=pod

=head1 NAME

add_custom_audience

=head1 DESCRIPTION

This example illustrates adding a custom audience. Custom audiences help you
reach your ideal audience by entering relevant keywords, URLs and apps. For more
information about custom audiences, see:
https://support.google.com/google-ads/answer/9805516.

=head1 SYNOPSIS

add_custom_audience.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut