新增及移除使用者

您可以使用下列方法,在 Client 下新增及移除個別 ClientUser

新增使用者

您可以使用 buyers.clients.users.create 方法,邀請新使用者代表客戶存取授權買方 UI。

建立 ClientUser 時,其 state 會設為 INVITED,Google 會傳送以下邀請函至您提供的電子郵件地址:

使用者必須點選「接受邀請」,才能取得 Authorized Buyers 市集 UI。您必須先登入 ,存取 Authorized Buyers 市集使用者介面的 Google 帳戶。

以下範例說明如何利用ClientUser create 方法。

REST

要求

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

{
 "email": "james@luxurymarscruises.mars"
}

回應

{
 "name": "buyers/12345678/clients/873721984/users/4683251",
 "state": "INVITED",
 "email": "james@luxurymarscruises.mars"
}

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.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.Users
{
    /// <summary>
    /// Creates a client user for the given client.
    ///
    /// When a client user is created, the specified email address will receive an email to confirm
    /// access to the Authorized Buyers UI. It will remain in the "INVITED" state and be unable to
    /// access the UI until the specified email has approved of the change.
    /// </summary>
    public class CreateClientUsers : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example creates a client user for the given client.";
        }

        /// <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;
            string email = null;

            OptionSet options = new OptionSet {
                "Creates a client user for the given client.",
                {
                    "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 users.create request."),
                    a => accountId = a
                },
                {
                    "c|client_id=",
                    ("[Required] The resource ID of the clients resource under which the client " +
                     "user is to be created. This will be used to construct the name used as a " +
                     "path parameter for the users.create request."),
                    c => clientId = c
                },
                {
                    "e|email=",
                    ("The client user's email address that has to be unique across all client " +
                     "users for a given client. By default, this will be set to a randomly " +
                     "generated email for demonstration purposes."),
                    e => email = e
                },
            };

            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["client_id"] = clientId;

            Random rng = new Random();

            parsedArgs["email"] = email ?? String.Format(
                "testemail{0}@test.com",
                rng.Next(10000000, 99999999));

            // 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 parent = $"buyers/{accountId}/clients/{clientId}";

            ClientUser newClientUser = new ClientUser()
            {
                Email = (string) parsedArgs["email"]
            };

            BuyersResource.ClientsResource.UsersResource.CreateRequest request =
                mkService.Buyers.Clients.Users.Create(newClientUser, parent);
            ClientUser response = null;

            Console.WriteLine("Creating client user for client: {0}", parent);

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

            Utilities.PrintClientUser(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.marketplace.v1.buyers.clients.users;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ClientUser;
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;
import org.apache.commons.lang3.RandomUtils;

/**
 * Creates a client user for the given client.
 *
 * <p>When a client user is created, the specified email address will receive an email to confirm
 * access to the Authorized Buyers UI. It will remain in the "INVITED" state and be unable to access
 * the UI until the specified email has approved of the change.
 */
public class CreateClientUsers {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Long clientId = parsedArgs.getLong("client_id");

    String parentClientName = String.format("buyers/%d/clients/%d", accountId, clientId);

    ClientUser newClientUser = new ClientUser();
    newClientUser.setEmail(parsedArgs.getString("email"));

    ClientUser clientUser = null;
    try {
      clientUser =
          marketplaceClient
              .buyers()
              .clients()
              .users()
              .create(parentClientName, newClientUser)
              .execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response:%n%s", ex);
      System.exit(1);
    }

    System.out.printf("Created client user for client with name \"%s\":%n", parentClientName);
    Utils.printClientUser(clientUser);
  }

  public static void main(String[] args) {
    RandomUtils rng = new RandomUtils();

    ArgumentParser parser =
        ArgumentParsers.newFor("CreateClientUsers")
            .build()
            .defaultHelp(true)
            .description(("Creates a client user for the given buyer and client ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the client user is to be created."
                + " This will be used to construct the name used as a path parameter for the"
                + " users.create request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-c", "--client_id")
        .help(
            "The resource ID of the buyers.clients resource under which the client user is to be"
                + " created. This will be used to construct the name used as a path parameter for"
                + " the users.create request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-e", "--email")
        .help(
            "The client user's email address that has to be unique across all client users for "
                + "a given client. By default, this will be set to a randomly generated email for "
                + "demonstration purposes.")
        .type(String.class)
        .setDefault(String.format("testemail%s@test.com", rng.nextInt(10000000, 99999999)));

    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.

"""Creates a client user for the given buyer account ID and client ID.

When a client user is created, the specified email address will receive an
email to confirm access to the Authorized Buyers UI. It will remain in the
"INVITED" state and be unable to access the UI until the specified email has
approved of the change.
"""


import argparse
import os
import pprint
import random
import sys

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

from googleapiclient.errors import HttpError

import util


_CLIENT_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_name = _CLIENT_NAME_TEMPLATE % (args.account_id, args.client_id)

  client_user = {
      'email': args.email
  }

  print(f'Creating client user for client with name "{client_name}":')
  try:
    # Construct and execute the request.
    response = (marketplace.buyers().clients().users().create(
        parent=client_name, body=client_user).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=('Create a client user 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 user is to be created.'))
  parser.add_argument(
      '-c', '--client_id', default=DEFAULT_CLIENT_RESOURCE_ID,
      help=('The resource ID of the clients resource under which the '
            'client user is to be created.'))
  # Optional fields.
  parser.add_argument(
      '-e', '--email',
      default=f'testemail{random.randint(10000000, 99999999)}@test.com',
      help=('The client user\'s email address that has to be unique across all '
            'client users for a given client. By default, this will be set to '
            'a randomly generated email for demonstration purposes.'))

  main(service, parser.parse_args())

移除使用者

您可以使用 buyers.clients.users.delete 方法移除 ClientUser

舉例來說,您可以使用 delete 永久撤銷個別使用者對特定客戶的授權買方市集使用者介面存取權。

移除 ClientUser 後,您必須建立新的 ClientUser,且使用者必須接受新的邀請,才能重新取得 Authorized Buyers 市集使用者介面的存取權。

以下範例示範如何使用ClientUser delete 方法。

REST

要求

DELETE https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients/873721984/users/4573638?alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

回應

{}

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.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.Users
{
    /// <summary>
    /// Deletes client user for the given buyer, client, and user IDs.
    /// </summary>
    public class DeleteClientUsers : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

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

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

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

            string accountId = null;
            string clientId = null;
            string userId = null;


            OptionSet options = new OptionSet {
                "Delete a client user with the given buyer, client, and user IDs.",
                {
                    "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 parent " +
                     "client was created. This will be used to construct the name used as a path " +
                     "parameter for the users.delete request."),
                    a => accountId = a
                },
                {
                    "c|client_id=",
                    ("[Required] The resource ID of the buyers.clients resource for which the " +
                     "client user was created. This will be used to construct the name used as " +
                     "a path parameter for the users.delete request."),
                    c => clientId = c
                },
                {
                    "u|user_id=",
                    ("[Required] The resource ID of the buyers.clients.users resource for which " +
                     "the client user was created. This will be used to construct the name used " +
                     "as a path parameter for the users.delete request."),
                    u => userId = u
                },
            };

            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;
            parsedArgs["user_id"] = userId;
            // 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 userId = (string) parsedArgs["user_id"];
            string name = $"buyers/{accountId}/clients/{clientId}/users/{userId}";

            BuyersResource.ClientsResource.UsersResource.DeleteRequest request =
                mkService.Buyers.Clients.Users.Delete(name);

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

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

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.marketplace.v1.buyers.clients.users;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
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 delete a client user for the given buyer, client, and user IDs.
 */
public class DeleteClientUsers {

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

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

    System.out.printf("Deleted client user with name \"%s\":%n", name);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("DeactivateClientUsers")
            .build()
            .defaultHelp(true)
            .description(("Delete a client user with the given buyer, client, and user ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the parent client was created. "
                + "This will be used to construct the name used as a path parameter for the "
                + "users.delete request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-c", "--client_id")
        .help(
            "The resource ID of the buyers.clients resource under which the client user was"
                + " created. This will be used to construct the name used as a path parameter for"
                + " the users.delete request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-u", "--client_user_id")
        .help(
            "The resource ID of the buyers.clients.users resource that is being deleted. "
                + "This will be used to construct the name used as a path parameter for the "
                + "users.delete 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.

"""Deletes a user with the given account, client, and user ID.

Note that this is intended to completely disassociate a given client user from a
client. As a result, the email associated with the client user will lose access
to the Authorized Buyers UI once it is deleted. To restore access, create and
activate a new client user using the same email address.
"""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_CLIENT_USERS_NAME_TEMPLATE = 'buyers/%s/clients/%s/users/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_CLIENT_RESOURCE_ID = 'ENTER_CLIENT_RESOURCE_ID_HERE'
DEFAULT_CLIENT_USER_RESOURCE_ID = 'ENTER_CLIENT_USER_RESOURCE_ID_HERE'


def main(marketplace, args):
  client_user_name = _CLIENT_USERS_NAME_TEMPLATE % (
      args.account_id, args.client_id, args.client_user_id)

  print(f'Deleting client user with name "{client_user_name}".')
  try:
    # Construct and execute the request.
    response = marketplace.buyers().clients().users().delete(
        name=client_user_name).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)


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=('Delete a client user for the given buyer account, client, '
                   'and client user 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 '
            'user was created. This will be used to construct the name used as '
            'a path parameter for the users.delete request.'))
  parser.add_argument(
      '-c', '--client_id', default=DEFAULT_CLIENT_RESOURCE_ID,
      help=('The resource ID of the buyers.clients resource under which the '
            'client user was created. This will be used to construct the name '
            'used as a path parameter for the users.delete request.'))
  parser.add_argument(
      '-u', '--client_user_id', default=DEFAULT_CLIENT_USER_RESOURCE_ID,
      help=('The resource ID of the buyers.clients.users resource for which '
            'the client user was created. This will be used to construct the '
            'name used as a path parameter for the users.delete request.'))

  main(service, parser.parse_args())