自定义受众群体

借助自定义受众群体,您可以通过输入相关的关键字、网址和应用名称来覆盖理想的受众群体。这也是将先前的两款可自定义的产品(自定义的意向细分受众群自定义的兴趣相似受众群体)迁移到受众群体产品套件的简化版辅助工作流中。

您可以在展示广告系列、发现广告系列、Gmail 广告系列和视频广告系列中设置自定义受众群体,方法是添加与您的产品或服务相关的特定关键字、网址和应用。然后,Google Ads 便会在网页、应用和视频上向具有这方面兴趣或购买意愿的用户展示广告。

自定义受众群体的工作原理

自定义受众群体会自动选择最适合您广告系列需求的受众群体。例如,跑鞋公司可能希望覆盖狂热的马拉松跑步爱好者,而不是运动爱好者的兴趣相似的受众群体。利用自定义受众群体,跑鞋公司可以通过以下方式界定此受众群体:

  1. 输入“5000 米长跑”“铁人三项运动员”或“长跑运动员”等兴趣。

  2. 使用内容与跑步、训练计划、马拉松营养学及其他马拉松主题相关的网站的网址。

  3. 输入马拉松铁杆跑友可能会感兴趣的“健康与健身”类别的应用,例如“Google 健身”。

创建自定义受众群体

以下代码示例演示了如何使用 CustomAudienceService 创建 CustomAudience

创建自定义受众群体的代码示例

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.v16.enums.CustomAudienceMemberTypeEnum.CustomAudienceMemberType;
import com.google.ads.googleads.v16.enums.CustomAudienceStatusEnum.CustomAudienceStatus;
import com.google.ads.googleads.v16.enums.CustomAudienceTypeEnum.CustomAudienceType;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.resources.CustomAudience;
import com.google.ads.googleads.v16.resources.CustomAudienceMember;
import com.google.ads.googleads.v16.services.CustomAudienceOperation;
import com.google.ads.googleads.v16.services.CustomAudienceServiceClient;
import com.google.ads.googleads.v16.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#

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

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V16.Errors;
using Google.Ads.GoogleAds.V16.Resources;
using Google.Ads.GoogleAds.V16.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V16.Enums.CustomAudienceMemberTypeEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.CustomAudienceStatusEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.CustomAudienceTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// 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.
    /// </summary>
    public class AddCustomAudience : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddCustomAudience"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the conversion action is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the conversion action is added.")]
            public long CustomerId { 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);

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string 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.";

        /// <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 conversion action is
        /// added.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the CustomAudienceService client.
            CustomAudienceServiceClient customAudienceServiceClient =
                client.GetService(Services.V16.CustomAudienceService);

            // Create a custom audience.
            CustomAudience customAudience = new CustomAudience
            {
                Name = $"Example CustomAudience #{ExampleUtilities.GetRandomString()}",
                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 = CustomAudienceType.Search,
                Status = CustomAudienceStatus.Enabled,
            };

            // Add custom audience members to the custom audience. Customers that meet any of the
            // membership conditions will be reached.
            // Keywords or keyword phrases, which describe the customers' interests or search terms.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Keyword,
                "mars cruise"));
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Keyword,
                "jupiter cruise"));
            // Website URLs that your customers might visit.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Url,
                "http://www.example.com/locations/mars"));
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Url,
                "http://www.example.com/locations/jupiter"));
            // Package names of Android apps which customers might install.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.App,
                "com.google.android.apps.adwords"));

            // Create a custom audience operation.
            CustomAudienceOperation customAudienceOperation = new CustomAudienceOperation
            {
                Create = customAudience
            };

            try
            {
                // Add the custom audience and display the results.
                MutateCustomAudiencesResponse customAudiencesResponse = customAudienceServiceClient
                    .MutateCustomAudiences(customerId.ToString(), new[] { customAudienceOperation });

                Console.WriteLine("New custom audience added with resource name: " +
                    $"'{customAudiencesResponse.Results.First().ResourceName}'.");
            }
            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 a custom audience member.
        /// </summary>
        /// <param name="memberType">The intended type of the new audience member.</param>
        /// <param name="value">The custom value to assign to the new audience member.</param>
        /// <returns></returns>
        public CustomAudienceMember CreateCustomAudienceMember(CustomAudienceMemberType memberType,
            string value)
        {
            CustomAudienceMember customAudienceMember = new CustomAudienceMember
            {
                MemberType = memberType
            };

            switch (memberType)
            {
                case CustomAudienceMemberType.Keyword:
                    customAudienceMember.Keyword = value;
                    break;

                case CustomAudienceMemberType.Url:
                    customAudienceMember.Url = value;
                    break;

                case CustomAudienceMemberType.App:
                    customAudienceMember.App = value;
                    break;
            }

            return customAudienceMember;
        }
    }
}

      

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\V16\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsException;
use Google\Ads\GoogleAds\V16\Enums\CustomAudienceMemberTypeEnum\CustomAudienceMemberType;
use Google\Ads\GoogleAds\V16\Enums\CustomAudienceStatusEnum\CustomAudienceStatus;
use Google\Ads\GoogleAds\V16\Enums\CustomAudienceTypeEnum\CustomAudienceType;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Resources\CustomAudience;
use Google\Ads\GoogleAds\V16\Resources\CustomAudienceMember;
use Google\Ads\GoogleAds\V16\Services\CustomAudienceOperation;
use Google\Ads\GoogleAds\V16\Services\MutateCustomAudiencesRequest;
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)
            // 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
            );
        } 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(
            MutateCustomAudiencesRequest::build($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);
        } elseif ($memberType == CustomAudienceMemberType::URL) {
            $customerAudienceMember->setUrl($value);
        } elseif ($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.enums.CustomAudienceTypeEnum.SEARCH
    custom_audience.status = client.enums.CustomAudienceStatusEnum.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.enums.CustomAudienceMemberTypeEnum

    member1 = create_custom_audience_member(
        client, member_type_enum.KEYWORD, "mars cruise"
    )

    member2 = create_custom_audience_member(
        client, member_type_enum.KEYWORD, "jupiter cruise"
    )

    member3 = create_custom_audience_member(
        client, member_type_enum.URL, "http://www.example.com/locations/mars"
    )

    member4 = create_custom_audience_member(
        client, member_type_enum.URL, "http://www.example.com/locations/jupiter"
    )

    member5 = create_custom_audience_member(
        client, member_type_enum.APP, "com.google.android.apps.adwords"
    )

    custom_audience.members.extend(
        [member1, member2, member3, member4, member5]
    )

    # 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}'"
    )


