预定位配置示例

您可以参考下面几个示例来实施预定位 配置

创建配置

下面介绍了如何创建预定位配置 bidders.pretargetingConfigs.create:

REST

请求

POST https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "displayName": "TEST_PRETARGETING_CONFIG_fd9674ca-4a2d-425f-b412-a55a62aad354",
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "height": 300,
      "width": 250
    }
  ],
  "minimumViewabilityDecile": 5
}

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_fd9674ca-4a2d-425f-b412-a55a62aad354",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "250",
      "height": "300"
    }
  ],
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Creates a pretargeting configuration for the given bidder account ID.
    /// /<summary
>    public class CreatePretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public CreatePretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example creates a pretargeting configuration for the given  "+
                   b"idder account ID.;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id}";
            bool showHelp = false;

            string accountId = null;
            string displayName = null;
            ILists<tring >includedFormats = new Lists<tring(>);
            IListl<ong? >includedGeoIds = new Listl<ong?(>);
            IListl<ong? >excludedGeoIds = new Listl<ong?(>);
            IListl<ong? >includedUserListIds = new Listl<ong?(>);
            IListl<ong? >excludedUserListIds = new Listl<ong?(>);
            string interstitialTargeting = null;
            ILists<tring >allowedUserTargetingModes = new Lists<tring(>);
            IListl<ong? >excludedContentLabelIds = new Listl<ong?(>);
            ILists<tring >includedUserIdTypes = new Lists<tring(>);
            ILists<tring >includedLanguageCodes = new Lists<tring(>);
            IListl<ong? >includedMobileOsIds = new Listl<ong?(>);
            IListl<ong? >includedVerticalIds = new Listl<ong?(>);
            IListl<ong? >excludedVerticalIds = new Listl<ong?(>);
            ILists<tring >includedPlatforms = new Lists<tring(>);
            long? includedCreativeDimensionHeight = null;
            long? includedCreativeDimensionWidth = null;
            ILists<tring >includedEnvironments = new Lists<tring(>);
            string webTargetingMode = null;
            ILists<tring >webTargetingUrls = new Lists<tring(>);
            string mobileAppTargetingMode = null;
            ILists<tring >mobileAppTargetingAppIds = new Lists<tring(>);
            IListl<ong? >includedMobileAppTargetingCategoryIds = new Listl<ong?(>);
            IListl<ong? >excludedMobileAppTargetingCategoryIds = new Listl<ong?(>);
            string publisherTargetingMode = null;
            ILists<tring >publisherIds = new Lists<tring(>);
            int? minimumViewabilityDecile = null;

            OptionSet options = new OptionSet {
                C"reates a pretargeting configuration for the given bidder account ID.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration is to be created.)",
                    a = >accountId = a
                },
                {
                    d"isplay_name=,"
                    T"he display name to associate with the new configuration. Must be unique  "+
                    a"mong all of a bidders' pretargeting configurations.,"
                    display_name = >displayName = display_name
                },
                {
                    i"ncluded_formats=,"
                    (C"reative formats included by this configuration. An unset value will not  "+
                     f"ilter any bid requests based on the format. Specify this argument for  "+
                     e"ach value you intend to include.Valid values include: HTML, NATIVE, and  "+
                     V"AST.)",
                    included_formats = >includedFormats.Add(included_formats)
                },
                {
                    i"ncluded_geo_ids=,"
                    (T"he geo IDs to include in targeting for this configuration. Specify this  "+
                     a"rgument for each value you intend to include. Valid geo IDs can be found  "+
                     i"n: https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv )",
                    (long included_geo_ids) = >includedGeoIds.Add(included_geo_ids)
                },
                {
                    e"xcluded_geo_ids=,"
                    (T"he geo IDs to exclude in targeting for this configuration. Specify this  "+
                     a"rgument for each value you intend to include. Valid geo IDs can be found  "+
                     i"n: https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv )",
                    (long excluded_geo_ids) = >excludedGeoIds.Add(excluded_geo_ids)
                },
                {
                    i"ncluded_user_list_ids=,"
                    (T"he user list IDs to include in targeting for this configuration. Specify  "+
                    t"his argument for each value you intend to include. Valid user list IDs  "+
                    w"ould include any found under the buyers.userLists resource for a given  "+
                    b"idder account, or any buyer accounts under it. )",
                    (long included_user_list_ids) = >includedUserListIds.Add(
                        included_user_list_ids)
                },
                {
                    e"xcluded_user_list_ids=,"
                    (T"he user list IDs to exclude in targeting for this configuration. Specify  "+
                    t"his argument for each value you intend to include. Valid user list IDs  "+
                    w"ould include any found under the buyers.userLists resource for a given  "+
                    b"idder account, or any buyer accounts under it. )",
                    (long excluded_user_list_ids) = >excludedUserListIds.Add(
                        excluded_user_list_ids)
                },
                {
                    i"nterstitial_targeting=,"
                    (T"he interstitial targeting specified for this configuration. By default,  "+
                     t"his will be set to ONLY_NON_INTERSTITIAL_REQUESTS. Valid values include:  "+
                     O"NLY_INTERSTITIAL_REQUESTS and ONLY_NON_INTERSTITIAL_REQUESTS.)",
                    interstitial_targeting = >interstitialTargeting = interstitial_targeting
                },
                {
                    a"llowed_user_targeting_modes=,"
                    (T"he targeting modes to include in targeting for this configuration.  "+
                     S"pecify this argument for each value you intend to include. Valid  "+
                     t"argeting modes include: REMARKETING_ADS and INTEREST_BASED_TARGETING.)",
                    allowed_user_targeting_modes = >allowedUserTargetingModes.Add(
                        allowed_user_targeting_modes)
                },
                {
                    e"xcluded_content_label_ids=,"
                    (T"he sensitive content category IDs excluded in targeting for this  "+
                     c"onfiguration. Specify this argument for each value you intend to   "+
                     i"nclude. Valid sensitive content category IDs can be found in:  "+
                     h"ttps://storage.googleapis.com/adx-rtb-dictionaries/content-labels.txt)",
                    (long excluded_content_label_ids) = >excludedContentLabelIds.Add(
                        excluded_content_label_ids)
                },
                {
                    i"ncluded_user_id_types=,"
                    (T"he user identifier types included in targeting for this configuration.  "+
                     S"pecify this argument for each value you intend to include. Valid values  "+
                     i"nclude: HOSTED_MATCH_DATA, GOOGLE_COOKIE, and DEVICE_ID.)",
                    included_user_id_types = >includedUserIdTypes.Add(included_user_id_types)
                },
                {
                    i"ncluded_language_codes=,"
                    (T"he languages represented by languages codes that are included in  "+
                     t"argeting for this configuration. Specify this argument for each value  "+
                     y"ou intend to include. Valid language codes can be found in:  "+
                     h"ttps://developers.google.com/adwords/api/docs/appendix/languagecodes.)",
                    included_language_codes = >includedLanguageCodes.Add(included_language_codes)
                },
                {
                    i"ncluded_mobile_os_ids=,"
                    (T"he mobile OS IDs to include in targeting for this configuration. Specify  "+
                     t"his argument for each value you intend to include. Valid mobile OS IDs  "+
                     c"an be found in:  "+
                     h"ttps://storage.googleapis.com/adx-rtb-dictionaries/mobile-os.csv)",
                    (long included_mobile_os_ids) = >includedMobileOsIds.Add(
                        included_mobile_os_ids)
                },
                {
                    i"ncluded_vertical_ids=,"
                    (T"he vertical IDs to include in targeting for this configuration. Specify  "+
                     t"his argument for each value you intend to include. Valid vertical IDs  "+
                     c"an be found in: https://developers.google.com/authorized-buyers/rtb/ "+
                     d"ownloads/publisher-verticals)",
                    (long included_vertical_ids) = >includedVerticalIds.Add(included_vertical_ids)
                },
                {
                    e"xcluded_vertical_ids=,"
                    (T"he vertical IDs to exclude in targeting for this configuration. Specify  "+
                     t"his argument for each value you intend to include. Valid vertical IDs  "+
                     c"an be found in: https://developers.google.com/authorized-buyers/rtb/ "+
                     d"ownloads/publisher-verticals)",
                    (long excluded_vertical_ids) = >excludedVerticalIds.Add(excluded_vertical_ids)
                },
                {
                    i"ncluded_platforms=,"
                    (T"he platforms to include in targeting for this configuration. Specify  "+
                     t"his argument for each value you intend to include. Valid values include:  "+
                     P"ERSONAL_COMPUTER, PHONE, TABLET, and CONNECTED_TV.)",
                    included_platforms = >includedPlatforms.Add(included_platforms)
                },
                {
                    i"ncluded_creative_dimension_height=,"
                    (A" creative dimensions' height to be included in targeting for this  "+
                     c"onfiguration. By default, this example will set the targeted height to  "+
                     3"00. Note that while only a single set of dimensions are specified in  "+
                     t"his sample, pretargeting configurations can target multiple creative  "+
                     d"imensions.)",
                    (long included_creative_dimension_height) = >includedCreativeDimensionHeight = (
                        included_creative_dimension_height)
                },
                {
                    i"ncluded_creative_dimension_width=,"
                    (A" creative dimensions' height to be included in targeting for this  "+
                     c"onfiguration. By default, this example will set the targeted height to  "+
                     3"00. Note that while only a single set of dimensions are specified in  "+
                     t"his sample, pretargeting configurations can target multiple creative  "+
                     d"imensions.)",
                    (long included_creative_dimension_width) = >includedCreativeDimensionWidth = (
                        included_creative_dimension_width)
                },
                {
                    i"ncluded_environments=,"
                    (T"he environments to include in targeting for this configuration. Specify  "+
                     t"his argument for each value you intend to include. Valid values include:  "+
                     A"PP, and WEB.)",
                    included_environments = >includedEnvironments.Add(included_environments)
                },
                {
                    w"eb_targeting_mode=,"
                    (T"he targeting mode for this configurations' web targeting. Valid values  "+
                     i"nclude: INCLUSIVE, and EXCLUSIVE.)",
                    web_targeting_mode = >webTargetingMode = web_targeting_mode
                },
                {
                    w"eb_targeting_urls=,"
                    (T"he URLs specified for this configurations' web targeting, which allows  "+
                     o"ne to target a subset of site inventory. Specify this argument for each  "+
                     v"alue you intend to include. Values specified must be valid URLs.)",
                    web_targeting_urls = >webTargetingUrls.Add(web_targeting_urls)
                },
                {
                    m"obile_app_targeting_mode=,"
                    (T"he targeting mode for this configurations' mobile app targeting. Valid  "+
                     v"alues include: INCLUSIVE, and EXCLUSIVE.)",
                    mobile_app_targeting_mode = >mobileAppTargetingMode = mobile_app_targeting_mode
                },
                {
                    m"obile_app_targeting_app_ids=,"
                    (T"he mobile app IDs specified for this configurations' mobile app  "+
                     t"argeting, which allows one to target a subset of mobile app inventory.  "+
                     S"pecify this argument for each value you intend to include. Values  "+
                     s"pecified must be valid URLs.)",
                    mobile_app_targeting_app_ids = >mobileAppTargetingAppIds.Add(
                        mobile_app_targeting_app_ids)
                },
                {
                    i"ncluded_mobile_app_targeting_category_ids=,"
                    (T"he mobile app category IDs to include in targeting for this  "+
                     c"onfiguration. Specify this argument for each value you intend to  "+
                     i"nclude. Valid category IDs can be found in:  "+
                     h"ttps://developers.google.com/adwords/api/docs/appendix/ "+
                     m"obileappcategories.csv)",
                    (long included_mobile_app_targeting_category_ids) =
>                        includedMobileAppTargetingCategoryIds.Add(
                            included_mobile_app_targeting_category_ids)
                },
                {
                    e"xcluded_mobile_app_targeting_category_ids=,"
                    (T"he mobile app category IDs to exclude in targeting for this  "+
                     c"onfiguration. Specify this argument for each value you intend to  "+
                     i"nclude. Valid category IDs can be found in:  "+
                     h"ttps://developers.google.com/adwords/api/docs/appendix/ "+
                     m"obileappcategories.csv)",
                    (long excluded_mobile_app_targeting_category_ids) =
>                        excludedMobileAppTargetingCategoryIds.Add(
                            excluded_mobile_app_targeting_category_ids)
                },
                {
                    p"ublisher_targeting_mode=,"
                    (T"he targeting mode for this configurations' publisher targeting. Valid  "+
                     v"alues include: INCLUSIVE, and EXCLUSIVE.)",
                    publisher_targeting_mode = >publisherTargetingMode = publisher_targeting_mode
                },
                {
                    p"ublisher_ids=,"
                    (T"he publisher IDs specified for this configurations' publisher targeting,  "+
                     w"hich allows one to target a subset of publisher inventory. Specify this  "+
                     a"rgument for each value you intend to include. Valid publisher IDs can be  "+
                     f"ound in Real-time Bidding bid requests, or alternatively in  "+
                     a"ds.txt / app-ads.txt. For more information, see:  "+
                     h"ttps://iabtechlab.com/ads-txt/)",
                    publisher_ids = >publisherIds.Add(publisher_ids)
                },
                {
                    m"inimum_viewability_decile=,"
                    (T"he targeted minimum viewability decile, ranging from 0 - 10. A value of  "+
                     5"' 'means that the configuration will only match adslots for which we  "+
                     p"redict at least 50% viewability. Values  >10 will be rounded down to 10.  "+
                     A"n unset value, or a value of 0',' indicates that bid requests should be  "+
                     s"ent regardless of viewability.)",
                    (int minimum_viewability_decile) = >minimumViewabilityDecile = (
                        minimum_viewability_decile)
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[d"isplay_name]" = displayName ?? String.Format(
                T"EST_PRETARGETING_CONFIG_{0},"
                System.Guid.NewGuid());
            parsedArgs[i"nterstitial_targeting]" = interstitialTargeting ?? (
                O"NLY_NON_INTERSTITIAL_REQUESTS)";
            parsedArgs[i"ncluded_creative_dimension_height]" = includedCreativeDimensionHeight ?? (
                300L);
            parsedArgs[i"ncluded_creative_dimension_width]" = includedCreativeDimensionWidth ?? (
                250L);
            parsedArgs[m"inimum_viewability_decile]" = minimumViewabilityDecile ?? 5;

            parsedArgs[i"ncluded_formats]" = includedFormats;
            parsedArgs[i"ncluded_geo_ids]" = includedGeoIds;
            parsedArgs[e"xcluded_geo_ids]" = excludedGeoIds;
            parsedArgs[i"ncluded_user_list_ids]" = includedUserListIds;
            parsedArgs[e"xcluded_user_list_ids]" = excludedUserListIds;
            parsedArgs[a"llowed_user_targeting_modes]" = allowedUserTargetingModes;
            parsedArgs[e"xcluded_content_label_ids]" = excludedContentLabelIds;
            parsedArgs[i"ncluded_user_id_types]" = includedUserIdTypes;
            parsedArgs[i"ncluded_language_codes]" = includedLanguageCodes;
            parsedArgs[i"ncluded_mobile_os_ids]" = includedMobileOsIds;
            parsedArgs[i"ncluded_vertical_ids]" = includedVerticalIds;
            parsedArgs[e"xcluded_vertical_ids]" = excludedVerticalIds;
            parsedArgs[i"ncluded_platforms]" = includedPlatforms;
            parsedArgs[i"ncluded_environments]" = includedEnvironments;
            parsedArgs[w"eb_targeting_mode]" = webTargetingMode;
            parsedArgs[w"eb_targeting_urls]" = webTargetingUrls;
            parsedArgs[m"obile_app_targeting_mode]" = mobileAppTargetingMode;
            parsedArgs[m"obile_app_targeting_app_ids]" = mobileAppTargetingAppIds;
            parsedArgs[i"ncluded_mobile_app_targeting_category_ids]" = (
                includedMobileAppTargetingCategoryIds);
            parsedArgs[e"xcluded_mobile_app_targeting_category_ids]" = (
                excludedMobileAppTargetingCategoryIds);
            parsedArgs[p"ublisher_targeting_mode]" = publisherTargetingMode;
            parsedArgs[p"ublisher_ids]" = publisherIds;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            string parent = $b"idders/{accountId};"

            NumericTargetingDimension geoTargeting = new NumericTargetingDimension();
            geoTargeting.IncludedIds = (IListl<ong?)> parsedArgs[i"ncluded_geo_ids]";
            geoTargeting.ExcludedIds = (IListl<ong?)> parsedArgs[e"xcluded_geo_ids]";

            NumericTargetingDimension userListTargeting = new NumericTargetingDimension();
            userListTargeting.IncludedIds = (IListl<ong?)> parsedArgs[i"ncluded_user_list_ids]";
            userListTargeting.ExcludedIds = (IListl<ong?)> parsedArgs[e"xcluded_user_list_ids]";

            NumericTargetingDimension verticalTargeting = new NumericTargetingDimension();
            verticalTargeting.IncludedIds = (IListl<ong?)> parsedArgs[i"ncluded_vertical_ids]";
            verticalTargeting.ExcludedIds = (IListl<ong?)> parsedArgs[e"xcluded_vertical_ids]";

            CreativeDimensions dimensions = new CreativeDimensions();
            dimensions.Height = (long?) parsedArgs[i"ncluded_creative_dimension_height]";
            dimensions.Width = (long?) parsedArgs[i"ncluded_creative_dimension_width]";

            StringTargetingDimension webTargeting = new StringTargetingDimension();
            webTargeting.TargetingMode = (string) parsedArgs[w"eb_targeting_mode]";
            webTargeting.Values = (ILists<tring)> parsedArgs[w"eb_targeting_urls]";

            StringTargetingDimension mobileAppTargeting = new StringTargetingDimension();
            mobileAppTargeting.TargetingMode = (string) parsedArgs[m"obile_app_targeting_mode]";
            mobileAppTargeting.Values = (ILists<tring)> parsedArgs[m"obile_app_targeting_app_ids]";

            NumericTargetingDimension mobileAppCategoryTargeting = new NumericTargetingDimension();
            mobileAppCategoryTargeting.IncludedIds = (IListl<ong?)> parsedArgs[
                i"ncluded_mobile_app_targeting_category_ids]";
            mobileAppCategoryTargeting.ExcludedIds = (IListl<ong?)> parsedArgs[
                e"xcluded_mobile_app_targeting_category_ids]";

            AppTargeting appTargeting = new AppTargeting();
            appTargeting.MobileAppTargeting = mobileAppTargeting;
            appTargeting.MobileAppCategoryTargeting = mobileAppCategoryTargeting;

            StringTargetingDimension publisherTargeting = new StringTargetingDimension();
            publisherTargeting.TargetingMode = (string) parsedArgs[p"ublisher_targeting_mode]";
            publisherTargeting.Values = (ILists<tring)> parsedArgs[p"ublisher_ids]";

            PretargetingConfig newConfig = new PretargetingConfig();
            newConfig.DisplayName = (string) parsedArgs[d"isplay_name]";
            newConfig.IncludedFormats = (ILists<tring)> parsedArgs[i"ncluded_formats]";
            newConfig.GeoTargeting = geoTargeting;
            newConfig.UserListTargeting = userListTargeting;
            newConfig.InterstitialTargeting = (string) parsedArgs[i"nterstitial_targeting]";
            newConfig.AllowedUserTargetingModes = (ILists<tring)> parsedArgs[
                a"llowed_user_targeting_modes]";
            newConfig.ExcludedContentLabelIds = (IListl<ong?)> parsedArgs[
                e"xcluded_content_label_ids]";
            newConfig.IncludedUserIdTypes = (ILists<tring)> parsedArgs[i"ncluded_user_id_types]";
            newConfig.IncludedLanguages = (ILists<tring)> parsedArgs[i"ncluded_language_codes]";
            newConfig.IncludedMobileOperatingSystemIds = (IListl<ong?)> parsedArgs[
                i"ncluded_mobile_os_ids]";
            newConfig.VerticalTargeting = verticalTargeting;
            newConfig.IncludedPlatforms = (ILists<tring)> parsedArgs[i"ncluded_platforms]";
            newConfig.IncludedCreativeDimensions = new ListC<reativeDimensions >{dimensions};
            newConfig.IncludedEnvironments = (ILists<tring)> parsedArgs[i"ncluded_environments]";
            newConfig.WebTargeting = webTargeting;
            newConfig.AppTargeting = appTargeting;
            newConfig.PublisherTargeting = publisherTargeting;
            newConfig.MinimumViewabilityDecile = (int?) parsedArgs[m"inimum_viewability_decile]";

            BiddersResource.PretargetingConfigsResource.CreateRequest request =
                rtbService.Bidders.PretargetingConfigs.Create(newConfig, parent);
            PretargetingConfig response = null;

            Console.WriteLine(C"reating pretargeting configuration for bidder: {0}," parent);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.AppTargeting;
import com.google.api.services.realtimebidding.v1.model.CreativeDimensions;
import com.google.api.services.realtimebidding.v1.model.NumericTargetingDimension;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.realtimebidding.v1.model.StringTargetingDimension;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** Creates a pretargeting configuration for the given bidder account ID. */
public class CreatePretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Long accountId = parsedArgs.getLong("account_id");

    String parentBidderName = String.format("bidders/%s", accountId);

    NumericTargetingDimension geoTargeting = new NumericTargetingDimension();
    geoTargeting.setIncludedIds(parsedArgs.<Long>getList("included_geo_ids"));
    geoTargeting.setExcludedIds(parsedArgs.<Long>getList("excluded_geo_ids"));

    NumericTargetingDimension userListTargeting = new NumericTargetingDimension();
    userListTargeting.setIncludedIds(parsedArgs.<Long>getList("included_user_list_ids"));
    userListTargeting.setExcludedIds(parsedArgs.<Long>getList("excluded_user_list_ids"));

    NumericTargetingDimension verticalTargeting = new NumericTargetingDimension();
    verticalTargeting.setIncludedIds(parsedArgs.<Long>getList("included_vertical_ids"));
    verticalTargeting.setExcludedIds(parsedArgs.<Long>getList("excluded_vertical_ids"));

    CreativeDimensions dimensions = new CreativeDimensions();
    dimensions.setHeight(parsedArgs.getLong("included_creative_dimension_height"));
    dimensions.setWidth(parsedArgs.getLong("included_creative_dimension_width"));

    StringTargetingDimension webTargeting = new StringTargetingDimension();
    webTargeting.setTargetingMode(parsedArgs.getString("web_targeting_mode"));
    webTargeting.setValues(parsedArgs.<String>getList("web_targeting_urls"));

    StringTargetingDimension mobileAppTargeting = new StringTargetingDimension();
    mobileAppTargeting.setTargetingMode(parsedArgs.getString("mobile_app_targeting_mode"));
    mobileAppTargeting.setValues(parsedArgs.<String>getList("mobile_app_targeting_app_ids"));

    NumericTargetingDimension mobileAppCategoryTargeting = new NumericTargetingDimension();
    mobileAppCategoryTargeting.setIncludedIds(
        parsedArgs.<Long>getList("included_mobile_app_targeting_category_ids"));
    mobileAppCategoryTargeting.setExcludedIds(
        parsedArgs.<Long>getList("excluded_mobile_app_targeting_category_ids"));

    AppTargeting appTargeting = new AppTargeting();
    appTargeting.setMobileAppTargeting(mobileAppTargeting);
    appTargeting.setMobileAppCategoryTargeting(mobileAppCategoryTargeting);

    StringTargetingDimension publisherTargeting = new StringTargetingDimension();
    publisherTargeting.setTargetingMode(parsedArgs.getString("publisher_targeting_mode"));
    publisherTargeting.setValues(parsedArgs.<String>getList("publisher_ids"));

    PretargetingConfig newPretargetingConfig = new PretargetingConfig();
    newPretargetingConfig.setDisplayName(parsedArgs.getString("display_name"));
    newPretargetingConfig.setIncludedFormats(parsedArgs.<String>getList("included_formats"));
    newPretargetingConfig.setGeoTargeting(geoTargeting);
    newPretargetingConfig.setUserListTargeting(userListTargeting);
    newPretargetingConfig.setInterstitialTargeting(parsedArgs.getString("interstitial_targeting"));
    newPretargetingConfig.setAllowedUserTargetingModes(
        parsedArgs.<String>getList("allowed_user_targeting_modes"));
    newPretargetingConfig.setExcludedContentLabelIds(
        parsedArgs.<Long>getList("excluded_content_label_ids"));
    newPretargetingConfig.setIncludedUserIdTypes(
        parsedArgs.<String>getList("included_user_id_types"));
    newPretargetingConfig.setIncludedLanguages(parsedArgs.<String>getList("included_languages"));
    newPretargetingConfig.setIncludedMobileOperatingSystemIds(
        parsedArgs.<Long>getList("included_mobile_os_ids"));
    newPretargetingConfig.setVerticalTargeting(verticalTargeting);
    newPretargetingConfig.setIncludedPlatforms(parsedArgs.<String>getList("included_platforms"));
    newPretargetingConfig.setIncludedCreativeDimensions(Collections.singletonList(dimensions));
    newPretargetingConfig.setIncludedEnvironments(
        parsedArgs.<String>getList("included_environments"));
    newPretargetingConfig.setWebTargeting(webTargeting);
    newPretargetingConfig.setAppTargeting(appTargeting);
    newPretargetingConfig.setPublisherTargeting(publisherTargeting);
    newPretargetingConfig.setMinimumViewabilityDecile(
        parsedArgs.getInt("minimum_viewability_decile"));

    PretargetingConfig pretargetingConfig =
        client
            .bidders()
            .pretargetingConfigs()
            .create(parentBidderName, newPretargetingConfig)
            .execute();

    System.out.printf(
        "Created pretargeting configuration for bidder Account ID '%s':\n", accountId);
    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("CreatePretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Creates a pretargeting configuration for the given bidder account ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration is to be created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-d", "--display_name")
        .help(
            "The display name to associate with the new configuration. Must be unique among "
                + "all of a bidder's pretargeting configurations.")
        .setDefault(String.format("TEST_PRETARGETING_CONFIG_%s", UUID.randomUUID()));
    parser
        .addArgument("--included_formats")
        .help(
            "Creative formats included by this configuration. Specify each ID separated by a space."
                + " An unset value will not filter any bid requests based on the format. Valid"
                + " values include: HTML, NATIVE, and VAST.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--included_geo_ids")
        .help(
            "The geo IDs to include in targeting for this configuration. Specify each ID "
                + "separated by a space. Valid geo IDs can be found in:"
                + "https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--excluded_geo_ids")
        .help(
            "The geo IDs to exclude in targeting for this configuration. Specify each ID "
                + "separated by a space. Valid geo IDs can be found in:"
                + "https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--included_user_list_ids")
        .help(
            "The user list IDs to include in targeting for this configuration. Specify each ID"
                + " separated by a space. Valid user list IDs would include any found under the"
                + " buyers.userLists resource for a given bidder account, or any buyer accounts"
                + " under it.")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--excluded_user_list_ids")
        .help(
            "The user list IDs to exclude in targeting for this configuration. Specify each ID"
                + " separated by a space. Valid user list IDs would include any found under the"
                + " buyers.userLists resource for a given bidder account, or any buyer accounts"
                + " under it.")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--interstitial_targeting")
        .help(
            "The interstitial targeting specified for this configuration. By default, this "
                + "will be set to ONLY_NON_INTERSTITIAL_REQUESTS. Valid values include: "
                + "ONLY_INTERSTITIAL_REQUESTS and ONLY_NON_INTERSTITIAL_REQUESTS.")
        .setDefault("ONLY_NON_INTERSTITIAL_REQUESTS");
    parser
        .addArgument("--allowed_user_targeting_modes")
        .help(
            "The targeting modes to include in targeting for this configuration. Specify each "
                + "value separated by a space. Valid targeting modes include: REMARKETING_ADS and "
                + "INTEREST_BASED_TARGETING.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--excluded_content_label_ids")
        .help(
            "The sensitive content category IDs excluded in targeting for this configuration."
                + " Specify each value separated by a space. Valid sensitive content category IDs"
                + " can be found in:"
                + " https://storage.googleapis.com/adx-rtb-dictionaries/content-labels.txt")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--included_user_id_types")
        .help(
            "The user identifier types included in targeting for this configuration. Specify "
                + "each value separated by a space. Valid values include: HOSTED_MATCH_DATA, "
                + "GOOGLE_COOKIE, and DEVICE_ID.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--included_language_codes")
        .help(
            "The languages represented by languages codes that are included in targeting for this"
                + " configuration. Specify each code separated by a space. Valid language codes can"
                + " be found in: "
                + "https://developers.google.com/adwords/api/docs/appendix/languagecodes.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--included_mobile_os_ids")
        .help(
            "The mobile OS IDs to include in targeting for this configuration. Specify each "
                + "value separated by a space. Valid mobile OS IDs can be found in: "
                + "https://storage.googleapis.com/adx-rtb-dictionaries/mobile-os.csv")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--included_vertical_ids")
        .help(
            "The vertical IDs to include in targeting for this configuration. Specify each ID"
                + " separated by a space. Valid vertical IDs can be found in: "
                + "https://developers.google.com/authorized-buyers/rtb/downloads/publisher-verticals")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--excluded_vertical_ids")
        .help(
            "The vertical IDs to exclude in targeting for this configuration. Specify each ID"
                + " separated by a space. Valid vertical IDs can be found in: "
                + "https://developers.google.com/authorized-buyers/rtb/downloads/publisher-verticals")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--included_platforms")
        .help(
            "The platforms to include in targeting for this configuration. Specify each value"
                + " separated by a space. Valid values include: PERSONAL_COMPUTER, PHONE, TABLET,"
                + " and CONNECTED_TV.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--included_creative_dimension_height")
        .help(
            "A creative dimension's height to be included in targeting for this configuration. By"
                + " default, this example will set the targeted height to 300. Note that while only"
                + " a single set of dimensions are specified in this sample, pretargeting"
                + " configurations can target multiple creative dimensions.")
        .type(Long.class)
        .setDefault(300L);
    parser
        .addArgument("--included_creative_dimension_width")
        .help(
            "A creative dimension's width to be included in targeting for this configuration. By"
                + " default, this example will set the targeted width to 250. Note that while only"
                + " a single set of dimensions are specified in this sample, pretargeting"
                + " configurations can target multiple creative dimensions.")
        .type(Long.class)
        .setDefault(250L);
    parser
        .addArgument("--included_environments")
        .help(
            "The environments to include in targeting for this configuration. Specify each "
                + "value separated by a space. Valid values include: APP, and WEB.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--web_targeting_mode")
        .help(
            "The targeting mode for this configuration's web targeting. Valid values include: "
                + "INCLUSIVE, and EXCLUSIVE.")
        .type(String.class);
    parser
        .addArgument("--web_targeting_urls")
        .help(
            "The URLs specified for this configuration's web targeting, which allows one to target"
                + " a subset of site inventory. Specify each value separated by a space. Values"
                + " specified must be valid URLs.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--mobile_app_targeting_mode")
        .help(
            "The targeting mode for the configuration's mobile app targeting. Valid values "
                + "include: INCLUSIVE, and EXCLUSIVE.")
        .type(String.class);
    parser
        .addArgument("--mobile_app_targeting_app_ids")
        .help(
            "The mobile app IDs specified for this configuration's mobile app targeting, which"
                + " allows one to target a subset of mobile app inventory. Specify each value"
                + " separated by a space. Values specified must be valid mobile App IDs, as found"
                + " on their respective app stores.")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--included_mobile_app_targeting_category_ids")
        .help(
            "The mobile app category IDs to include in targeting for this configuration. "
                + "Specify each ID separated by a space. Valid category IDs can be found in: "
                + "https://developers.google.com/adwords/api/docs/appendix/mobileappcategories.csv")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--excluded_mobile_app_targeting_category_ids")
        .help(
            "The mobile app category IDs to exclude in targeting for this configuration. "
                + "Specify each ID separated by a space. Valid category IDs can be found in: "
                + "https://developers.google.com/adwords/api/docs/appendix/mobileappcategories.csv")
        .type(Long.class)
        .nargs("*");
    parser
        .addArgument("--publisher_targeting_mode")
        .help(
            "The targeting mode for the configuration's publisher targeting. Valid values "
                + "include: INCLUSIVE, and EXCLUSIVE.")
        .type(String.class);
    parser
        .addArgument("--publisher_ids")
        .help(
            "The publisher IDs specified for this configuration's publisher targeting, which allows"
                + " one to target a subset of publisher inventory. Specify each ID separated by a"
                + " space. Valid publisher IDs can be found in Real-time Bidding bid requests, or"
                + " alternatively in ads.txt / app-ads.txt. For more information, see: "
                + "https://iabtechlab.com/ads-txt/")
        .type(String.class)
        .nargs("*");
    parser
        .addArgument("--minimum_viewability_decile")
        .help(
            "The targeted minimum viewability decile, ranging from 0 - 10. A value of '5' means"
                + " that the configuration will only match adslots for which we predict at least"
                + " 50% viewability. Values > 10 will be rounded down to 10. An unset value, or a"
                + " value of '0', indicates that bid requests should be sent regardless of"
                + " viewability.")
        .type(String.class)
        .setDefault(5);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_PretargetingConfig;
use Google_Service_RealTimeBidding_AppTargeting;
use Google_Service_RealTimeBidding_CreativeDimensions;
use Google_Service_RealTimeBidding_NumericTargetingDimension;
use Google_Service_RealTimeBidding_StringTargetingDimension;

/**
 * Creates a pretargeting configuration for the given bidder account ID.
 */
class CreatePretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration is to be created.',
                'required' => true
            ],
            [
                'name' => 'display_name',
                'display' => 'Display name',
                'description' =>
                    'The display name to associate with the new configuration. Must be unique ' .
                    'among all of a bidder\'s pretargeting configurations.',
                'required' => false,
                'default' => 'TEST_PRETARGETING_CONFIG_' . uniqid()
            ],
            [
                'name' => 'included_formats',
                'display' => 'Included formats',
                'description' =>
                    'Creative formats included by this configuration. Specify each value ' .
                    'separated by a comma. An unset value will not filter any bid requests ' .
                    'based on the format. Valid values include: HTML, NATIVE, and VAST.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_geo_ids',
                'display' => 'Included geo IDs',
                'description' =>
                    'The geo IDs to include in targeting for this configuration. Specify each ' .
                    'ID separated by a comma. Valid geo IDs can be found in: ' .
                    'https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'excluded_geo_ids',
                'display' => 'Excluded geo IDs',
                'description' =>
                    'The geo IDs to exclude in targeting for this configuration. Specify each ' .
                    'ID separated by a comma. Valid geo IDs can be found in: ' .
                    'https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_user_list_ids',
                'display' => 'Included user list IDs',
                'description' =>
                    'The user list IDs to include in targeting for this configuration. Specify ' .
                    'each ID separated by a comma. Valid user list IDs would include any found ' .
                    'under the buyers.userLists resource for a given bidder account, or any ' .
                    'buyer accounts under it.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'excluded_user_list_ids',
                'display' => 'Excluded user list IDs',
                'description' =>
                    'The user list IDs to exclude in targeting for this configuration. Specify ' .
                    'each ID separated by a comma. Valid user list IDs would include any found ' .
                    'under the buyers.userLists resource for a given bidder account, or any ' .
                    'buyer accounts under it.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'interstitial_targeting',
                'display' => 'Interstitial targeting',
                'description' =>
                    'The interstitial targeting specified for this configuration. By default, ' .
                    'this will be set to ONLY_NON_INTERSTITIAL_REQUESTS. Valid values include: ' .
                    'ONLY_INTERSTITIAL_REQUESTS and ONLY_NON_INTERSTITIAL_REQUESTS.',
                'required' => false,
                'default' => 'ONLY_NON_INTERSTITIAL_REQUESTS'
            ],
            [
                'name' => 'allowed_user_targeting_modes',
                'display' => 'Allowed user targeting modes',
                'description' =>
                    'The targeting modes to include in targeting for this configuration. ' .
                    'Specify each value separated by a comma. Valid targeting modes include: ' .
                    'REMARKETING_ADS and INTEREST_BASED_TARGETING.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'excluded_content_label_ids',
                'display' => 'Excluded content label IDs',
                'description' =>
                    'The sensitive content category IDs excluded in targeting for this ' .
                    'configuration. Specify each value separated by a comma. Valid sensitive ' .
                    'content category IDs can be found in: ' .
                    'https://storage.googleapis.com/adx-rtb-dictionaries/content-labels.txt',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_user_id_types',
                'display' => 'Included user ID types',
                'description' =>
                    'The user identifier types included in targeting for this configuration. ' .
                    'Specify each value separated by a comma. Valid values include: ' .
                    'HOSTED_MATCH_DATA, GOOGLE_COOKIE, and DEVICE_ID.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_language_codes',
                'display' => 'Included language codes',
                'description' =>
                    'The languages represented by languages codes that are included in ' .
                    'targeting for this configuration. Specify each code separated by a comma. ' .
                    'Valid language codes can be found in: ' .
                    'https://developers.google.com/adwords/api/docs/appendix/languagecodes.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_mobile_os_ids',
                'display' => 'Included mobile OS IDs',
                'description' =>
                    'The mobile OS IDs to include in targeting for this configuration. Specify ' .
                    'each value separated by a comma. Valid mobile OS IDs can be found in: ' .
                    'https://storage.googleapis.com/adx-rtb-dictionaries/mobile-os.csv',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_vertical_ids',
                'display' => 'Included vertical IDs',
                'description' =>
                    'The vertical IDs to include in targeting for this configuration. Specify ' .
                    'each ID separated by a comma. Valid vertical IDs can be found in: ' .
                    'https://developers.google.com/authorized-buyers/rtb/downloads/' .
                    'publisher-verticals',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'excluded_vertical_ids',
                'display' => 'Excluded vertical IDs',
                'description' =>
                    'The vertical IDs to exclude in targeting for this configuration. Specify ' .
                    'each ID separated by a comma. Valid vertical IDs can be found in: ' .
                    'https://developers.google.com/authorized-buyers/rtb/downloads/' .
                    'publisher-verticals',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_platforms',
                'display' => 'Included platforms',
                'description' =>
                    'The platforms to include in targeting for this configuration. Specify each ' .
                    'value separated by a comma. Valid values include: PERSONAL_COMPUTER, ' .
                    'PHONE, TABLET, and CONNECTED_TV.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_creative_dimension_height',
                'display' => 'Included creative dimension height',
                'description' =>
                    'A creative dimension\'s height to be included in targeting for this ' .
                    'configuration. By default, this example will set the targeted height to ' .
                    '300. Note that while only a single set of dimensions are specified in this ' .
                    'sample, pretargeting configurations can target multiple creative dimensions.',
                'required' => false,
                'default' => 300
            ],
            [
                'name' => 'included_creative_dimension_width',
                'display' => 'Included creative dimension width',
                'description' =>
                    'A creative dimension\'s width to be included in targeting for this ' .
                    'configuration. By default, this example will set the targeted height to ' .
                    '250. Note that while only a single set of dimensions are specified in this ' .
                    'sample, pretargeting configurations can target multiple creative dimensions.',
                'required' => false,
                'default' => 250
            ],
            [
                'name' => 'included_environments',
                'display' => 'Included environments',
                'description' =>
                    'The environments to include in targeting for this configuration. Specify ' .
                    'each value separated by a comma. Valid values include: APP, and WEB.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'web_targeting_mode',
                'display' => 'Web targeting mode',
                'description' =>
                    'The targeting mode for this configuration\'s web targeting. Valid values ' .
                    'include: INCLUSIVE, and EXCLUSIVE.',
                'required' => false,
                'default' => null
            ],
            [
                'name' => 'web_targeting_urls',
                'display' => 'Web targeting URLs',
                'description' =>
                    'The URLs specified for this configuration\'s web targeting, which allows ' .
                    'one to target a subset of site inventory. Specify each value separated by ' .
                    'a comma. Values specified must be valid URLs.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'mobile_app_targeting_mode',
                'display' => 'Mobile app targeting mode',
                'description' =>
                    'The targeting mode for this configuration\'s mobile app targeting. Valid ' .
                    'values include: INCLUSIVE, and EXCLUSIVE.',
                'required' => false,
                'default' => null
            ],
            [
                'name' => 'mobile_app_targeting_app_ids',
                'display' => 'Mobile app targeting app IDs',
                'description' =>
                    'The mobile app IDs specified for this configuration\'s mobile app ' .
                    'targeting, which allows one to target a subset of mobile app inventory. ' .
                    'Specify each value separated by a comma. Values specified must be valid ' .
                    'mobile App IDs, as found on their respective app stores.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'included_mobile_app_targeting_category_ids',
                'display' => 'Included mobile app targeting category IDs',
                'description' =>
                    'The mobile app category IDs to include in targeting for this ' .
                    'configuration. Specify each ID separated by a comma. Valid category IDs ' .
                    'can be found in: https://developers.google.com/adwords/api/docs/appendix/' .
                    'mobileappcategories.csv',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'excluded_mobile_app_targeting_category_ids',
                'display' => 'Excluded mobile app targeting category IDs',
                'description' =>
                    'The mobile app category IDs to exclude in targeting for this ' .
                    'configuration. Specify each ID separated by a comma. Valid category IDs ' .
                    'can be found in: https://developers.google.com/adwords/api/docs/appendix/' .
                    'mobileappcategories.csv',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'publisher_targeting_mode',
                'display' => 'Publisher targeting mode',
                'description' =>
                    'The targeting mode for this configuration\'s publisher targeting. Valid ' .
                    'values include: INCLUSIVE, and EXCLUSIVE.',
                'required' => false,
                'default' => null
            ],
            [
                'name' => 'publisher_ids',
                'display' => 'Publisher IDs',
                'description' =>
                    'The publisher IDs specified for this configuration\'s publisher targeting, ' .
                    'which allows one to target a subset of publisher inventory. Specify each ' .
                    'ID separated by a comma. Valid publisher IDs can be found in Real-time ' .
                    'Bidding bid requests, or alternatively in ads.txt / app-ads.txt. For more ' .
                    'information, see: https://iabtechlab.com/ads-txt/',
                'required' => false,
                'is_array' => true,
                'default' => []
            ],
            [
                'name' => 'minimum_viewability_decile',
                'display' => 'Minimum viewability decile',
                'description' =>
                    'The targeted minimum viewability decile, ranging from 0 - 10. A value of ' .
                    '"5" means that the configuration will only match adslots for which we ' .
                    'predict at least 50% viewability. Values > 10 will be rounded down to 10. ' .
                    'An unset value, or a value of "0", indicates that bid requests should be ' .
                    'sent regardless of viewability.',
                'required' => false,
                'default' => null
            ],
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $parentName = "bidders/$values[account_id]";

        $geoTargeting = new Google_Service_RealTimeBidding_NumericTargetingDimension();
        $geoTargeting->includedIds = $values['included_geo_ids'];
        $geoTargeting->excludedIds = $values['excluded_geo_ids'];

        $userListTargeting = new Google_Service_RealTimeBidding_NumericTargetingDimension();
        $userListTargeting->includedIds = $values['included_user_list_ids'];
        $userListTargeting->excludedIds = $values['excluded_user_list_ids'];

        $verticalTargeting = new Google_Service_RealTimeBidding_NumericTargetingDimension();
        $verticalTargeting->includedIds = $values['included_vertical_ids'];
        $verticalTargeting->excludedIds = $values['excluded_vertical_ids'];

        $includedCreativeDimensions = new Google_Service_RealTimeBidding_CreativeDimensions();
        $includedCreativeDimensions->height = $values['included_creative_dimension_height'];
        $includedCreativeDimensions->width = $values['included_creative_dimension_width'];

        $webTargeting = new Google_Service_RealTimeBidding_StringTargetingDimension();
        $webTargeting->targetingMode = $values['web_targeting_mode'];
        $webTargeting->values = $values['web_targeting_urls'];

        $mobileAppTargeting = new Google_Service_RealTimeBidding_StringTargetingDimension();
        $mobileAppTargeting->targetingMode = $values['mobile_app_targeting_mode'];
        $mobileAppTargeting->values = $values['mobile_app_targeting_app_ids'];

        $mobileAppCategoryTargeting = new Google_Service_RealTimeBidding_NumericTargetingDimension();
        $mobileAppCategoryTargeting->includedIds = $values['included_mobile_app_targeting_category_ids'];
        $mobileAppCategoryTargeting->excludedIds = $values['excluded_mobile_app_targeting_category_ids'];

        $appTargeting = new Google_Service_RealTimeBidding_AppTargeting();
        $appTargeting->mobileAppTargeting = $mobileAppTargeting;
        $appTargeting->mobileAppCategoryTargeting = $mobileAppCategoryTargeting;

        $publisherTargeting = new Google_Service_RealTimeBidding_StringTargetingDimension();
        $publisherTargeting->targetingMode = $values['publisher_targeting_mode'];
        $publisherTargeting->values = $values['publisher_ids'];

        $newPretargetingConfig = new Google_Service_RealTimeBidding_PretargetingConfig();
        $newPretargetingConfig->displayName = $values['display_name'];
        $newPretargetingConfig->includedFormats = $values['included_formats'];
        $newPretargetingConfig->geoTargeting = $geoTargeting;
        $newPretargetingConfig->userListTargeting = $userListTargeting;
        $newPretargetingConfig->interstitialTargeting = $values['interstitial_targeting'];
        $newPretargetingConfig->allowedUserTargetingModes = $values['allowed_user_targeting_modes'];
        $newPretargetingConfig->excludedContentLabelIds = $values['excluded_content_label_ids'];
        $newPretargetingConfig->includedUserIdTypes = $values['included_user_id_types'];
        $newPretargetingConfig->includedLanguages = $values['included_languages'];
        $newPretargetingConfig->includedMobileOperatingSystemIds = $values['included_mobile_os_ids'];
        $newPretargetingConfig->verticalTargeting = $verticalTargeting;
        $newPretargetingConfig->includedPlatforms = $values['included_platforms'];
        $newPretargetingConfig->includedCreativeDimensions = [$includedCreativeDimensions];
        $newPretargetingConfig->includedEnvironments = $values['included_environments'];
        $newPretargetingConfig->webTargeting = $webTargeting;
        $newPretargetingConfig->appTargeting = $appTargeting;
        $newPretargetingConfig->publisherTargeting = $publisherTargeting;
        $newPretargetingConfig->minimumViewabilityDecile = $values['minimum_viewability_decile'];

        print "<h2>Creating pretargeting configuration for '$parentName':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->create($parentName, $newPretargetingConfig);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Create Pretargeting Configuration';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 creates a pretargeting config for the given bidder account ID.
"""


import argparse
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  body = {
      'displayName': args.display_name,
      'includedFormats': args.included_formats,
      'geoTargeting': {
          'includedIds': args.included_geo_ids,
          'excludedIds': args.excluded_geo_ids
      },
      'userListTargeting': {
          'includedIds': args.included_user_list_ids,
          'excludedIds': args.excluded_user_list_ids
      },
      'interstitialTargeting': args.interstitial_targeting,
      'allowedUserTargetingModes': args.allowed_user_targeting_modes,
      'excludedContentLabelIds': args.excluded_content_label_ids,
      'includedUserIdTypes': args.included_user_id_types,
      'includedLanguages': args.included_language_codes,
      'includedMobileOperatingSystemIds': args.included_mobile_os_ids,
      'verticalTargeting': {
          'includedIds': args.included_vertical_ids,
          'excludedIds': args.excluded_vertical_ids
      },
      'includedPlatforms': args.included_platforms,
      'includedCreativeDimensions': [{
          'height': args.included_creative_dimension_height,
          'width': args.included_creative_dimension_width
      }],
      'includedEnvironments': args.included_environments,
      'webTargeting': {
          'targetingMode': args.web_targeting_mode,
          'values': args.web_targeting_urls
      },
      'appTargeting': {
          'mobileAppTargeting': {
              'targetingMode': args.mobile_app_targeting_mode,
              'values': args.mobile_app_targeting_app_ids
          },
          'mobileAppCategoryTargeting': {
              'includedIds': args.included_mobile_app_targeting_category_ids,
              'excludedIds': args.excluded_mobile_app_targeting_category_ids
          }
      },
      'publisherTargeting': {
          'targetingMode': args.publisher_targeting_mode,
          'values': args.publisher_ids
      },
      'minimumViewabilityDecile': args.minimum_viewability_decile
  }

  print('Creating a pretargeting configuration for account ID: '
        f'"{account_id}".')
  try:
    response = realtimebidding.bidders().pretargetingConfigs().create(
        parent=_BIDDER_NAME_TEMPLATE % account_id, body=body).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Creates a pretargeting configuration for the given bidder '
                   'account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration is to be created.'))
  # Optional fields.
  parser.add_argument(
      '-d', '--display_name',
      default=f'TEST_PRETARGETING_CONFIG_{uuid.uuid4()}',
      help=('The display name to associate with the new configuration. Must '
            'be unique among all of a bidder\'s pretargeting configurations.'))
  parser.add_argument(
      '--included_formats', nargs='*', default=[],
      help=('Creative formats included by this configuration. An unset value '
            'will not filter any bid requests based on the format. Valid '
            'values include: HTML, NATIVE, and VAST.'))
  parser.add_argument(
      '--included_geo_ids', nargs='*', default=[],
      help=('The geo IDs to include in targeting for this configuration. '
            'Specify each ID separated by a space. Valid geo IDs can be found '
            'in: https://storage.googleapis.com/adx-rtb-dictionaries/'
            'geo-table.csv'))
  parser.add_argument(
      '--excluded_geo_ids', nargs='*', default=[],
      help=('The geo IDs to exclude in targeting for this configuration. '
            'Specify each ID separated by a space. Valid geo IDs can be found '
            'in: https://storage.googleapis.com/adx-rtb-dictionaries/'
            'geo-table.csv'))
  parser.add_argument(
      '--included_user_list_ids', nargs='*', default=[],
      help=('The user list IDs to include in targeting for this '
            'configuration. Specify each ID separated by a space. Valid user '
            'list IDs would include any found under the buyers.userLists '
            'resource for a given bidder account, or any buyer accounts under '
            'it.'))
  parser.add_argument(
      '--excluded_user_list_ids', nargs='*', default=[],
      help=('The user list IDs to exclude in targeting for this '
            'configuration. Specify each ID separated by a space. Valid user '
            'list IDs would include any found under the buyers.userLists '
            'resource for a given bidder account, or any buyer accounts under '
            'it.'))
  parser.add_argument(
      '--interstitial_targeting', default='ONLY_NON_INTERSTITIAL_REQUESTS',
      help=('The interstitial targeting specified for this configuration. By '
            'default, this will be set to ONLY_NON_INTERSTITIAL_REQUESTS. '
            'Valid values include: ONLY_INTERSTITIAL_REQUESTS and '
            'ONLY_NON_INTERSTITIAL_REQUESTS.'))
  parser.add_argument(
      '--allowed_user_targeting_modes', nargs='*', default=[],
      help=('The targeting modes to include in targeting for this '
            'configuration. Specify each value separated by a space. Valid '
            'targeting modes include: REMARKETING_ADS and '
            'INTEREST_BASED_TARGETING.'))
  parser.add_argument(
      '--excluded_content_label_ids', nargs='*', default=[],
      help=('The sensitive content category IDs excluded in targeting for '
            'this configuration. Valid sensitive content category IDs can be '
            'found in: https://storage.googleapis.com/adx-rtb-dictionaries/'
            'content-labels.txt'))
  parser.add_argument(
      '--included_user_id_types', nargs='*', default=[],
      help=('The user identifier types included in targeting for this '
            'configuration. Specify each value separated by a space. Valid '
            'values include: HOSTED_MATCH_DATA, GOOGLE_COOKIE, and DEVICE_ID.'
           ))
  parser.add_argument(
      '--included_language_codes', nargs='*', default=[],
      help=('The languages represented by languages codes that are included '
            'in targeting for this configuration. Specify each code separated '
            'by a space. Valid language codes can be found in: '
            'https://developers.google.com/adwords/api/docs/appendix/'
            'languagecodes.'))
  parser.add_argument(
      '--included_mobile_os_ids', nargs='*', default=[],
      help=('The mobile OS IDs to include in targeting for this '
            'configuration. Specify each value separated by a space. Valid '
            'mobile OS IDs can be found in: '
            'https://storage.googleapis.com/adx-rtb-dictionaries/mobile-os.csv'
           ))
  parser.add_argument(
      '--included_vertical_ids', nargs='*', default=[],
      help=('The vertical IDs to include in targeting for this configuration. '
            'Specify each ID separated by a space. Valid vertical IDs can be '
            'found in: '
            'https://developers.google.com/authorized-buyers/rtb/downloads/'
            'publisher-verticals'))
  parser.add_argument(
      '--excluded_vertical_ids', nargs='*', default=[],
      help=('The vertical IDs to exclude in targeting for this configuration. '
            'Specify each ID separated by a space. Valid vertical IDs can be '
            'found in: '
            'https://developers.google.com/authorized-buyers/rtb/downloads/'
            'publisher-verticals'))
  parser.add_argument(
      '--included_platforms', nargs='*', default=[],
      help=('The platforms to include in targeting for this configuration. '
            'Specify each value separated by a space. Valid values include: '
            'PERSONAL_COMPUTER, PHONE, TABLET, and CONNECTED_TV.'))
  parser.add_argument(
      '--included_creative_dimension_height', default=300,
      help=('A creative dimension\s height to be included in targeting for '
            'this configuration. By default, this example will set the '
            'targeted height to 300. Note that while only a single set of '
            'dimensions are specified in this sample, pretargeting '
            'configurations can target multiple creative dimensions.'))
  parser.add_argument(
      '--included_creative_dimension_width', default=250,
      help=('A creative dimension\s width to be included in targeting for '
            'this configuration. By default, this example will set the '
            'targeted height to 250. Note that while only a single set of '
            'dimensions are specified in this sample, pretargeting '
            'configurations can target multiple creative dimensions.'))
  parser.add_argument(
      '--included_environments', nargs='*', default=[],
      help=('The environments to include in targeting for this configuration. '
            'Specify each value separated by a space. Valid values include: '
            'APP, and WEB.'))
  parser.add_argument(
      '--web_targeting_mode', default=None,
      help=('The targeting mode for this configuration\'s web targeting. '
            'Valid values include: INCLUSIVE, and EXCLUSIVE.'))
  parser.add_argument(
      '--web_targeting_urls', nargs='*', default=[],
      help=('The URLs specified for this configuration\'s web targeting, '
            'which allows one to target a subset of site inventory. Specify '
            'each value separated by a space. Values specified must be valid '
            'URLs.'))
  parser.add_argument(
      '--mobile_app_targeting_mode', default=None,
      help=('The targeting mode for the configuration\'s mobile app '
            'targeting. Valid values include: INCLUSIVE, and EXCLUSIVE.'))
  parser.add_argument(
      '--mobile_app_targeting_app_ids', nargs='*', default=[],
      help=('The mobile app IDs specified for this configuration\'s mobile '
            'app targeting, which allows one to target a subset of mobile app '
            'inventory. Specify each value separated by a space. Values '
            'specified must be valid mobile App IDs, as found on their '
            'respective app stores.'))
  parser.add_argument(
      '--included_mobile_app_targeting_category_ids', nargs='*', default=[],
      help=('The mobile app category IDs to include in targeting for this '
            'configuration. Specify each ID separated by a space. Valid '
            'category IDs can be found in:'
            'https://developers.google.com/adwords/api/docs/appendix/'
            'mobileappcategories.csv'))
  parser.add_argument(
      '--excluded_mobile_app_targeting_category_ids', nargs='*', default=[],
      help=('The mobile app category IDs to exclude in targeting for this '
            'configuration. Specify each ID separated by a space. Valid '
            'category IDs can be found in:'
            'https://developers.google.com/adwords/api/docs/appendix/'
            'mobileappcategories.csv'))
  parser.add_argument(
      '--publisher_targeting_mode', default=None,
      help=('The targeting mode for the configuration\'s publisher targeting. '
            'Valid values include: INCLUSIVE, and EXCLUSIVE.'))
  parser.add_argument(
      '--publisher_ids', nargs='*', default=[],
      help=('The publisher IDs specified for this configuration\'s publisher '
            'targeting, which allows one to target a subset of publisher '
            'inventory. Specify each ID separated by a space. Valid publisher '
            'IDs can be found in Real-time Bidding bid requests, or '
            'alternatively in ads.txt / app-ads.txt. For more information, '
            'see: https://iabtechlab.com/ads-txt/'))
  parser.add_argument(
      '-m', '--minimum_viewability_decile', default=5,
      help=('The display name to associate with the new configuration. Must '
            'be unique among all of a bidder\'s pretargeting configurations.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Creates a pretargeting configuration for the given bidder account ID.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def create_pretargeting_configs(realtimebidding, options)
  parent = "bidders/#{options[:account_id]}"

  body = Google::Apis::RealtimebiddingV1::PretargetingConfig.new(
    display_name: options[:display_name],
    included_formats: options[:included_formats],
    geo_targeting: Google::Apis::RealtimebiddingV1::NumericTargetingDimension.new(
      included_ids: options[:included_geo_ids],
      excluded_ids: options[:excluded_geo_ids]
    ),
    user_list_targeting: Google::Apis::RealtimebiddingV1::NumericTargetingDimension.new(
      included_ids: options[:included_user_list_ids],
      excluded_ids: options[:excluded_user_list_ids]
    ),
    interstitial_targeting: options[:interstitial_targeting],
    allowed_user_targeting_modes: options[:allowed_user_targeting_modes],
    excluded_content_label_ids: options[:excluded_content_label_ids],
    included_user_id_types: options[:included_user_id_types],
    included_languages: options[:included_language_codes],
    included_mobile_operating_system_ids: options[:included_mobile_os_ids],
    vertical_targeting: Google::Apis::RealtimebiddingV1::NumericTargetingDimension.new(
      included_ids: options[:included_vertical_ids],
      excluded_ids: options[:excluded_vertical_ids]
    ),
    included_platforms: options[:included_platforms],
    included_creative_dimensions: [Google::Apis::RealtimebiddingV1::CreativeDimensions.new(
      height: options[:included_creative_dimension_height],
      width: options[:included_creative_dimension_width]
    )],
    included_environments: options[:included_environments],
    web_targeting: Google::Apis::RealtimebiddingV1::StringTargetingDimension.new(
      targeting_mode: options[:web_targeting_mode],
      values: options[:web_targeting_urls]
    ),
    app_targeting: Google::Apis::RealtimebiddingV1::AppTargeting.new(
      mobile_app_targeting: Google::Apis::RealtimebiddingV1::StringTargetingDimension.new(
        targeting_mode: options[:mobile_app_targeting_mode],
        values: options[:mobile_app_targeting_app_ids]
      ),
      mobile_app_category_targeting: Google::Apis::RealtimebiddingV1::NumericTargetingDimension.new(
        included_ids: options[:included_mobile_app_targeting_category_ids],
        excluded_ids: options[:excluded_mobile_app_targeting_category_ids]
      )
    ),
    publisher_targeting: Google::Apis::RealtimebiddingV1::StringTargetingDimension.new(
      targeting_mode: options[:publisher_targeting_mode],
      values: options[:publisher_ids]
    ),
    minimum_viewability_decile: options[:minimum_viewability_decile]
  )

  puts "Creating a pretargeting configuration for bidder account '#{parent}'"

  pretargeting_config = realtimebidding.create_bidder_pretargeting_config(parent, body)
  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configuration is to be created, This '\
      'will be used to construct the name used as a path parameter for the pretargetingConfig.create request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'display_name',
      'The display name to associate with the new configuration. Must be unique among all of a bidder\'s '\
      'pretargeting configurations.',
      short_alias: 'd', required: false, default_value: "TEST_PRETARGETING_CONFIG_#{SecureRandom.uuid}"
    ),
    Option.new(
      'included_formats',
      'Creative formats included by this configuration. Specify each ID separated by a comma. An unset value will '\
      'not filter any bid requests based on the format. Valid values include: HTML, NATIVE, and VAST.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_geo_ids',
      'The geo IDs to include in targeting for this configuration. Specify each ID separated by a comma. Valid geo '\
      'IDs can be found in: https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'excluded_geo_ids',
      'The geo IDs to exclude in targeting for this configuration. Specify each ID separated by a comma. Valid geo '\
      'IDs can be found in: https://storage.googleapis.com/adx-rtb-dictionaries/geo-table.csv',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_user_list_ids',
      'The user list IDs to include in targeting for this configuration. Specify each ID separated by a comma. '\
      'Valid user list IDs would include any found under the buyers.userLists resource for a given bidder account, '\
      'or any buyer accounts under it.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'excluded_user_list_ids',
      'The user list IDs to exclude in targeting for this configuration. Specify each ID separated by a comma. '\
      'Valid user list IDs would include any found under the buyers.userLists resource for a given bidder account, '\
      'or any buyer accounts under it.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'interstitial_targeting',
      'The interstitial targeting specified for this configuration. By default, this will be set to '\
      'ONLY_NON_INTERSTITIAL_REQUESTS. Valid values include: ONLY_INTERSTITIAL_REQUESTS and '\
      'ONLY_NON_INTERSTITIAL_REQUESTS.',
      required: false, default_value: 'ONLY_NON_INTERSTITIAL_REQUESTS'
    ),
    Option.new(
      'allowed_user_targeting_modes',
      'The targeting modes to include in targeting for this configuration. Specify each value separated by a comma. '\
      'Valid targeting modes include: REMARKETING_ADS and INTEREST_BASED_TARGETING.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'excluded_content_label_ids',
      'The sensitive content category IDs excluded in targeting for this configuration. Specify each value separated '\
      'by a comma. Valid sensitive content category IDs can be found in: '\
      'https://storage.googleapis.com/adx-rtb-dictionaries/content-labels.txt',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_user_id_types',
      'The user identifier types included in targeting for this configuration. Specify each value separated by a ' \
      'comma. Valid values include: HOSTED_MATCH_DATA, GOOGLE_COOKIE, and DEVICE_ID.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_language_codes',
      'The languages represented by languages codes that are included in targeting for this configuration. Specify '\
      'each code separated by a comma. Valid language codes can be found in: '\
      'https://developers.google.com/adwords/api/docs/appendix/languagecodes.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_mobile_os_ids',
      'The mobile OS IDs to include in targeting for this configuration. Specify each value separated by a comma. '\
      'Valid mobile OS IDs can be found in: https://storage.googleapis.com/adx-rtb-dictionaries/mobile-os.csv',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_vertical_ids',
      'The vertical IDs to include in targeting for this configuration. Specify each ID separated by a comma. Valid '\
      'vertical IDs can be found in: https://developers.google.com/authorized-buyers/rtb/downloads/'\
      'publisher-verticals',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'excluded_vertical_ids',
      'The vertical IDs to exclude in targeting for this configuration. Specify each ID separated by a comma. Valid '\
      'vertical IDs can be found in: https://developers.google.com/authorized-buyers/rtb/downloads/'\
      'publisher-verticals',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_platforms',
      'The platforms to include in targeting for this configuration. Specify each value separated by a comma. Valid '\
      'values include: PERSONAL_COMPUTER, PHONE, TABLET, and CONNECTED_TV.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_creative_dimension_height',
      'A creative dimension\s height to be included in targeting for this configuration. By default, this example '\
      'will set the targeted height to 300. Note that while only a single set of dimensions are specified in this '\
      'sample, pretargeting configurations can target multiple creative dimensions.',
      required: false, default_value: 300
    ),
    Option.new(
      'included_creative_dimension_width',
      'A creative dimension\s width to be included in targeting for this configuration. By default, this example '\
      'will set the targeted width to 250. Note that while only a single set of dimensions are specified in this '\
      'sample, pretargeting configurations can target multiple creative dimensions.',
      required: false, default_value: 250
    ),
    Option.new(
      'included_environments',
      'The environments to include in targeting for this configuration. Specify each value separated by a comma. '\
      'Valid values include: APP, and WEB.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'web_targeting_mode',
      'The targeting mode for this configuration\'s web targeting. Valid values include: INCLUSIVE, and EXCLUSIVE.',
      required: false, default_value: nil
    ),
    Option.new(
      'web_targeting_urls',
      'The URLs specified for this configuration\'s web targeting, which allows one to target a subset of site '\
      'inventory. Specify each value separated by a comma. Values specified must be valid URLs.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'mobile_app_targeting_mode',
      'The targeting mode for the configuration\'s mobile app targeting. Valid values include: INCLUSIVE, and '\
      'EXCLUSIVE.',
      required: false, default_value: nil
    ),
    Option.new(
      'mobile_app_targeting_app_ids',
      'The mobile app IDs specified for this configuration\'s mobile app targeting, which allows one to target a '\
      'subset of mobile app inventory. Specify each value separated by a comma. Values specified must be valid '\
      'mobile App IDs, as found on their respective app stores.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'included_mobile_app_targeting_category_ids',
      'The mobile app category IDs to include in targeting for this configuration. Specify each ID separated by a '\
      'comma. Valid category IDs can be found in: '\
      'https://developers.google.com/adwords/api/docs/appendix/mobileappcategories.csv',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'excluded_mobile_app_targeting_category_ids',
      'The mobile app category IDs to exclude in targeting for this configuration. Specify each ID separated by a '\
      'comma. Valid category IDs can be found in: '\
      'https://developers.google.com/adwords/api/docs/appendix/mobileappcategories.csv',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'publisher_targeting_mode',
      'The targeting mode for the configuration\'s publisher targeting. Valid values include: INCLUSIVE, and '\
      'EXCLUSIVE.',
      required: false, default_value: nil
    ),
    Option.new(
      'publisher_ids',
      'The publisher IDs specified for this configuration\'s publisher targeting, which allows one to target a '\
      'subset of publisher inventory. Specify each ID separated by a comma. Valid publisher IDs can be found in '\
      'Real-time Bidding bid requests, or alternatively in ads.txt / app-ads.txt. For more information, see: '\
      'https://iabtechlab.com/ads-txt/',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'minimum_viewability_decile',
      'The targeted minimum viewability decile, ranging from 0 - 10. A value of "5" means that the configuration '\
      'will only match adslots for which we predict at least 50% viewability. Values > 10 will be rounded down to '\
      '10. An unset value, or a value of "0", indicates that bid requests should be sent regardless of viewability.',
      required: false, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    create_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

检索单个配置

下面介绍了如何获取单个预定位配置 具有 bidders.pretargetingConfigs.get:

REST

请求

GET https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_bea55522-1373-4cfe-baf3-bac5e594c76e",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "250",
      "height": "300"
    }
  ],
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Gets a single pretargeting configuration with a specified name.
    /// /<summary
>    public class GetPretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public GetPretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example gets a specified pretargeting configuration;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id," p"retargeting_config_id}";
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;

            OptionSet options = new OptionSet {
                G"ets a specified pretargeting configuration.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration that is  "+
                     b"eing retrieved.)",
                    (long p) = >pretargetingConfigId = p
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string name = $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"

            BiddersResource.PretargetingConfigsResource.GetRequest request =
                rtbService.Bidders.PretargetingConfigs.Get(name);

            PretargetingConfig response = null;

            Console.WriteLine(R"etrieving pretargeting configuration with name: {'0},'" name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** Gets a single pretargeting configuration with a specified name. */
public class GetPretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    String name =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            parsedArgs.getLong("account_id"), parsedArgs.getLong("pretargeting_config_id"));

    System.out.printf("Retrieving pretargeting configuration with name: %s\n", name);

    PretargetingConfig pretargetingConfig =
        client.bidders().pretargetingConfigs().get(name).execute();

    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetPretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Get a specified pretargeting configuration."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration that is being retrieved.")
        .required(true)
        .type(Long.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * Gets a single pretargeting configuration for the given bidder's account ID.
 */
class GetPretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration that is being retrieved.',
                'required' => true,
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";

        print "<h2>Retrieving pretargeting configuration with name '$name':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->get($name);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Get Pretargeting Configuration';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Gets a single pretargeting configuration for the given bidder's account ID.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, pretargeting_config_id):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      account_id, pretargeting_config_id)

  print('Retrieving a pretargeting configuration with name: '
        f'"{pretargeting_config_name}".')
  try:
    response = realtimebidding.bidders().pretargetingConfigs().get(
        name=pretargeting_config_name).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print('Unable to create realtimebidding service - %s' % ex)
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Get a pretargeting configuration for a given bidder '
                   'account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, required=True,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration was created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help=('The resource ID of the pretargeting configuration that is being '
            'retrieved.'))

  args = parser.parse_args()

  main(service, args.account_id, args.pretargeting_config_id)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Gets a pretargeting configuration for the given bidder account and pretargeting configuration IDs.

require 'optparse'

require_relative '../../../util'


def get_pretargeting_configs(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  puts "Get pretargeting configuration with name '#{name}'"

  pretargeting_config = realtimebidding.get_bidder_pretargeting_config(name)
  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which pretargeting configurations were created. This will be '\
      'used to construct the name used as a path parameter for the pretargetingConfigs.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id',
      'The resource ID of the bidders.pretargetingConfig resource for which the pretargeting configuration was '\
      'created. This will be used to construct the name used as a path parameter for the pretargetingConfigs.get '\
      'request.',
      type: Integer, short_alias: 'p', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    get_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

检索预定位配置列表

下面介绍了如何检索预定位配置的列表 为您的账号配置 bidders.pretargetingConfigs.list:

REST

请求

GET https://realtimebidding.googleapis.com/v1/bidders/53728410/pretargetingConfigs?pageSize=10&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

响应

{
  "pretargetingConfigs": [
    {
      "name": "bidders/12345678/pretargetingConfigs/560983",
      "displayName": "TEST_PRETARGETING_CONFIG_bea55522-1373-4cfe-baf3-bac5e594c76e",
      "billingId": "112233445566",
      "state": "ACTIVE",
      "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
      "includedCreativeDimensions": [
        {
          "width": "250",
          "height": "300"
        }
      ],
      "minimumViewabilityDecile": 5
    },
    {
      "name": "bidders/12345678/pretargetingConfigs/565124",
      "displayName": "TEST_PRETARGETING_CONFIG_a859ac07-ab5b-438c-a98f-86054c03b3fb",
      "billingId": "116622553344",
      "state": "SUSPENDED",
      "includedFormats": [
        "HTML",
        "VAST"
      ],
      "geoTargeting": {
        "includedIds": [
          "200635",
          "1014448",
          "1022183",
          "200622",
          "1023191",
          "9061237",
          "1014221"
        ]
      },
      "includedCreativeDimensions": [
        {
          "width": "320",
          "height": "480"
        },
        {
          "width": "1920",
          "height": "1080"
        }
      ]
    }
  ]
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Lists pretargeting configurations for a given bidder account ID.
    /// /<summary
>    public class ListPretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public ListPretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example lists all pretargeting configurations for a given bidder  "+
                   a"ccount.;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id}";
            bool showHelp = false;

            string accountId = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                L"ist pretargeting configurations for the given bidder account.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configurations were created. This will be used to construct  "+
                     t"he parent used as a path parameter for the pretargetingConfigs.list  "+
                     r"equest.)",
                    a = >accountId = a
                },
                {
                    p"|page_size=,"
                    (T"he number of rows to return per page. The server may return fewer rows  "+
                     t"han specified.)",
                    (int p) = >pageSize =  p
                }
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"ageSize]" = pageSize ?? Utilities.MAX_PAGE_SIZE;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            string parent = $b"idders/{accountId};"
            string pageToken = null;

            Console.WriteLine(@L"isting pretargeting configurations for bidder account {""0},"""
                              parent);
            do
            {
                BiddersResource.PretargetingConfigsResource.ListRequest request =
                   rtbService.Bidders.PretargetingConfigs.List(parent);
                request.PageSize = (int) parsedArgs[p"ageSize]";
                request.PageToken = pageToken;

                ListPretargetingConfigsResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    throw new ApplicationException(
                        $R"eal-time Bidding API returned error response:\n{exception.Message})";
                }

                var pretargetingConfigs = page.PretargetingConfigs;
                pageToken = page.NextPageToken;

                if(pretargetingConfigs == null)
                {
                    Console.WriteLine(N"o pretargeting configurations found for bidder account.)";
                }
                else
                {
                    foreach (PretargetingConfig config in pretargetingConfigs)
                        {
                            Utilities.PrintPretargetingConfiguration(config);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.ListPretargetingConfigsResponse;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to list pretargeting configurations for a given bidder account ID.
 */
public class ListPretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Long accountId = parsedArgs.getLong("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBidderName = String.format("bidders/%s", accountId);
    String pageToken = null;

    System.out.printf("Found pretargeting configurations for bidder Account ID '%d':\n", accountId);

    do {
      List<PretargetingConfig> pretargetingConfigs = null;

      ListPretargetingConfigsResponse response =
          client
              .bidders()
              .pretargetingConfigs()
              .list(parentBidderName)
              .setPageSize(pageSize)
              .setPageToken(pageToken)
              .execute();

      pretargetingConfigs = response.getPretargetingConfigs();
      pageToken = response.getNextPageToken();

      if (pretargetingConfigs == null) {
        System.out.println("No pretargeting configurations found.");
      } else {
        for (PretargetingConfig pretargetingConfig : pretargetingConfigs) {
          Utils.printPretargetingConfig(pretargetingConfig);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListPretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Lists pretargeting configurations for the given bidder account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting configurations"
                + " were created. This will be used to construct the parent used as a path"
                + " parameter for the pretargetingConfigs.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--page_size")
        .help(
            "The resource ID of the buyers resource under which the user lists were created. "
                + "This will be used to construct the parent used as a path parameter for the "
                + "userLists.list request.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * Lists pretargeting configurations for a given bidder account ID.
 */
class ListPretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Bidder account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configurations were created. This will be used to construct the parent ' .
                    'used as a path parameter for the pretargetingConfig.list request.'
            ],
            [
                'name' => 'page_size',
                'display' => 'Page size',
                'required' => false,
                'description' =>
                    'The number of rows to return per page. The server may return fewer rows ' .
                    'than specified.',
                'default' => 10
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $parentName = "bidders/$values[account_id]";
        $queryParams = ['pageSize' => $values['page_size']];

        $result = $this->service->bidders_pretargetingConfigs->listBiddersPretargetingConfigs($parentName, $queryParams);

        print "<h2>Pretargeting configurations found for '$parentName':</h2>";
        if (empty($result['pretargetingConfigs'])) {
            print '<p>No pretargeting configurations found</p>';
        } else {
            foreach ($result['pretargetingConfigs'] as $pretargetingConfig) {
                $this->printResult($pretargetingConfig);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Bidder Pretargeting Configurations';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Lists pretargeting configurations for the given bidder's account ID."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  page_token = None
  more_pages = True

  print('Listing pretargeting configurations for bidder account: '
        f'"{account_id}".')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.bidders().pretargetingConfigs().list(
          parent=_BIDDER_NAME_TEMPLATE % account_id, pageToken=page_token,
          pageSize=args.page_size).execute()
    except HttpError as e:
      print(e)
      sys.exit(1)

    pprint.pprint(response)

    page_token = response.get('nextPageToken')
    more_pages = bool(page_token)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Lists pretargeting configurations for the given bidder '
                   'account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configs were created by a buyer. This will be used '
            'to construct the parent used as a path parameter for the '
            'pretargetingConfigs.list request.'))
  # Optional fields.
  parser.add_argument(
      '-p', '--page_size', default=util.MAX_PAGE_SIZE,
      help=('The number of rows to return per page. The server may return '
            'fewer rows than specified.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Lists pretargeting configurations for the given bidder's account ID.

require 'optparse'

require_relative '../../../util'


def list_pretargeting_configs(realtimebidding, options)
  parent = "bidders/#{options[:account_id]}"
  page_size = options[:page_size]

  page_token = nil

  puts "Listing pretargeting configurations for bidder account '#{parent}'"
  begin
    response = realtimebidding.list_bidder_pretargeting_configs(
        parent, page_size: page_size, page_token: page_token
    )

    page_token = response.next_page_token

    unless response.pretargeting_configs.nil?
      response.pretargeting_configs.each do |pretargeting_config|
        print_pretargeting_config(pretargeting_config)
      end
    else
      puts 'No pretargeting configurations found for buyer account'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configurations were created, This will '\
      'be used to construct the parent used as a path parameter for the pretargetingConfigs.list request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

修补现有的预定位配置

下面介绍了如何修补现有的预定位配置 具有 bidders.pretargetingConfigs.patch:

您无法使用 patch 方法修改预定位配置的 state。使用以下 bidders.pretargetingConfigs.activatebidders.pretargetingConfigs.suspend 方法。

REST

请求

PATCH https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983?updateMask=displayName%2CincludedFormats%2CgeoTargeting.includedIds%2CincludedCreativeDimensions&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "displayName": "TEST_PRETARGETING_CONFIG_1153a27b-ee53-43af-a051-88eecd309510",
  "includedFormats": [
    "HTML",
    "VAST"
  ],
  "geoTargeting": {
    "includedIds": [
      "200635",
      "1014448",
      "1022183",
      "200622",
      "1023191",
      "9061237",
      "1014221"
    ]
  },
  "includedCreativeDimensions": [
    {
      "height": 480,
      "width": 320
    },
    {
      "height": 1080,
      "width": 1920
    }
  ]
}

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_1153a27b-ee53-43af-a051-88eecd309510",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "includedFormats": [
    "HTML",
    "VAST"
  ],
  "geoTargeting": {
    "includedIds": [
      "200635",
      "1014448",
      "1022183",
      "200622",
      "1023191",
      "9061237",
      "1014221"
    ]
  },
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "320",
      "height": "480"
    },
    {
      "width": "1920",
      "height": "1080"
    }
  ],
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Patches a pretargeting configuration with a specified name.
    /// /<summary
>    public class PatchPretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public PatchPretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example patches a specified pretargeting configuration.;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id," p"retargeting_config_id}";
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;
            string displayName = null;

            OptionSet options = new OptionSet {
                P"atches a specified pretargeting configuration.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration to be  "+
                     p"atched.)",
                    (long p) = >pretargetingConfigId = p
                },
                {
                    d"isplay_name=,"
                    T"he display name to associate with the new configuration. Must be unique  "+
                    a"mong all of a bidders' pretargeting configurations.,"
                    display_name = >displayName = display_name
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            parsedArgs[d"isplay_name]" = displayName ?? String.Format(
                T"EST_PRETARGETING_CONFIG_{0},"
                System.Guid.NewGuid());
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string name = $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"

            NumericTargetingDimension geoTargeting = new NumericTargetingDimension();
            geoTargeting.IncludedIds = new Listl<ong?(>) {
                200635L,  // Austin, TX
                1014448L,  // Boulder, CO
                1022183L,  // Hoboken, NJ
                200622L,   // New Orleans, LA
                1023191L,  // New York, NY
                9061237L,  // Mountain View, CA
                1014221L   // San Francisco, CA
            };

            CreativeDimensions dimensions1 = new CreativeDimensions();
            dimensions1.Height = 480L;
            dimensions1.Width = 320L;

            CreativeDimensions dimensions2 = new CreativeDimensions();
            dimensions2.Height = 1080L;
            dimensions2.Width = 1920L;

            ListC<reativeDimensions >creativeDimensions = new ListC<reativeDimensions(>) {
                dimensions1,
                dimensions2
            };

            PretargetingConfig body = new PretargetingConfig();
            body.DisplayName = (string) parsedArgs[d"isplay_name]";
            // Note that repeated fields such as this are completely overwritten by the contents
            // included in the patch request.
            body.IncludedFormats = new Lists<tring(>) {H"TML," V"AST}";
            body.GeoTargeting = geoTargeting;
            body.IncludedCreativeDimensions = creativeDimensions;

            BiddersResource.PretargetingConfigsResource.PatchRequest request =
                rtbService.Bidders.PretargetingConfigs.Patch(body, name);
            PretargetingConfig response = null;

            Console.WriteLine(P"atching pretargeting configuration with name: {0}," name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.CreativeDimensions;
import com.google.api.services.realtimebidding.v1.model.NumericTargetingDimension;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** Patches a pretargeting configuration with a specified name. */
public class PatchPretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Long accountId = parsedArgs.getLong("account_id");

    String name =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            accountId, parsedArgs.getLong("pretargeting_config_id"));
    String updateMask =
        "displayName,includedFormats,geoTargeting.includedIds," + "includedCreativeDimensions";

    NumericTargetingDimension geoTargeting = new NumericTargetingDimension();
    geoTargeting.setIncludedIds(
        Arrays.asList(
            200635L, // Austin, TX
            1014448L, // Boulder, CO
            1022183L, // Hoboken, NJ
            200622L, // New Orleans, LA
            1023191L, // New York, NY
            9061237L, // Mountain View, CA
            1014221L // San Francisco, CA
            ));

    CreativeDimensions creativeDimensions1 = new CreativeDimensions();
    creativeDimensions1.setHeight(480L);
    creativeDimensions1.setWidth(320L);

    CreativeDimensions creativeDimensions2 = new CreativeDimensions();
    creativeDimensions2.setHeight(1080L);
    creativeDimensions2.setWidth(1920L);

    PretargetingConfig body = new PretargetingConfig();
    body.setDisplayName(parsedArgs.getString("display_name"));
    // Note that repeated fields such as this are completely overwritten by the contents included in
    // the patch request.
    body.setIncludedFormats(Arrays.asList("HTML", "VAST"));
    body.setGeoTargeting(geoTargeting);
    body.setIncludedCreativeDimensions(Arrays.asList(creativeDimensions1, creativeDimensions2));

    PretargetingConfig pretargetingConfig =
        client
            .bidders()
            .pretargetingConfigs()
            .patch(name, body)
            .setUpdateMask(updateMask)
            .execute();

    System.out.printf("Patched pretargeting configuration with name '%s':\n", name);
    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("PatchPretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Patches a specified pretargeting configuration."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration to be patched.")
        .required(true)
        .type(Integer.class);
    parser
        .addArgument("-d", "--display_name")
        .help(
            "The display name to associate with the new configuration. Must be unique among "
                + "all of a bidder's pretargeting configurations.")
        .setDefault(String.format("TEST_PRETARGETING_CONFIG_%s", UUID.randomUUID()));

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_PretargetingConfig;
use Google_Service_RealTimeBidding_AppTargeting;
use Google_Service_RealTimeBidding_CreativeDimensions;
use Google_Service_RealTimeBidding_NumericTargetingDimension;
use Google_Service_RealTimeBidding_StringTargetingDimension;

/**
 * Patches a pretargeting configuration with the specified name.
 */
class PatchPretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration to be patched.',
                'required' => true,
            ],
            [
                'name' => 'display_name',
                'display' => 'Display name',
                'description' =>
                    'The patched display name to associate with the configuration. Must be ' .
                    'unique among all of a bidder\'s pretargeting configurations.',
                'required' => false,
                'default' => 'TEST_PRETARGETING_CONFIG_' . uniqid()
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";

        $geoTargeting = new Google_Service_RealTimeBidding_NumericTargetingDimension();
        $geoTargeting->includedIds = [
            '200635',   // Austin, TX
            '1014448',  // Boulder, CO
            '1022183',  // Hoboken, NJ
            '200622',   // New Orleans, LA
            '1023191',  // New York, NY
            '9061237',  // Mountain View, CA
            '1014221'   // San Francisco, CA
        ];

        $includedCreativeDimensions1 = new Google_Service_RealTimeBidding_CreativeDimensions();
        $includedCreativeDimensions1->height = 480;
        $includedCreativeDimensions1->width = 320;

        $includedCreativeDimensions2 = new Google_Service_RealTimeBidding_CreativeDimensions();
        $includedCreativeDimensions2->height = 1080;
        $includedCreativeDimensions2->width = 1920;

        $body = new Google_Service_RealTimeBidding_PretargetingConfig();
        $body->displayName = $values['display_name'];
        $body->includedFormats = ['HTML', 'VAST'];
        $body->geoTargeting = $geoTargeting;
        $body->includedCreativeDimensions = [$includedCreativeDimensions1, $includedCreativeDimensions2];

        $queryParams = [
            'updateMask' =>
                'displayName,includedFormats,geoTargeting.includedIds,includedCreativeDimensions'
        ];

        print "<h2>Patching a pretargeting configuration with name '$name':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->patch($name, $body, $queryParams);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Patch Pretargeting Configuration';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 patches a pretargeting config with a specified name."""


import argparse
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      args.account_id, args.pretargeting_config_id)

  body = {
      'displayName': args.display_name,
      'includedFormats': ['HTML', 'VAST'],
      'geoTargeting': {
          # Note that repeated fields such as this are completely overwritten
          # by the contents included in the patch request.
          'includedIds': [
              '200635',   # Austin, TX
              '1014448',  # Boulder, CO
              '1022183',  # Hoboken, NJ
              '200622',   # New Orleans, LA
              '1023191',  # New York, NY
              '9061237',  # Mountain View, CA
              '1014221'   # San Francisco, CA
          ],
      },
      'includedCreativeDimensions': [
          {
              'height': 480,
              'width': 320
          },
          {
              'height': 1080,
              'width': 1920
          }
      ],
  }

  update_mask = ('displayName,includedFormats,geoTargeting.includedIds,'
                 'includedCreativeDimensions')

  print('Patching a pretargeting configuration with name: '
        f'"{pretargeting_config_name}".')
  try:
    response = realtimebidding.bidders().pretargetingConfigs().patch(
        name=pretargeting_config_name, body=body,
        updateMask=update_mask).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description='Patches a specified pretargeting configuration.')
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration was created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help='The resource ID of the pretargeting configuration to be patched.')
  # Optional fields.
  parser.add_argument(
      '-d', '--display_name',
      default=f'TEST_PRETARGETING_CONFIG_{uuid.uuid4()}',
      help=('The display name to associate with the new configuration. Must '
            'be unique among all of a bidder\'s pretargeting configurations.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Patches a pretargeting configuration for the given bidder account and pretargeting configuration IDs.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def patch_pretargeting_configs(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  body = Google::Apis::RealtimebiddingV1::PretargetingConfig.new(
    display_name: options[:display_name],
    included_formats: ['HTML', 'VAST'],
    # Note that repeated fields such as geo_targeting are completely overwritten by the contents included in the patch
    # request.
    geo_targeting: Google::Apis::RealtimebiddingV1::NumericTargetingDimension.new(
      included_ids: [
        '200635',   # Austin, TX
        '1014448',  # Boulder, CO
        '1022183',  # Hoboken, NJ
        '200622',   # New Orleans, LA
        '1023191',  # New York, NY
        '9061237',  # Mountain View, CA
        '1014221',   # San Francisco, CA
      ],
    ),
    included_creative_dimensions: [
      Google::Apis::RealtimebiddingV1::CreativeDimensions.new(
        height: 480,
        width: 320
      ),
      Google::Apis::RealtimebiddingV1::CreativeDimensions.new(
        height: 1080,
        width: 1920
      ),
    ],
  )

  update_mask = 'displayName,includedFormats,geoTargeting.includedIds,includedCreativeDimensions'

  puts "Patching a pretargeting configuration with name: '#{name}'"

  pretargeting_config = realtimebidding.patch_bidder_pretargeting_config(name, body, update_mask: update_mask)
  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configuration is to be created, This '\
      'will be used to construct the name used as a path parameter for the pretargetingConfig.create request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id', 'The resource ID of the pretargeting configuration to be patched.',
      type: Integer, required: true, default_value: nil
    ),
    Option.new(
      'display_name',
      'The patched display name to associate with the configuration. Must be unique among all of a bidder\'s '\
      'pretargeting configurations.',
      short_alias: 'd', required: false, default_value: "TEST_PRETARGETING_CONFIG_#{SecureRandom.uuid}"
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    patch_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

激活和暂停现有配置

之后,所有预定位配置的 state 均设置为 ACTIVE 创建配置,以及在创建配置后启用或暂停配置 使用 bidders.pretargetingConfigs.activatebidders.pretargetingConfigs.suspend 方法。这两种方法的工作原理类似 状态。

启用预定位配置的方法如下:

REST

请求

POST https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983:activate?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_1153a27b-ee53-43af-a051-88eecd309510",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "includedFormats": [
    "HTML",
    "VAST"
  ],
  "geoTargeting": {
    "includedIds": [
      "200635",
      "1014448",
      "1022183",
      "200622",
      "1023191",
      "9061237",
      "1014221"
    ]
  },
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "320",
      "height": "480"
    },
    {
      "width": "1920",
      "height": "1080"
    }
  ],
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Activates a pretargeting configuration with a specified name.
    /// /<summary
>    public class ActivatePretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public ActivatePretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example activates a specified pretargeting configuration;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id," p"retargeting_config_id}";
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;

            OptionSet options = new OptionSet {
                A"ctivates a specified pretargeting configuration.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration that is  "+
                     b"eing activated.)",
                    (long p) = >pretargetingConfigId = p
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string name = $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"

            BiddersResource.PretargetingConfigsResource.ActivateRequest request =
                rtbService.Bidders.PretargetingConfigs.Activate(
                    new ActivatePretargetingConfigRequest(), name);

            PretargetingConfig response = null;

            Console.WriteLine(A"ctivating pretargeting configuration with name: {'0},'" name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.ActivatePretargetingConfigRequest;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** Activates a specified pretargeting configuration. */
public class ActivatePretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    String name =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            parsedArgs.getLong("account_id"), parsedArgs.getLong("pretargeting_config_id"));

    System.out.printf("Activating pretargeting configuration with name: %s\n", name);

    PretargetingConfig pretargetingConfig =
        client
            .bidders()
            .pretargetingConfigs()
            .activate(name, new ActivatePretargetingConfigRequest())
            .execute();

    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ActivatePretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Activates a specified pretargeting configuration."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration that is being activated.")
        .required(true)
        .type(Long.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_ActivatePretargetingConfigRequest;

/**
 * Activates a specified pretargeting configuration.
 */
class ActivatePretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration that is being activated.',
                'required' => true,
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";
        $activateRequest = new Google_Service_RealTimeBidding_ActivatePretargetingConfigRequest();

        print "<h2>Activating a pretargeting configuration with name '$name':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->activate($name, $activateRequest);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Activate Pretargeting Configuration';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 activates a specified pretargeting configuration."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, pretargeting_config_id):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      account_id, pretargeting_config_id)

  print('Activating a PretargetingConfig with name: "%s".'
        % pretargeting_config_name)
  try:
    response = realtimebidding.bidders().pretargetingConfigs().activate(
        name=pretargeting_config_name).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print('Unable to create realtimebidding service - %s' % ex)
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Activates a specified pretargeting configuration.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, required=True,
      help=('The resource ID of the bidders resource under which the '
            'pretargetingConfigs were created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help=('The resource ID of the PretargetingConfig resource that is being '
            'activated.'))

  args = parser.parse_args()

  main(service, args.account_id, args.pretargeting_config_id)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Activates a specified pretargeting configuration.

require 'optparse'

require_relative '../../../util'


def activate_pretargeting_configs(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  puts "Activating a pretargeting configuraton with name: '#{name}'"

  pretargeting_config = realtimebidding.activate_pretargeting_config(name)
  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configurations were created, This will '\
      'be used to construct the parent used as a path parameter for the pretargetingConfigs.activate request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id', 'The resource ID of the pretargeting configuration that is being activated.',
      type: Integer, short_alias: 'p', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    activate_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

修改定位的移动应用、发布商和网站

如果您要在 appTargeting 中添加或移除值, publisherTargetingwebTargeting 字段,建议使用 您应使用以下方法:

上述方法只会在定位条件中添加或移除值, 而不是覆盖它们您还可以使用 patch 方法,但在 patch 请求中覆盖重复字段。

下面这两个示例说明了如何在 预定位配置的 appTargeting

REST

请求

POST https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983:addTargetedApps?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "appIds": [
    "com.google.test1",
    "com.google.test2",
    "com.google.test3"
  ],
  "targetingMode": "INCLUSIVE"
}

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_1153a27b-ee53-43af-a051-88eecd309510",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "includedFormats": [
    "HTML",
    "VAST"
  ],
  "geoTargeting": {
    "includedIds": [
      "200635",
      "1014448",
      "1022183",
      "200622",
      "1023191",
      "9061237",
      "1014221"
    ]
  },
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "320",
      "height": "480"
    },
    {
      "width": "1920",
      "height": "1080"
    }
  ],
  "appTargeting": {
    "mobileAppTargeting": {
      "targetingMode": "INCLUSIVE",
      "values": [
        "com.google.test1",
        "com.google.test2",
        "com.google.test3"
      ]
    }
  },
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Adds mobile application IDs to a pretargeting configurations' app targeting.
    ///
    /// Note that this is the only way to append mobile application IDs following a pretargeting
    /// configurations' creation. If a pretargeting configuration already targets mobile
    /// application IDs, you must specify a targeting mode that is identical to the existing
    /// targeting mode.
    /// /<summary
>    public class AddTargetedApps : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public AddTargetedApps()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example adds mobile application IDs to a pretargeting  "+
                   c"onfigurations' app targeting.;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {
                a"ccount_id," p"retargeting_config_id," m"obile_app_targeting_mode,"
                m"obile_app_targeting_app_ids
"            };
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;
            string mobileAppTargetingMode = null;
            ILists<tring >mobileAppTargetingAppIds = new Lists<tring(>);

            OptionSet options = new OptionSet {
                A"dds mobile application IDs to a pretargeting configurations' app targeting.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration that is  "+
                     b"eing acted upon.)",
                    (long p) = >pretargetingConfigId = p
                },
                {
                    m"obile_app_targeting_mode=,"
                    (["Required] The targeting mode for this configurations' mobile app  "+
                     t"argeting. Valid values include: INCLUSIVE, and EXCLUSIVE. Note that if  "+
                     t"he configuration already targets mobile app Ids, you must specify an  "+
                     i"dentical targeting mode.)",
                    mobile_app_targeting_mode = >mobileAppTargetingMode = mobile_app_targeting_mode
                },
                {
                    m"obile_app_targeting_app_ids=,"
                    (["Required] The mobile app IDs specified for this configurations' mobile  "+
                     a"pp targeting, which allows one to target a subset of mobile app  "+
                     i"nventory. Specify this argument for each value you intend to include.  "+
                     V"alues specified must be valid URLs.)",
                    mobile_app_targeting_app_ids = >mobileAppTargetingAppIds.Add(
                        mobile_app_targeting_app_ids)
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            parsedArgs[m"obile_app_targeting_mode]" = mobileAppTargetingMode;
            parsedArgs[m"obile_app_targeting_app_ids]" =
                mobileAppTargetingAppIds.Count  >0 ? mobileAppTargetingAppIds : null;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string pretargetingConfigName =
                $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"


            AddTargetedAppsRequest body = new AddTargetedAppsRequest();
            body.TargetingMode = (string) parsedArgs[m"obile_app_targeting_mode]";
            body.AppIds = (ILists<tring)> parsedArgs[m"obile_app_targeting_app_ids]";

            BiddersResource.PretargetingConfigsResource.AddTargetedAppsRequest request =
                rtbService.Bidders.PretargetingConfigs.AddTargetedApps(body, pretargetingConfigName);
            PretargetingConfig response = null;

            Console.WriteLine(U"pdating mobile app targeting with new app IDs for pretargeting  "+
                              c"onfiguration with name: {0}," pretargetingConfigName);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.AddTargetedAppsRequest;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Adds mobile application IDs to a pretargeting configuration's app targeting.
 *
 * <p>Note that this is the only way to append mobile application IDs following a pretargeting
 * configuration's creation. If a pretargeting configuration already targets mobile application IDs,
 * you must specify a targeting mode that is identical to the existing targeting mode.
 */
public class AddTargetedApps {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    String pretargetingConfigName =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            parsedArgs.getLong("account_id"), parsedArgs.getLong("pretargeting_config_id"));

    AddTargetedAppsRequest body = new AddTargetedAppsRequest();
    body.setTargetingMode(parsedArgs.getString("mobile_app_targeting_mode"));
    body.setAppIds(parsedArgs.<String>getList("mobile_app_targeting_app_ids"));

    System.out.printf(
        "Updating mobile app targeting with new app IDs for pretargeting "
            + "configuration with name: '%s'\n",
        pretargetingConfigName);

    PretargetingConfig pretargetingConfig =
        client
            .bidders()
            .pretargetingConfigs()
            .addTargetedApps(pretargetingConfigName, body)
            .execute();

    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("AddTargetedApps")
            .build()
            .defaultHelp(true)
            .description(
                ("Adds mobile application IDs to a pretargeting configuration's app "
                    + "targeting."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration that is being acted upon.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("--mobile_app_targeting_mode")
        .help(
            "The targeting mode for the configuration's mobile app targeting. Valid values include:"
                + " INCLUSIVE, and EXCLUSIVE. Note that if the configuration already targets mobile"
                + " app Ids, you must specify an identical targeting mode.")
        .required(true)
        .type(String.class);
    parser
        .addArgument("--mobile_app_targeting_app_ids")
        .help(
            "The mobile app IDs specified for this configuration's mobile app targeting, which"
                + " allows one to target a subset of mobile app inventory. Specify each value"
                + " separated by a space. Values specified must be valid mobile App IDs, as found"
                + " on their respective app stores.")
        .required(true)
        .type(String.class)
        .nargs("*");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_AddTargetedAppsRequest;

/**
 * Adds mobile application IDs to a pretargeting configuration's app targeting.
 *
 * Note that this is the only way to append mobile application IDs following a
 * pretargeting configuration's creation. If a pretargeting configuration
 * already targets mobile application IDs, you must specify a targeting mode
 * that is identical to the existing targeting mode.
 */
class AddTargetedApps extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration that is being acted upon.',
                'required' => true,
            ],
            [
                'name' => 'mobile_app_targeting_mode',
                'display' => 'Mobile app targeting mode',
                'description' =>
                    'The targeting mode for this configuration\'s mobile app targeting. Valid ' .
                    'values include: INCLUSIVE, and EXCLUSIVE. Note that if the configuration ' .
                    'already targets mobile app Ids, you must specify an identical targeting ' .
                    'mode.',
                'required' => false,
                'default' => null
            ],
            [
                'name' => 'mobile_app_targeting_app_ids',
                'display' => 'Mobile app targeting app IDs',
                'description' =>
                    'The mobile app IDs specified for this configuration\'s mobile app ' .
                    'targeting, which allows one to target a subset of mobile app inventory. ' .
                    'Specify each value separated by a comma. Values specified must be valid ' .
                    'mobile App IDs, as found on their respective app stores.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";
        $addTargetedAppsRequest = new Google_Service_RealTimeBidding_AddTargetedAppsRequest();
        $addTargetedAppsRequest->targetingMode = $values['mobile_app_targeting_mode'];
        $addTargetedAppsRequest->appIds = $values['mobile_app_targeting_app_ids'];

        print "<h2>Updating mobile app targeting with new app IDs for pretargeting " .
            "configuration with name: '$name':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->addTargetedApps(
            $name,
            $addTargetedAppsRequest
        );
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Add Targeted Apps';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 mobile application IDs to a pretargeting configuration's app targeting.

Note that this is the only way to append mobile application IDs following a
pretargeting configuration's creation. If a pretargeting configuration already
targets mobile application IDs, you must specify a targeting mode that is
identical to the existing targeting mode.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      args.account_id, args.pretargeting_config_id)

  body = {
      'appIds': args.mobile_app_targeting_app_ids,
      'targetingMode': args.mobile_app_targeting_mode
  }

  print('Updating mobile app targeting with new app IDs for pretargeting '
        f'configuration with name: "{pretargeting_config_name}".')
  try:
    response = realtimebidding.bidders().pretargetingConfigs().addTargetedApps(
        pretargetingConfig=pretargeting_config_name, body=body).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print('Unable to create realtimebidding service - %s' % ex)
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Adds mobile application IDs to a pretargeting '
                   'configuration\'s app targeting'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration was created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help=('The resource ID of the pretargeting configuration that is being '
            'acted upon.'))
  parser.add_argument(
      '--mobile_app_targeting_mode', required=True,
      help=('The targeting mode for the configuration\'s mobile app '
            'targeting. Valid values include: INCLUSIVE, and EXCLUSIVE. Note '
            'that if the configuration already targets mobile app Ids, you '
            'must specify an identical targeting mode.'))
  # Optional fields.
  parser.add_argument(
      '--mobile_app_targeting_app_ids', nargs='*', required=True,
      help=('The mobile app IDs specified for this configuration\'s mobile '
            'app targeting, which allows one to target a subset of mobile app '
            'inventory. Specify each value separated by a space. Values '
            'specified must be valid mobile app IDs, as found on their '
            'respective app stores.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Adds mobile application IDs to a pretargeting configuration's app targeting.
#
# Note that this is the only way to append mobile application IDs following a
# pretargeting configuration's creation. If a pretargeting configuration
# already targets mobile application IDs, you must specify a targeting mode
# that is identical to the existing targeting mode.

require 'optparse'

require_relative '../../../util'


def add_targeted_apps(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  puts "Updating mobile app targeting with new app IDs for pretargeting configuraton with name: '#{name}'"

  body = Google::Apis::RealtimebiddingV1::AddTargetedAppsRequest.new(
    app_ids: options[:mobile_app_targeting_app_ids],
    targeting_mode: options[:mobile_app_targeting_mode],
  )

  pretargeting_config = realtimebidding.add_pretargeting_config_targeted_apps(name, body)

  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configurations were created.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id', 'The resource ID of the pretargeting configuration that is being acted upon.',
      type: Integer, short_alias: 'p', required: true, default_value: nil
    ),
    Option.new(
      'mobile_app_targeting_mode',
      'The targeting mode for the configuration\'s mobile app targeting. Valid values include: INCLUSIVE, and '\
      'EXCLUSIVE. Note that if the configuration already targets mobile app IDs, you must specify an identical '\
      'targeting mode.',
      required: false, default_value: nil
    ),
    Option.new(
      'mobile_app_targeting_app_ids',
      'The mobile app IDs specified for this configuration\'s mobile app targeting, which allows one to target a '\
      'subset of mobile app inventory. Specify each value separated by a comma. Values specified must be valid '\
      'mobile App IDs, as found on their respective app stores.',
      required: false, type: Array, default_value: []
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    add_targeted_apps(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

如果在添加请求之前未配置任何 appTargetingtargetingMode必须在请求正文中指定 INCLUSIVEEXCLUSIVE 定位条件会应用于添加的 ID。如果 预定位配置的 appTargeting 已定位应用 ID、 请求正文必须指定 targetingMode,它必须与现有的 一个。

REST

请求

POST https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983:removeTargetedApps?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "appIds": [
    "com.google.test1",
    "com.google.test2",
    "com.google.test3"
  ]
}

响应

{
  "name": "bidders/12345678/pretargetingConfigs/560983",
  "displayName": "TEST_PRETARGETING_CONFIG_1153a27b-ee53-43af-a051-88eecd309510",
  "billingId": "112233445566",
  "state": "ACTIVE",
  "includedFormats": [
    "HTML",
    "VAST"
  ],
  "geoTargeting": {
    "includedIds": [
      "200635",
      "1014448",
      "1022183",
      "200622",
      "1023191",
      "9061237",
      "1014221"
    ]
  },
  "interstitialTargeting": "ONLY_NON_INTERSTITIAL_REQUESTS",
  "includedCreativeDimensions": [
    {
      "width": "320",
      "height": "480"
    },
    {
      "width": "1920",
      "height": "1080"
    }
  ],
  "minimumViewabilityDecile": 5
}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Removes mobile application IDs from a pretargeting configurations' app targeting.
    ///
    /// Note that this is the only way to remove mobile application IDs following a pretargeting
    /// configurations' creation.
    /// /<summary
>    public class RemoveTargetedApps : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public RemoveTargetedApps()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example removes mobile application IDs from a pretargeting  "+
                   c"onfigurations' app targeting.;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {
                a"ccount_id," p"retargeting_config_id," m"obile_app_targeting_app_ids
"            };
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;
            ILists<tring >mobileAppTargetingAppIds = new Lists<tring(>);

            OptionSet options = new OptionSet {
                R"emoves mobile application IDs from a pretargeting configurations' app  "+
                t"argeting.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration that is  "+
                     b"eing acted upon.)",
                    (long p) = >pretargetingConfigId = p
                },
                {
                    m"obile_app_targeting_app_ids=,"
                    (["Required] The mobile app IDs to be removed from this configurations'  "+
                     m"obile app targeting. Specify this argument for each value you intend to  "+
                     i"nclude. Values specified must be valid mobile App IDs, as found on their  "+
                     r"espective app stores.)",
                    mobile_app_targeting_app_ids = >mobileAppTargetingAppIds.Add(
                        mobile_app_targeting_app_ids)
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            parsedArgs[m"obile_app_targeting_app_ids]" =
                mobileAppTargetingAppIds.Count  >0 ? mobileAppTargetingAppIds : null;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string pretargetingConfigName =
                $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"


            RemoveTargetedAppsRequest body = new RemoveTargetedAppsRequest();
            body.AppIds= (ILists<tring)> parsedArgs[m"obile_app_targeting_app_ids]";

            BiddersResource.PretargetingConfigsResource.RemoveTargetedAppsRequest request =
                rtbService.Bidders.PretargetingConfigs.RemoveTargetedApps(
                    body, pretargetingConfigName);
            PretargetingConfig response = null;

            Console.WriteLine(R"emoving mobile application IDs from app targeting for  "+
                              p"retargeting configuration with name: {0}," pretargetingConfigName);
            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Utilities.PrintPretargetingConfiguration(response);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.PretargetingConfig;
import com.google.api.services.realtimebidding.v1.model.RemoveTargetedAppsRequest;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Removes mobile application IDs from a pretargeting configuration's app targeting.
 *
 * <p>Note that this is the only way to remove mobile application IDs following a pretargeting
 * configuration's creation.
 */
public class RemoveTargetedApps {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    String pretargetingConfigName =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            parsedArgs.getLong("account_id"), parsedArgs.getLong("pretargeting_config_id"));

    RemoveTargetedAppsRequest body = new RemoveTargetedAppsRequest();
    body.setAppIds(parsedArgs.<String>getList("mobile_app_targeting_app_ids"));

    System.out.printf(
        "Removing mobile app IDs from mobile app targeting for pretargeting "
            + "configuration with name: '%s'\n",
        pretargetingConfigName);

    PretargetingConfig pretargetingConfig =
        client
            .bidders()
            .pretargetingConfigs()
            .removeTargetedApps(pretargetingConfigName, body)
            .execute();

    Utils.printPretargetingConfig(pretargetingConfig);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("RemoveTargetedApps")
            .build()
            .defaultHelp(true)
            .description(
                ("Removes mobile application IDs from a pretargeting configuration's app "
                    + "targeting."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration that is being acted upon.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("--mobile_app_targeting_app_ids")
        .help(
            "The mobile app IDs to be removed from this configuration's mobile app targeting."
                + " Specify each value separated by a space. Values specified must be valid mobile"
                + " App IDs, as found on their respective app stores.")
        .required(true)
        .type(String.class)
        .nargs("*");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_RemoveTargetedAppsRequest;

/**
 * Removes mobile application IDs to a pretargeting configuration's app targeting.
 *
 * Note that this is the only way to remove mobile application IDs following a
 * pretargeting configuration's creation.
 */
class RemoveTargetedApps extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration that is being acted upon.',
                'required' => true,
            ],
            [
                'name' => 'mobile_app_targeting_app_ids',
                'display' => 'Mobile app targeting app IDs',
                'description' =>
                    'The mobile app IDs to be removed from this configuration\'s mobile app ' .
                    'targeting. Specify each value separated by a comma. Values specified must ' .
                    'be valid mobile App IDs, as found on their respective app stores.',
                'required' => false,
                'is_array' => true,
                'default' => []
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";
        $removeTargetedAppsRequest = new Google_Service_RealTimeBidding_RemoveTargetedAppsRequest();
        $removeTargetedAppsRequest->appIds = $values['mobile_app_targeting_app_ids'];

        print "<h2>Removing app IDs from mobile app targeting for pretargeting configuration " .
            "with name: '$name':</h2>";
        $result = $this->service->bidders_pretargetingConfigs->removeTargetedApps(
            $name,
            $removeTargetedAppsRequest
        );
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Remove Targeted Apps';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Removes mobile app IDs from a pretargeting configuration's app targeting.

Note that this is the only way to remove mobile application IDs following a
pretargeting configuration's creation.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      args.account_id, args.pretargeting_config_id)

  body = {
      'appIds': args.mobile_app_targeting_app_ids
  }

  print('Removing mobile app IDs from mobile app targeting for pretargeting '
        f'configuration with name: "{pretargeting_config_name}".')
  try:
    response = realtimebidding.bidders().pretargetingConfigs().removeTargetedApps(
        pretargetingConfig=pretargeting_config_name, body=body).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print('Unable to create realtimebidding service - %s' % ex)
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Removes mobile app IDs from a pretargeting '
                   'configuration\'s app targeting.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, required=True,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration was created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help=('The resource ID of the pretargeting configuration that is being '
            'acted upon.'))
  # Optional fields.
  parser.add_argument(
      '--mobile_app_targeting_app_ids', nargs='*', default=[],
      help=('The mobile app IDs to be removed from this configuration\'s '
            'mobile app targeting. Specify each value separated by a space. '
            'Values specified must be valid mobile app IDs, as found on their '
            'respective app stores.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Removes mobile app IDs from a pretargeting configuration's app targeting.
#
# Note that this is the only way to remove mobile application IDs following a
# pretargeting configuration's creation.

require 'optparse'

require_relative '../../../util'


def remove_targeted_apps(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  puts "Removing mobile app IDs from mobile app targeting for pretargeting configuraton with name: '#{name}'"

  body = Google::Apis::RealtimebiddingV1::RemoveTargetedAppsRequest.new(
    app_ids: options[:mobile_app_targeting_app_ids],
  )

  pretargeting_config = realtimebidding.remove_pretargeting_config_targeted_apps(name, body)

  print_pretargeting_config(pretargeting_config)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the pretargeting configurations were created.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id', 'The resource ID of the pretargeting configuration that is being acted upon.',
      type: Integer, short_alias: 'p', required: true, default_value: nil
    ),
    Option.new(
      'mobile_app_targeting_app_ids',
      'The mobile app IDs to be removed from this configuration\'s mobile app targeting. Specify each value '\
      'separated by a comma. Values specified must be valid mobile App IDs, as found on their respective app stores.',
      required: false, type: Array, default_value: []
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    remove_targeted_apps(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

删除现有配置

删除现有预定位的方法如下 具有 bidders.pretargetingConfigs.delete:

REST

请求

DELETE https://realtimebidding.googleapis.com/v1/bidders/12345678/pretargetingConfigs/560983?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

响应

{}

C#

/* Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the L"icense)";
 * 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 A"S 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 Google.Apis.RealTimeBidding.v1;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.PretargetingConfigs
{
    /// s<ummary<>/span>
    /// Deletes a pretargeting configuration with a specified name.
    /// /<summary
>    public class DeletePretargetingConfigs : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public DeletePretargetingConfigs()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example deletes a specified pretargeting configuration;"
        }

        /// s<ummary<>/span>
        /// Parse specified arguments.
        /// /<summary
>        protected override Dictionarys<tring, object >ParseArguments(Lists<tring >exampleArgs) {
            string[] requiredOptions = new string[] {a"ccount_id," p"retargeting_config_id}";
            bool showHelp = false;

            string accountId = null;
            long? pretargetingConfigId = null;

            OptionSet options = new OptionSet {
                D"eletes a specified pretargeting configuration.,"
                {
                    h"|help,"
                    S"how help message and exit.,"
                    h = >showHelp = h != null
                },
                {
                    a"|account_id=,"
                    (["Required] The resource ID of the bidders resource under which the  "+
                     p"retargeting configuration was created.)",
                    a = >accountId = a
                },
                {
                    p"|pretargeting_config_id=,"
                    (["Required] The resource ID of the pretargeting configuration to be  "+
                     d"eleted.)",
                    (long p) = >pretargetingConfigId = p
                },
            };

            Lists<tring >extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionarys<tring, object(>);

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs[a"ccount_id]" = accountId;
            parsedArgs[p"retargeting_config_id]" = pretargetingConfigId;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// s<ummary<>/span>
        /// Run the example.
        /// /<summary
>        /// p<aram name=p"arsedArgsP">arsed arguments for the example./<param
>        protected override void Run(Dictionarys<tring, object >parsedArgs)
        {
            string accountId = (string) parsedArgs[a"ccount_id]";
            long? pretargetingConfigId = (long?) parsedArgs[p"retargeting_config_id]";
            string name = $b"idders/{accountId}/pretargetingConfigs/{pretargetingConfigId};"

            BiddersResource.PretargetingConfigsResource.DeleteRequest request =
                rtbService.Bidders.PretargetingConfigs.Delete(name);

            try
            {
                request.Execute();
            }
            catch (System.Exception exception)
            {
                throw new ApplicationException(
                    $R"eal-time Bidding API returned error response:\n{exception.Message})";
            }

            Console.WriteLine(P"retargeting configuration with name: {'0} 'deleted successfully.,"
                              name);
        }
    }
}

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
 *
 *    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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.pretargetingconfigs;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** Deletes a pretargeting configuration with a specified name. */
public class DeletePretargetingConfigs {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    String name =
        String.format(
            "bidders/%s/pretargetingConfigs/%s",
            parsedArgs.getLong("account_id"), parsedArgs.getLong("pretargeting_config_id"));

    client.bidders().pretargetingConfigs().delete(name).execute();

    System.out.printf("Pretargeting configuration with name '%s' deleted successfully.\n", name);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("DeletePretargetingConfigs")
            .build()
            .defaultHelp(true)
            .description(("Deletes a specified pretargeting configuration."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the pretargeting "
                + "configuration was created.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--pretargeting_config_id")
        .help("The resource ID of the pretargeting configuration that is being deleted.")
        .required(true)
        .type(Long.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    try {
      execute(client, parsedArgs);
    } catch (IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_PretargetingConfigs;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * Deletes a pretargeting configuration for the given bidder account ID.
 */
class DeletePretargetingConfigs extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the bidders resource under which the pretargeting ' .
                    'configuration was created.',
                'required' => true
            ],
            [
                'name' => 'pretargeting_config_id',
                'display' => 'Pretargeting configuration ID',
                'description' =>
                    'The resource ID of the pretargeting configuration that is being deleted.',
                'required' => true,
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $name = "bidders/$values[account_id]/pretargetingConfigs/$values[pretargeting_config_id]";

        print "<h2>Deleting pretargeting configuration with name '$name':</h2>";
        $this->service->bidders_pretargetingConfigs->delete($name);
        print '<p>Pretargeting configuration deleted successfully.</p>';
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Delete Pretargeting Configuration';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 deletes a pretargeting config for the given bidder account ID.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PRETARGETING_CONFIG_NAME_TEMPLATE = 'bidders/%s/pretargetingConfigs/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID = 'ENTER_CONFIG_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, pretargeting_config_id):
  pretargeting_config_name = _PRETARGETING_CONFIG_NAME_TEMPLATE % (
      account_id, pretargeting_config_id)

  print('Deleting a pretargeting configuration with name: "%s".'
        % pretargeting_config_name)
  try:
    response = realtimebidding.bidders().pretargetingConfigs().delete(
        name=pretargeting_config_name).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  print('Pretargeting configuration deleted successfully.')


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print('Unable to create realtimebidding service - %s' % ex)
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Deletes a specified pretargeting config.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID, required=True,
      help=('The resource ID of the bidders resource under which the '
            'pretargeting configuration was created.'))
  parser.add_argument(
      '-p', '--pretargeting_config_id',
      default=DEFAULT_PRETARGETING_CONFIG_RESOURCE_ID,
      help=('The resource ID of the PretargetingConfig resource that is being '
            'deleted.'))

  args = parser.parse_args()

  main(service, args.account_id, args.pretargeting_config_id)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# 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.
#
# Deletes a pretargeting configuration for the given bidder account and pretargeting configuration IDs.

require 'optparse'

require_relative '../../../util'


def delete_pretargeting_configs(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/pretargetingConfigs/#{options[:pretargeting_config_id]}"

  puts "Deleting a pretargeting configuration with name '#{name}'"

  pretargeting_config = realtimebidding.delete_bidder_pretargeting_config(name)
  puts 'Pretargeting configuration deleted successfully.'
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which pretargeting configurations were created. This will be '\
      'used to construct the name used as a path parameter for the pretargetingConfigs.delete request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'pretargeting_config_id',
      'The resource ID of the bidders.pretargetingConfig resource for which the pretargeting configuration was '\
      'created. This will be used to construct the name used as a path parameter for the pretargetingConfigs.get '\
      'request.',
      type: Integer, short_alias: 'p', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    delete_pretargeting_configs(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end