ดูลูกค้า

คุณสามารถใช้วิธีต่อไปนี้เพื่อดูไฟล์ clients ในบัญชีของคุณ

ดูลูกค้าแต่ละราย

คุณสามารถใช้ buyers.clients.get เพื่อเรียกข้อมูล Client และดูระดับการเข้าถึง UI ของมาร์เก็ตเพลสของ Authorized Buyers

เช่น เมื่อเจรจาข้อเสนอกับผู้เผยแพร่โฆษณา คุณจะ ใช้ get เพื่อดูข้อมูลเกี่ยวกับ Client ที่ระบุไว้ในข้อเสนอได้

ตัวอย่างต่อไปนี้แสดงวิธีเรียกข้อมูล Client แต่ละรายการ ด้วยเมธอด get

REST

ส่งคำขอ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients/984287215?alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

คำตอบ

{
 "name": "buyers/12345678/clients/984287215",
 "role": "CLIENT_DEAL_APPROVER",
 "state": "ACTIVE",
 "displayName": "Demo Approver 1"
}

C#

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

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.Clients
{
    /// <summary>
    /// Gets a single client for the given buyer account ID and client ID.
    /// </summary>
    public class GetClients : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetClients()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example gets a specific client for a buyer account.";
        }

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

            string accountId = null;
            string clientId = null;

            OptionSet options = new OptionSet {
                "Get a client for a given buyer account ID and client ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the client " +
                     "was created. This will be used to construct the name used as a path " +
                     "parameter for the clients.get request."),
                    a => accountId = a
                },
                {
                    "c|client_id=",
                    ("[Required] The resource ID of the buyers.clients resource for which the " +
                     "client was created. This will be used to construct the name used as a " +
                     "path parameter for the clients.get request."),
                    c => clientId = c
                },
            };

            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 optional arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["client_id"] = clientId;
            // 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 clientId = (string) parsedArgs["client_id"];
            string name = $"buyers/{accountId}/clients/{clientId}";

            BuyersResource.ClientsResource.GetRequest request =
                mkService.Buyers.Clients.Get(name);
            Client response = null;

            Console.WriteLine("Getting client with name: {0}", name);

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

            Utilities.PrintClient(response);
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.clients;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.Client;
import com.google.api.services.samples.authorizedbuyers.marketplace.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 client for the given buyer account ID and client ID.
 */
public class GetClients {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Long clientId = parsedArgs.getLong("client_id");
    String name = String.format("buyers/%d/clients/%d", accountId, clientId);

    Client client = null;

    try {
      client = marketplaceClient.buyers().clients().get(name).execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response:%n%s", ex);
      System.exit(1);
    }

    System.out.printf(
        "Found Client with ID \"%s\" for buyer account ID '%d':%n", clientId, accountId);
    Utils.printClient(client);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetClients")
            .build()
            .defaultHelp(true)
            .description(("Get a client for the given buyer account ID and client ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the client was created. This will"
                + " be used to construct the parent used as a path parameter for the clients.get "
                + "request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-c", "--client_id")
        .help(
            "The resource ID of the buyers.clients resource for which the client was created "
                + "This will be used to construct the name used as a path parameter for the "
                + "clients.get request.")
        .required(true)
        .type(Long.class);

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

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace 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);
    }

    execute(client, parsedArgs);
  }
}

Python

#!/usr/bin/python
#
# Copyright 2021 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 client for the given account and client IDs."""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_CLIENTS_NAME_TEMPLATE = 'buyers/%s/clients/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_CLIENT_RESOURCE_ID = 'ENTER_CLIENT_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    client_id = args.client_id

    print(f'Get client "{client_id}" for account "{account_id}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().clients().get(
            name=_CLIENTS_NAME_TEMPLATE % (account_id, client_id)).execute()
    except HttpError as e:
        print(e)
        sys.exit(1)

    pprint.pprint(response)


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

    parser = argparse.ArgumentParser(
        description=('Get a client for the given buyer account ID and client '
                     'ID.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource under which the '
              'client was created. This will be used to construct the '
              'name used as a path parameter for the clients.get request.'))
    parser.add_argument(
        '-c', '--client_id', default=DEFAULT_CLIENT_RESOURCE_ID,
        help=('The resource ID of the buyers.clients resource for which the '
              'client was created. This will be used to construct the '
              'name used as a path parameter for the clients.get request.'))

    main(service, parser.parse_args())

แสดงรายการลูกค้าหลายราย

คุณสามารถใช้ buyers.clients.list เพื่อเรียกดูข้อมูลของลูกค้าทั้งหมด หรือค้นหาลูกค้าที่เชื่อมโยงกับหนึ่งใน ลูกค้าที่ใช้ filter กับ partnerClientId