def create_custom_audience_member(client, member_type, value):
    """Creates a custom audience member for a given member type and value.

    Args:
        client: an initialized GoogleAdsClient instance.
        member_type: the custom audience member type.
        value: the custom audience member value.

    Returns:
        A newly created CustomAudienceMember.
    """
    member = client.get_type("CustomAudienceMember")
    member.member_type = member_type

    member_type_enum = client.enums.CustomAudienceMemberTypeEnum

    if member_type == member_type_enum.KEYWORD:
        member.keyword = value
    elif member_type == member_type_enum.URL:
        member.url = value
    elif member_type == member_type_enum.APP:
        member.app = value
    else:
        raise ValueError(
            "The member type must be a MemberTypeEnum value of KEYWORD, URL, or APP"
        )

    return member


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

    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'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 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::V16::Resources::CustomAudience;
use Google::Ads::GoogleAds::V16::Resources::CustomAudienceMember;
use Google::Ads::GoogleAds::V16::Enums::CustomAudienceTypeEnum   qw(SEARCH);
use Google::Ads::GoogleAds::V16::Enums::CustomAudienceStatusEnum qw(ENABLED);
use Google::Ads::GoogleAds::V16::Enums::CustomAudienceMemberTypeEnum
  qw(KEYWORD URL APP);
use
  Google::Ads::GoogleAds::V16::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::V16::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::V16::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::V16::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

      

定位到自定义受众群体

创建细分受众群后,下一步是定位该细分受众群。您可以通过设置 CampaignCriterion.custom_audience 字段在广告系列一级定位自定义受众群体,也可以通过设置 AdGroupCriterion.custom_audience 字段在广告组层级定位自定义受众群体。

自定义受众群体建议

从 Google Ads API v16 开始,您可以检索 CUSTOM_AUDIENCE_OPT_IN 类型的建议,此类建议建议创建自定义受众群体。如果您是第三方广告客户,并且允许用户创建和管理细分受众群,那么这种方法尤其有用。当用户根据建议创建自定义受众群体时,有助于提高帐号的总体优化得分。

如需了解详情,请参阅优化得分和建议指南。

查看名单效果

如需收集细分受众群的性能数据,请针对 ad_group_audience_viewcampaign_audience_view 资源发出搜索请求。例如,您可以查看 conversionscost_per_conversion 来确定定位细分受众群是否确实会促成更多转化,然后相应地调整出价调节系数。

SELECT
  ad_group_criterion.criterion_id,
  metrics.conversions,
  metrics.cost_per_conversion
FROM ad_group_audience_view