Zarządzanie połączeniami z wydawcami

Połączenie z wydawcą to połączenie między licytującym a wydawcą w Otwartym ustalaniu stawek.

Licytujący mogą używać połączeń z wydawcą, by kontrolować, od których sprzedawców będą otrzymywać pytania o stawkę. Połączenia z wydawcą są inicjowane tylko przez wydawcę i odrzucane lub odrzucane przez licytującego. Akceptacja prośby o połączenie pozwala wydawcy wysyłać pytania o stawkę do licytującego, dlatego zalecamy, aby licytujący przyjmowali tylko po podpisaniu umowy z wydawcą.

Do zarządzania prośbami o połączenie z wydawcą możesz używać zasobu bidders.publisherConnections.

W tym przewodniku bidderId jest Twoim identyfikatorem konta, a publisherId to identyfikator wydawcy z pliku ads.txt lub app-ads.txt. Ten plik jest hostowany przez witrynę lub aplikację wydawcy, np. http://example.com/ads.txt.

Możesz też użyć identyfikatora list, aby wyświetlić identyfikatory wydawców, którzy wysłały Ci prośbę o połączenie.

Oto kilka sposobów wykorzystania zasobu bidders.publisherConnections:

Wyświetl połączenia

Uzyskaj połączenie indywidualne

Możesz połączyć się z konkretnym wydawcą za pomocą metody get. Ta metoda zwraca obiekt PublisherConnection.

Oto przykładowe żądanie get:

REST

Żądanie

GET https://realtimebidding.googleapis.com/v1/bidders/{bidderId}/publisherConnections/{publisherId}

Odpowiedź

{
  "name":"bidders/12345/publisherConnections/pub-12345",
  "publisherPlatform":"GOOGLE_AD_MANAGER",
  "displayName":"Company A",
  "biddingState":"APPROVED",
  "createTime":"2022-10-02T15:01:23Z"
}

C#

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

using 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.PublisherConnections
{
    /// <summary>
    /// Gets a single publisher connection with a specified name.
    /// </summary>
    public class GetPublisherConnections : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetPublisherConnections()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example gets a specified publisher connection.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "publisher_connection_id"};
            bool showHelp = false;

            string accountId = null;
            string publisherConnectionId = null;

            OptionSet options = new OptionSet {
                "Gets a specified publisher connection.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource under which the " +
                     "publisher connection exists. This will be used to construct the name used " +
                     "as a path parameter for the publisherConnections.get request."),
                    a => accountId = a
                },
                {
                    "p|publisher_connection_id=",
                    ("[Required] The resource ID of the publisher connection that is being " +
                     "retrieved. This value is the publisher ID found in ads.txt or " +
                     "app-ads.txt, and is used to construct the name used as a path parameter " +
                     "for the publisherConnections.get request."),
                    p => publisherConnectionId = p
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

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

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string publisherConnectionId = (string) parsedArgs["publisher_connection_id"];
            string name = $"bidders/{accountId}/publisherConnections/{publisherConnectionId}";

            BiddersResource.PublisherConnectionsResource.GetRequest request =
                rtbService.Bidders.PublisherConnections.Get(name);

            PublisherConnection response = null;

            Console.WriteLine("Retrieving publisher connection with name: '{0}'", name);

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

            Utilities.PrintPublisherConnection(response);
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.publisherConnections;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.PublisherConnection;
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;

/**
 * This sample illustrates how to get a single publisher connection for the given bidder.
 *
 * <p>Note: This sample will only return a populated response for bidders who are exchanges
 * participating in Open Bidding.
 */
public class GetPublisherConnections {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Integer accountId = parsedArgs.getInt("account_id");
    String publisherConnectionId = parsedArgs.getString("publisher_connection_id");
    String name =
        String.format("bidders/%d/publisherConnections/%s", accountId, publisherConnectionId);

    PublisherConnection publisherConnection =
        client.bidders().publisherConnections().get(name).execute();

    System.out.printf("Get publisher connection with name \"%s\":\n", name);
    Utils.printPublisherConnection(publisherConnection);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetPublisherConnections")
            .build()
            .defaultHelp(true)
            .description(
                ("Get a publisher connection for the given bidder and publisher connection IDs"));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the publisher connection exists. "
                + "This will be used to construct the name used as a path parameter for the "
                + "publisherConnections.get request.")
        .required(true)
        .type(Integer.class);
    parser
        .addArgument("-p", "--publisher_connection_id")
        .help(
            "The resource ID of the publisher connection that is being retrieved. This value is the"
                + " publisher ID found in ads.txt or app-ads.txt, and is used to construct the name"
                + " used as a path parameter for the publisherConnections.get request.")
        .required(true);

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

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

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

/**
 * Gets a single publisher connection for the given bidder's account ID.
 *
 * Note: This sample will only return a populated response for bidders who are
 * exchanges participating in Open Bidding.
 */
class GetPublisherConnections 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 publisher ' .
                    'connection exists. This will be used to construct the name used as a path ' .
                    'parameter for the publisherConnections.get request.',
                'required' => true
            ],
            [
                'name' => 'publisher_connection_id',
                'display' => 'Publisher connection ID',
                'description' =>
                    'The resource ID of the publisher connection that is being retrieved. This ' .
                    'value is the publisher ID found in ads.txt or app-ads.txt, and is used to ' .
                    'construct the name used as a path parameter for the ' .
                    'publisherConnections.get request.',
                'required' => true,
            ]
        ];
    }

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

        print "<h2>Retrieving publisher connection with name '$name':</h2>";
        $result = $this->service->bidders_publisherConnections->get($name);
        $this->printResult($result);
    }

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