ตัวอย่างต่อไปนี้แสดงวิธีรายชื่อลูกค้าด้วย list

REST

ส่งคำขอ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients?pageSize=3&alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

คำตอบ

{
 "clients": [
   {
     "name": "buyers/12345678/clients/995152331",
     "role": "CLIENT_DEAL_NEGOTIATOR",
     "state": "ACTIVE",
     "displayName": "Demo Negotiator 1",
     "partnerClientId": "pcid-5e845421-251a-4a0c-8316-67f9b8140d3a"
   },
   {
     "name": "buyers/12345678/clients/837492105",
     "role": "CLIENT_DEAL_VIEWER",
     "state": "INACTIVE",
     "displayName": "Demo Viewer 1",
     "sellerVisible": true
   },
   {
     "name": "buyers/12345678/clients/984287215",
     "role": "CLIENT_DEAL_APPROVER",
     "state": "ACTIVE",
     "displayName": "Demo Approver 1"
   }
 ],
 "nextPageToken": "CAMQ26Xgn7nb9gIY26Xgn7nb9gI="
}

C#

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

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.Clients
{
    /// <summary>
    /// Lists clients for a given buyer account ID.
    /// </summary>
    public class ListClients : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListClients()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists all clients for a given buyer 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 filter = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List clients for the given buyer account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "clients were created. This will be used to construct the parent used as " +
                     "a path parameter for the clients.list request."),
                    a => accountId = a
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
                {
                    "f|filter=",
                    ("Query string to filter clients. If no filter is specified, all clients " +
                     "will be returned. By default, no filter will be set."),
                    f => filter = f
                },
            };

            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["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            parsedArgs["filter"] = filter;
            // 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 = $"buyers/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing clients for buyer account ""{0}""", parent);
            do
            {
                BuyersResource.ClientsResource.ListRequest request =
                    mkService.Buyers.Clients.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListClientsResponse page = null;

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

                var clients = page.Clients;
                pageToken = page.NextPageToken;

                if (clients == null)
                {
                    Console.WriteLine("No clients found for buyer account.");
                }
                else
                {
                    foreach (Client client in clients)
                    {
                        Utilities.PrintClient(client);
                    }
                }
            }
            while(pageToken != null);
        }
    }
}

Java

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

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.clients;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.Client;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListClientsResponse;
import com.google.api.services.samples.authorizedbuyers.marketplace.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 Clients for a given buyer account ID. */
public class ListClients {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBuyerName = String.format("buyers/%d", accountId);
    String pageToken = null;

    System.out.printf("Found Clients for buyer Account ID '%d':%n", accountId);

    do {
      List<Client> clients = null;

      try {
        ListClientsResponse response =
            marketplaceClient
                .buyers()
                .clients()
                .list(parentBuyerName)
                .setFilter(parsedArgs.getString("filter"))
                .setPageSize(pageSize)
                .setPageToken(pageToken)
                .execute();

        clients = response.getClients();
        pageToken = response.getNextPageToken();
      } catch (IOException ex) {
        System.out.printf("Marketplace API returned error response:%n%s", ex);
        System.exit(1);
      }
      if (clients == null) {
        System.out.println("No clients found.");
      } else {
        for (Client client : clients) {
          Utils.printClient(client);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListClients")
            .build()
            .defaultHelp(true)
            .description(("Lists clients associated with the given buyer account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the clients were created. "
                + "This will be used to construct the parent used as a path parameter for the "
                + "clients.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-f", "--filter")
        .help(
            "Query string to filter clients. If no filter is specified, all clients will be "
                + "returned. By default, no filter will be set.");
    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);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace 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);
    }

    execute(client, parsedArgs);
  }
}

Python

#!/usr/bin/python
#
# Copyright 2021 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 lists clients for the specified buyer."""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    list_filter = args.filter
    page_size = args.page_size

    page_token = None
    more_pages = True

    print(f'Listing clients for buyer account: "{account_id}".')
    while more_pages:
        try:
            # Construct and execute the request.
            response = marketplace.buyers().clients().list(
                parent=_BUYER_NAME_TEMPLATE % account_id, pageToken=page_token,
                filter=list_filter, pageSize=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.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description='Lists clients for the given buyer account.')
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource under which the clients '
              'were created. This will be used to construct the parent used '
              'as a path parameter for the clients.list request.'))
    # Optional fields.
    parser.add_argument(
        '-f', '--filter', default=None,
        help=('Query string to filter clients. If no filter is specified, all '
              'clients will be returned. By default, no filter will be set.'))
    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.'))

    main(service, parser.parse_args())