Python

#!/usr/bin/python
#
# Copyright 2022 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 publisher connection for the given bidder.

Note: This sample will only return a populated response for bidders who are
exchanges participating in Open Bidding.
"""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_PUBLISHER_CONNECTION_NAME_TEMPLATE = 'bidders/%s/publisherConnections/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'
DEFAULT_PUBLISHER_CONNECTION_RESOURCE_ID = 'ENTER_CONNECTION_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, publisher_connection_id):
  publisher_connection_name = _PUBLISHER_CONNECTION_NAME_TEMPLATE % (
      account_id, publisher_connection_id)

  print('Retrieving a publisher connection with name: '
        f'"{publisher_connection_name}".')
  try:
    response = realtimebidding.bidders().publisherConnections().get(
        name=publisher_connection_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 publisher connection for the given bidder and '
                   'publisher connection IDs.'))
  # 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 '
            'publisher connection exists. This will be used to construct the '
            'name used as a path parameter for the publisherConnections.get '
            'request.'))
  parser.add_argument(
      '-p', '--publisher_connection_id',
      default=DEFAULT_PUBLISHER_CONNECTION_RESOURCE_ID, required=True,
      help=('The resource ID of the publisher connection that is being '
            'retrieved. This value is the publisher ID found in ads.txt or '
            'app-ads.txt, and is used to construct the name used as a path '
            'parameter for the publisherConnections.get request.'))

  args = parser.parse_args()

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


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2022 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 single publisher connection for the given bidder.
#
# Note: This sample will only return a populated response for bidders who are
# exchanges participating in Open Bidding.

require 'optparse'

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


def get_publisher_connections(realtimebidding, options)
  name = "bidders/#{options[:account_id]}/publisherConnections/#{options[:publisher_connection_id]}"

  puts "Get publisher connection with name '#{name}'"

  publisher_connection = realtimebidding.get_bidder_publisher_connection(name)
  print_publisher_connection(publisher_connection)
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 publisher connection exists. This will be used to '\
      'construct the name used as a path parameter for the publisherConnections.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'publisher_connection_id',
      'The resource ID of the publisher connection that is being retrieved. This value is the publisher ID found in '\
      'ads.txt or app-ads.txt, and is used to construct the name used as a path parameter for the '\
      'publisherConnections.get request.',
      type: String, short_alias: 'p', required: true, default_value: nil
    ),
  ]

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

  begin
    get_publisher_connections(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

Pokaż wszystkie połączenia

Wszystkie prośby o połączenia możesz wyświetlać za pomocą metody list. Aby zawęzić wyniki, możesz użyć filtrów list i metody list, np. aby wyświetlić połączenia według stanu ustalania stawek.

Oto przykład żądania list z filtrem dla danych publisherPlatform ustawionym na GOOGLE_AD_MANAGER:

REST

Żądanie

GET https://realtimebidding.googleapis.com/v1/bidders/{bidderId}/publisherConnections?filter=publisherPlatform+%3D+GOOGLE_AD_MANAGER

Odpowiedź

{
  "publisherConnections":[
     {
        "name":"bidders/12345/publisherConnections/pub-12345",
        "publisherPlatform":"GOOGLE_AD_MANAGER",
        "displayName":"Company A",
        "biddingState":"APPROVED",
        "createTime":"2022-10-02T15:01:23Z"
     },
     {
        "name":"bidders/12345/publisherConnections/pub-23456",
        "publisherPlatform":"GOOGLE_AD_MANAGER",
        "displayName":"Company B",
        "biddingState":"APPROVED",
        "createTime":"2022-10-02T15:01:23Z"
     },
     {
        "name":"bidders/12345/publisherConnections/pub-78901",
        "publisherPlatform":"GOOGLE_AD_MANAGER",
        "displayName":"Company C",
        "biddingState":"REJECTED",
        "createTime":"2022-10-02T15:01:23Z"
     }
  ]
}

C#

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

using 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.PublisherConnections
{
    /// <summary>
    /// Lists publisher connections for a given bidder account ID.
    /// </summary>
    public class ListPublisherConnections : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListPublisherConnections()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists all publisher connections for a given bidder " +
                   "account.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;
            string defaultFilter = "publisherPlatform = GOOGLE_AD_MANAGER";
            string defaultOrderBy = "createTime DESC";
            string filter = null;
            string orderBy = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List publisher connections for the given bidder account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] 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."),
                    a => accountId = a
                },
                {
                    "f|filter=",
                    ("Query string to filter publisher connections. To demonstrate usage, this " +
                     "sample will default to filtering by publisherPlatform."),
                    f => filter =  f
                },
                {
                    "o|order_by=",
                    ("A string specifying the order by which results should be sorted. To " +
                     "demonstrate usage, this sample will default to ordering by createTime."),
                    o => orderBy =  o
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

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

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"bidders/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing publisher connections for bidder account ""{0}""", parent);
            do
            {
                BiddersResource.PublisherConnectionsResource.ListRequest request =
                   rtbService.Bidders.PublisherConnections.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.OrderBy = (string) parsedArgs["order_by"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListPublisherConnectionsResponse page = null;

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

                var publisherConnections = page.PublisherConnections;
                pageToken = page.NextPageToken;

                if(publisherConnections == null)
                {
                    Console.WriteLine("No publisher connections found for bidder account.");
                }
                else
                {
                    foreach (PublisherConnection connection in publisherConnections)
                        {
                            Utilities.PrintPublisherConnection(connection);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.publisherConnections;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.ListPublisherConnectionsResponse;
import com.google.api.services.realtimebidding.v1.model.PublisherConnection;
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 a given bidder's publisher connections.
 *
 * <p>Note: This sample will only return a populated response for bidders who are exchanges
 * participating in Open Bidding.
 */
public class ListPublisherConnections {

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

    System.out.printf("Listing publisher connections for bidder with name \"%s\":%n", parent);

    do {
      List<PublisherConnection> publisherConnections = null;

      ListPublisherConnectionsResponse response = client
          .bidders()
          .publisherConnections()
          .list(parent)
          .setPageSize(pageSize)
          .setPageToken(pageToken)
          .execute();

      publisherConnections = response.getPublisherConnections();
      pageToken = response.getNextPageToken();

      if (publisherConnections == null) {
        System.out.println("No publisher connections found.");
      } else {
        for (PublisherConnection publisherConnection : publisherConnections) {
          Utils.printPublisherConnection(publisherConnection);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListPublisherConnections")
            .build()
            .defaultHelp(true)
            .description("Lists publisher connections associated with the given bidder account.");
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The number of rows to return per page. The server may return fewer rows than "
                + "specified.")
        .required(true)
        .type(Integer.class);
    parser
        .addArgument("-f", "--filter")
        .help(
            "Query string to filter publisher connections. To demonstrate usage, this sample "
                + "will default to filtering by publisherPlatform.")
        .setDefault("publisherPlatform = GOOGLE_AD_MANAGER");
    parser
        .addArgument("-o", "--order_by")
        .help(
            "A string specifying the order by which results should be sorted. To demonstrate "
                + "usage, this sample will default to ordering by createTime.")
        .setDefault("createTime DESC");
    parser
        .addArgument("-p", "--page_size")
        .help(
            "The number of rows to return per page. The server may return fewer rows than "
                + "specified.")
        .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 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

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

/**
 * Lists publisher connections for a given bidder account ID.
 *
 * Note: This sample will only return a populated response for bidders who are
 * exchanges participating in Open Bidding.
 */
class ListPublisherConnections 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 publisher ' .
                    'connections exist. This will be used to construct the parent ' .
                    'used as a path parameter for the publisherConnections.list request.'
            ],
            [
                'name' => 'filter',
                'display' => 'Filter',
                'required' => false,
                'description' =>
                    'Query string used to filter publisher connections. To demonstrate usage, ' .
                    'this sample will default to filtering by publisherPlatform.',
                'default' => 'publisherPlatform = GOOGLE_AD_MANAGER'
            ],
            [
                'name' => 'order_by',
                'display' => 'Order by',
                'required' => false,
                'description' =>
                    'A string specifying the order by which results should be sorted. To ' .
                    'demonstrate usage, this sample will default to ordering by createTime.',
                'default' => 'createTime DESC'
            ],
            [
                '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 = [
            'filter' => $values['filter'],
            'orderBy' => $values['order_by'],
            'pageSize' => $values['page_size']
        ];

        $result = $this->service->bidders_publisherConnections->listBiddersPublisherConnections(
            $parentName,
            $queryParams
        );

        print "<h2>Publisher connections found for '$parentName':</h2>";
        if (empty($result['publisherConnections'])) {
            print '<p>No publisher connections found</p>';
        } else {
            foreach ($result['publisherConnections'] as $publisherConnection) {
                $this->printResult($publisherConnection);
            }
        }
    }

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

Python

#!/usr/bin/python
#
# Copyright 2022 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 a bidder's publisher connections.

Note: This sample will only return a populated response for bidders who are
exchanges participating in Open Bidding.
"""


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 publisher connections for bidder account: '
        f'"{account_id}".')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.bidders().publisherConnections().list(
          parent=_BIDDER_NAME_TEMPLATE % account_id, pageToken=page_token,
          pageSize=args.page_size, filter=args.filter,
          orderBy=args.order_by).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 publisher connections 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 publisher '
            'connections exist. This will be used to construct the parent used '
            'as a path parameter for the publisherConnections.list request.'))
  # Optional fields.
  parser.add_argument(
      '-f', '--filter', default='publisherPlatform = GOOGLE_AD_MANAGER',
      help=('Query string used to filter publisher connections. To demonstrate '
            'usage, this sample will default to filtering by publisherPlatform.'
            ))
  parser.add_argument(
      '-o', '--order_by', default='createTime DESC',
      help=('A string specifying the order by which results should be sorted. '
            'To demonstrate usage, this sample will default to ordering by '
            'createTime.'))
  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 2022 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 a bidder's publisher connections.
#
# Note: This sample will only return a populated response for bidders who are
# exchanges participating in Open Bidding.

require 'optparse'

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


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

  page_token = nil

  puts "Listing publisher connections for bidder with name '#{parent}'"
  begin
    response = realtimebidding.list_bidder_publisher_connections(
        parent,
        filter: filter,
        order_by: order_by,
        page_size: page_size,
        page_token: page_token,
    )

    page_token = response.next_page_token

    unless response.publisher_connections.nil?
      response.publisher_connections.each do |publisher_connection|
        print_publisher_connection(publisher_connection)
      end
    else
      puts 'No publisher connections 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 publisher connections exist. This will be used to '\
      'construct the parent used as a path parameter for the publisherConnections.list request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'filter',
      'Query string used to filter publisher connections. To demonstrate usage, this sample will default to '\
      'filtering by publisherPlatform.',
      type: String, short_alias: 'f', required: false, default_value: 'publisherPlatform = GOOGLE_AD_MANAGER'
    ),
    Option.new(
      'order_by',
      'A string specifying the order by which results should be sorted. To demonstrate usage, this sample will '\
      'default to ordering by createTime.',
      type: String, short_alias: 'o', required: false, default_value: 'createTime DESC'
    ),
    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_publisher_connections(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

W tym przykładzie wywołanie list zawiera tylko niewielką liczbę połączeń. W przypadku krótkich odpowiedzi zwracany jest cały zestaw połączeń, a nie wyniki z podziałem na strony zawierające ciąg nextPageToken.

Zatwierdzanie próśb

Za pomocą batchApprove możesz zatwierdzić co najmniej jedną prośbę o połączenie z wydawcą. Możesz zatwierdzać nowe i wcześniej odrzucone prośby. Zalecamy zatwierdzanie połączeń z wydawcami, od których chcesz otrzymywać pytania o stawkę po podpisaniu umowy. Ta metoda zwraca zatwierdzone przez Ciebie obiekty PublisherConnection.

Oto przykład żądania batchApprove:

REST

Żądanie

POST https://realtimebidding.googleapis.com/v1/bidders/{bidderId}/publisherConnections:batchApprove

{
 "names": [
   "bidders/12345/publisherConnections/pub-12345",
   "bidders/12345/publisherConnections/pub-23456"
 ]
}

Odpowiedź

{
 "publisherConnections":[
   {
     "name":"bidders/12345/publisherConnections/pub-12345",
     "publisherPlatform":"GOOGLE_AD_MANAGER",
     "displayName":"Company A",
     "biddingState":"APPROVED",
     "createTime":"2022-10-02T15:01:23Z"
   },
   {
     "name":"bidders/12345/publisherConnections/pub-23456",
     "publisherPlatform":"GOOGLE_AD_MANAGER",
     "displayName":"Company B",
     "biddingState":"APPROVED",
     "createTime":"2022-10-02T15:01:23Z"
   }
 ]
}

C#

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

using 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.PublisherConnections
{
    /// <summary>
    /// Batch approves one or more publisher connections.
    ///
    /// Approving a publisher connection means that the bidder agrees to receive bid requests from
    /// the publisher.
    /// </summary>
    public class BatchApprovePublisherConnections : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public BatchApprovePublisherConnections()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example batch approves one or more publisher connections.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "publisher_connection_ids"};
            bool showHelp = false;

            string accountId = null;
            IList<string> publisherConnectionIds = new List<string>();

            OptionSet options = new OptionSet {
                "Batch approves one or more publisher connections to a given bidder account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource for which the " +
                     "publisher connections are being approved."),
                    a => accountId = a
                },
                {
                    "p|publisher_connection_ids=",
                    ("[Required] One or more resource IDs for the bidders.publisherConnections " +
                     "resource that are being approved. Specify this argument for each value " +
                     "you intend to include. Values specified must be valid URLs. These will be " +
                     "used to construct the publisher connection names passed in the " +
                     "publisherConnections.batchApprove request body"),
                    p => publisherConnectionIds.Add(p)
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["publisher_connection_ids"] =
                publisherConnectionIds.Count > 0 ? publisherConnectionIds : null;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"bidders/{accountId}";

            IList<string> publisherConnectionIds =
                (IList<string>) parsedArgs["publisher_connection_ids"];
            IList<string> publisherConnectionNames = new List<string>();

            foreach (string publisherConnectionId in publisherConnectionIds)
            {
                publisherConnectionNames.Add(
                    $"bidders/{accountId}/publisherConnections/{publisherConnectionId}");
            }

            BatchApprovePublisherConnectionsRequest body =
                new BatchApprovePublisherConnectionsRequest();
            body.Names = publisherConnectionNames;

            BiddersResource.PublisherConnectionsResource.BatchApproveRequest request =
                rtbService.Bidders.PublisherConnections.BatchApprove(body, parent);
            BatchApprovePublisherConnectionsResponse response = null;

            Console.WriteLine(
                "Batch approving publisher connections for bidder with name: {0}",
                parent);

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

            foreach (PublisherConnection publisherConnection in response.PublisherConnections)
            {
                Utilities.PrintPublisherConnection(publisherConnection);
            }
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.publisherConnections;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.BatchApprovePublisherConnectionsRequest;
import com.google.api.services.realtimebidding.v1.model.BatchApprovePublisherConnectionsResponse;
import com.google.api.services.realtimebidding.v1.model.PublisherConnection;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
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;

/**
 * Batch approves one or more publisher connections.
 *
 * <p>Approving a publisher connection means that the bidder agrees to receive bid requests from the
 * publisher.
 */
public class BatchApprovePublisherConnections {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Integer bidderAccountId = parsedArgs.getInt("account_id");
    String parent = String.format("bidders/%d", bidderAccountId);

    String publisherConnectionNameTemplate = "bidders/%d/publisherConnections/%s";
    List<String> publisherConnectionIds = parsedArgs.getList("publisher_connection_ids");
    List<String> publisherConnectionNames = new ArrayList<>(publisherConnectionIds.size());

    // Populate list of publisher connection names that are to be approved.
    for (String publisherConnectionId : publisherConnectionIds) {
      publisherConnectionNames.add(
          String.format(publisherConnectionNameTemplate, bidderAccountId, publisherConnectionId));
    }

    // Set list of publisher connection names to the API request body.
    BatchApprovePublisherConnectionsRequest body = new BatchApprovePublisherConnectionsRequest();
    body.setNames(publisherConnectionNames);

    System.out.printf("Batch approving publisher connections for bidder with name: '%s'\n", parent);

    BatchApprovePublisherConnectionsResponse batchApprovePublisherConnectionsResponse =
        client.bidders().publisherConnections().batchApprove(parent, body).execute();

    for (PublisherConnection publisherConnection :
        batchApprovePublisherConnectionsResponse.getPublisherConnections()) {
      Utils.printPublisherConnection(publisherConnection);
    }
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("BatchApprovePublisherConnections")
            .build()
            .defaultHelp(true)
            .description(
                ("Batch approves one or more publisher connections to a given bidder account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource for which the publisher connections are "
                + "being approved.")
        .required(true)
        .type(Integer.class);
    parser
        .addArgument("-p", "--publisher_connection_ids")
        .help(
            "One or more resource IDs for the bidders.publisherConnections resource that are "
                + "being approved. Specify each ID separated by a space. These will be used to "
                + "construct the publisher connection names passed in the "
                + "publisherConnections.batchApprove request body.")
        .required(true)
        .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 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

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

/**
 * Batch approves one or more publisher connections.
 *
 * Approving a publisher connection means that the bidder agrees to receive
 * bid requests from the publisher.
 */
class BatchApprovePublisherConnections 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 publisher ' .
                    'connections exist. This will be used to construct the parent used as a ' .
                    'path parameter for the publisherConnections.batchApprove request, as well ' .
                    'as the publisher connection names passed in the request body.',
                'required' => true
            ],
            [
                'name' => 'publisher_connection_ids',
                'display' => 'Publisher connection IDs',
                'description' =>
                    'One or more resource IDs for the bidders.publisherConnections resource ' .
                    'that are being approved. Specify each value separated by a comma. These ' .
                    'will be used to construct the publisher connection names passed in the ' .
                    'publisherConnections.batchApprove request body.',
                'required' => true,
                'is_array' => true
            ]
        ];
    }

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

        $pubConnIds = $values[publisher_connection_ids];
        $batchApproveRequest = new Google_Service_RealTimeBidding_BatchApprovePublisherConnectionsRequest();
        $batchApproveRequest->names = array_map(
            function ($pubConnId) use ($accountId) {
                    return "$parent/publisherConnections/$pubConnId";
            },
            $pubConnIds
        );

        print "<h2>Batch approving publisher connections for bidder with name: \"$parent\":";
        $result = $this->service->bidders_publisherConnections->batchApprove(
            $parent,
            $batchApproveRequest
        );
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Batch Approve Publisher Connections';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2022 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.

"""Batch approves one or more publisher connections.

Approving a publisher connection means that the bidder agrees to receive bid
requests from the publisher.
"""


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'
_PUBLISHER_CONNECTION_NAME_TEMPLATE = 'bidders/%s/publisherConnections/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  parent = _BIDDER_NAME_TEMPLATE % account_id

  body = {
      "names": [
          _PUBLISHER_CONNECTION_NAME_TEMPLATE % (
              account_id, publisher_connection_id)
          for publisher_connection_id in args.publisher_connection_ids
      ]
  }

  print('Batch approving publisher connections for bidder with name: '
        f'"{parent}".')
  try:
    response = realtimebidding.bidders().publisherConnections().batchApprove(
        parent=parent, 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='Batch approves one or more publisher connections.')
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'publisher connections exist. This will be used to construct the '
            'parent used as a path parameter for the '
            'publisherConnections.batchApprove request, as well as the '
            'publisher connection names passed in the request body.'))
  parser.add_argument(
      '-p', '--publisher_connection_ids', nargs='+', required=True,
      help=('One or more resource IDs for the bidders.publisherConnections '
            'resource that are being approved. Specify each value separated by '
            'a space. These will be used to construct the publisher connection '
            'names passed in the publisherConnections.batchApprove request '
            'body.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2022 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.
#
# Batch approves one or more publisher connections.
#
# Approving a publisher connection means that the bidder agrees to receive bid
# requests from the publisher.

require 'optparse'

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


def batch_approve_publisher_connections(realtimebidding, options)
  account_id = options[:account_id]
  parent = "bidders/#{account_id}"
  publisher_connection_names = options[:publisher_connection_ids].map{
      |publisher_connection_id| "bidders/#{account_id}/publisherConnections/#{publisher_connection_id}"}

  puts "Batch approving publisher connections for bidder with name: '#{parent}'"

  body = Google::Apis::RealtimebiddingV1::BatchApprovePublisherConnectionsRequest.new(
    names: publisher_connection_names
  )

  response = realtimebidding.batch_approve_publisher_connections(parent, body)

  unless response.publisher_connections.nil?
    response.publisher_connections.each do |publisher_connection|
      print_publisher_connection(publisher_connection)
    end
  end
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 publisher connections exist. This will be used to '\
      'construct the parent used as a path parameter for the publisherConnections.batchApprove request, as well as '\
      'the publisher connection names passed in the request body.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'publisher_connection_ids',
      'One or more resource IDs for the bidders.publisherConnections resource that are being approved. Specify each '\
      'value separated by a comma. These will be used to construct the publisher connection names passed in the '\
      'publisherConnections.batchApprove request body.',
      type: Array, short_alias: 'p', required: true, default_value: nil
    ),
  ]

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

  begin
    batch_approve_publisher_connections(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

Odrzuć prośby

Możesz użyć batchReject, aby odrzucić jedną lub więcej próśb o połączenie z wydawcą. Możesz odrzucać nowe i wcześniej zatwierdzone prośby. Ta metoda zwraca odrzucone obiekty PublisherConnection.

Oto przykład żądania batchReject:

REST

Żądanie

POST https://realtimebidding.googleapis.com/v1/bidders/{bidderId}/publisherConnections:batchReject

{
 "names":[
   "bidders/12345/publisherConnections/pub-12345",
   "bidders/12345/publisherConnections/pub-23456"
 ]
}

Odpowiedź

{
  "publisherConnections":[
    {
      "name":"bidders/12345/publisherConnections/pub-12345",
      "publisherPlatform":"GOOGLE_AD_MANAGER",
      "displayName":"Company A",
      "biddingState":"REJECTED",
      "createTime":"2022-10-02T15:01:23Z"
    },
    {
      "name":"bidders/12345/publisherConnections/pub-23456",
      "publisherPlatform":"GOOGLE_AD_MANAGER",
      "displayName":"Company B",
      "biddingState":"REJECTED",
      "createTime":"2022-10-02T15:01:23Z"
   }
 ]
}

C#

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

using 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.PublisherConnections
{
    /// <summary>
    /// Batch rejects one or more publisher connections.
    ///
    /// A bidder will not receive bid requests from publishers associated with rejected publisher
    /// connections.
    /// </summary>
    public class BatchRejectPublisherConnections : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public BatchRejectPublisherConnections()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example batch rejects one or more publisher connections.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "publisher_connection_ids"};
            bool showHelp = false;

            string accountId = null;
            IList<string> publisherConnectionIds = new List<string>();

            OptionSet options = new OptionSet {
                "Batch rejects one or more publisher connections to a given bidder account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource for which the " +
                     "publisher connections are being rejected."),
                    a => accountId = a
                },
                {
                    "p|publisher_connection_ids=",
                    ("[Required] One or more resource IDs for the bidders.publisherConnections " +
                     "resource that are being rejected. Specify this argument for each value " +
                     "you intend to include. Values specified must be valid URLs. These will be " +
                     "used to construct the publisher connection names passed in the " +
                     "publisherConnections.batchReject request body"),
                    p => publisherConnectionIds.Add(p)
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["publisher_connection_ids"] =
                publisherConnectionIds.Count > 0 ? publisherConnectionIds : null;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"bidders/{accountId}";

            IList<string> publisherConnectionIds =
                (IList<string>) parsedArgs["publisher_connection_ids"];
            IList<string> publisherConnectionNames = new List<string>();

            foreach (string publisherConnectionId in publisherConnectionIds)
            {
                publisherConnectionNames.Add(
                    $"bidders/{accountId}/publisherConnections/{publisherConnectionId}");
            }

            BatchRejectPublisherConnectionsRequest body =
                new BatchRejectPublisherConnectionsRequest();
            body.Names = publisherConnectionNames;

            BiddersResource.PublisherConnectionsResource.BatchRejectRequest request =
                rtbService.Bidders.PublisherConnections.BatchReject(body, parent);
            BatchRejectPublisherConnectionsResponse response = null;

            Console.WriteLine(
                "Batch rejecting publisher connections for bidder with name: {0}",
                parent);

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

            foreach (PublisherConnection publisherConnection in response.PublisherConnections)
            {
                Utilities.PrintPublisherConnection(publisherConnection);
            }
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders.publisherConnections;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.BatchRejectPublisherConnectionsRequest;
import com.google.api.services.realtimebidding.v1.model.BatchRejectPublisherConnectionsResponse;
import com.google.api.services.realtimebidding.v1.model.PublisherConnection;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
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;

/**
 * Batch rejects one or more publisher connections.
 *
 * <p>A bidder will not receive bid requests from publishers associated with rejected publisher
 * connections.
 */
public class BatchRejectPublisherConnections {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) throws IOException {
    Integer bidderAccountId = parsedArgs.getInt("account_id");
    String parent = String.format("bidders/%d", bidderAccountId);

    String publisherConnectionNameTemplate = "bidders/%d/publisherConnections/%s";
    List<String> publisherConnectionIds = parsedArgs.getList("publisher_connection_ids");
    List<String> publisherConnectionNames = new ArrayList<>(publisherConnectionIds.size());

    for (String publisherConnectionId : publisherConnectionIds) {
      publisherConnectionNames.add(
          String.format(publisherConnectionNameTemplate, bidderAccountId, publisherConnectionId));
    }

    BatchRejectPublisherConnectionsRequest body = new BatchRejectPublisherConnectionsRequest();
    body.setNames(publisherConnectionNames);

    System.out.printf("Batch rejecting publisher connections for bidder with name: '%s'\n", parent);

    BatchRejectPublisherConnectionsResponse batchRejectPublisherConnectionsResponse =
        client.bidders().publisherConnections().batchReject(parent, body).execute();

    for (PublisherConnection publisherConnection :
        batchRejectPublisherConnectionsResponse.getPublisherConnections()) {
      Utils.printPublisherConnection(publisherConnection);
    }
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("BatchRejectPublisherConnections")
            .build()
            .defaultHelp(true)
            .description(
                ("Batch rejects one or more publisher connections from a given bidder account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource for which the publisher connections are "
                + "being rejected.")
        .required(true)
        .type(Integer.class);
    parser
        .addArgument("-p", "--publisher_connection_ids")
        .help(
            "One or more resource IDs for the bidders.publisherConnections resource that are "
                + "being rejected. Specify each ID separated by a space. These will be used to "
                + "construct the publisher connection names passed in the "
                + "publisherConnections.batchReject request body.")
        .required(true)
        .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 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

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

/**
 * Batch rejects one or more publisher connections.
 *
 * A bidder will not receive bid requests from publishers associated with
 * rejected publisher connections.
 */
class BatchRejectPublisherConnections 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 publisher ' .
                    'connections exist. This will be used to construct the parent used as a ' .
                    'path parameter for the publisherConnections.batchReject request, as well ' .
                    'as the publisher connection names passed in the request body.',
                'required' => true
            ],
            [
                'name' => 'publisher_connection_ids',
                'display' => 'Publisher connection IDs',
                'description' =>
                    'One or more resource IDs for the bidders.publisherConnections resource ' .
                    'that are being rejected. Specify each value separated by a comma. These ' .
                    'will be used to construct the publisher connection names passed in the ' .
                    'publisherConnections.batchReject request body.',
                'required' => true,
                'is_array' => true
            ]
        ];
    }

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

        $pubConnIds = $values[publisher_connection_ids];
        $batchRejectRequest = new Google_Service_RealTimeBidding_BatchRejectPublisherConnectionsRequest();
        $batchRejectRequest->names = array_map(
            function ($pubConnId) use ($accountId) {
                    return "$parent/publisherConnections/$pubConnId";
            },
            $pubConnIds
        );

        print "<h2>Batch rejecting publisher connections for bidder with name: \"$parent\":";
        $result = $this->service->bidders_publisherConnections->batchReject(
            $parent,
            $batchRejectRequest
        );
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Batch Reject Publisher Connections';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2022 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.

"""Batch rejects one or more publisher connections.

A bidder will not receive bid requests from publishers associated with rejected
publisher connections.
"""


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'
_PUBLISHER_CONNECTION_NAME_TEMPLATE = 'bidders/%s/publisherConnections/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  parent = _BIDDER_NAME_TEMPLATE % account_id

  body = {
      "names": [
          _PUBLISHER_CONNECTION_NAME_TEMPLATE % (
              account_id, publisher_connection_id)
          for publisher_connection_id in args.publisher_connection_ids
      ]
  }

  print('Batch rejecting publisher connections for bidder with name: '
        f'"{parent}".')
  try:
    response = realtimebidding.bidders().publisherConnections().batchReject(
        parent=parent, 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='Batch rejects one or more publisher connections.')
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'publisher connections exist. This will be used to construct the '
            'parent used as a path parameter for the '
            'publisherConnections.batchReject request, as well as the '
            'publisher connection names passed in the request body.'))
  parser.add_argument(
      '-p', '--publisher_connection_ids', nargs='+', required=True,
      help=('One or more resource IDs for the bidders.publisherConnections '
            'resource that are being rejected. Specify each value separated by '
            'a space. These will be used to construct the publisher connection '
            'names passed in the publisherConnections.batchReject request '
            'body.'))

  args = parser.parse_args()

  main(service, args)

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2022 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.
#
# Batch rejects one or more publisher connections.
#
# A bidder will not receive bid requests from publishers associated with
# rejected publisher connections.

require 'optparse'

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


def batch_reject_publisher_connections(realtimebidding, options)
  account_id = options[:account_id]
  parent = "bidders/#{account_id}"
  publisher_connection_names = options[:publisher_connection_ids].map{
      |publisher_connection_id| "bidders/#{account_id}/publisherConnections/#{publisher_connection_id}"}

  puts "Batch rejecting publisher connections for bidder with name: '#{parent}'"

  body = Google::Apis::RealtimebiddingV1::BatchRejectPublisherConnectionsRequest.new(
    names: publisher_connection_names
  )

  response = realtimebidding.batch_reject_publisher_connections(parent, body)

  unless response.publisher_connections.nil?
    response.publisher_connections.each do |publisher_connection|
      print_publisher_connection(publisher_connection)
    end
  end
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 publisher connections exist. This will be used to '\
      'construct the parent used as a path parameter for the publisherConnections.batchReject request, as well as '\
      'the publisher connection names passed in the request body.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'publisher_connection_ids',
      'One or more resource IDs for the bidders.publisherConnections resource that are being rejected. Specify each '\
      'value separated by a comma. These will be used to construct the publisher connection names passed in the '\
      'publisherConnections.batchReject request body.',
      type: Array, short_alias: 'p', required: true, default_value: nil
    ),
  ]

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

  begin
    batch_reject_publisher_connections(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