Управлять активностью клиентов

Вы можете использовать следующие методы для изменения state Client . state устанавливается в ACTIVE для новых Client ресурсов автоматически после того, как клиент принимает приглашение.

Вы можете установить state INACTIVE для данного Client , чтобы лишить его доступа к пользовательскому интерфейсу торговой площадки авторизованных покупателей.

Деактивировать

Вы можете деактивировать активного Client с помощью метода buyers.clients.deactivate .

Например, вы можете использовать этот метод, если хотите отключить доступ клиента к пользовательскому интерфейсу торговой площадки авторизованных покупателей.

Когда вы деактивируете Client , он теряет доступ к пользовательскому интерфейсу. Вы по-прежнему можете просматривать и обсуждать предложения от имени деактивированных клиентов.

В следующем примере показано, как можно деактивировать Client с помощью метода deactivate .

ОТДЫХ

Запрос

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

Ответ

{
 "name": "buyers/12345678/clients/837492105",
 "role": "CLIENT_DEAL_VIEWER",
 "state": "INACTIVE",
 "displayName": "Demo Viewer 1",
 "sellerVisible": true
}

С#

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

using Google.Apis.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
{
    /// s<ummary<>/span>
    /// Deactivates client for the given buyer account ID and client ID.
    /// /<summary
>    public class DeactivateClients : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public DeactivateClients()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example deactivates a specific client for a buyer account.;"
        }

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

            string accountId = null;
            string clientId = null;

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

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

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

            return parsedArgs;
        }

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

            BuyersResource.ClientsResource.DeactivateRequest request =
                mkService.Buyers.Clients.Deactivate(new DeactivateClientRequest(), name);
            Client response = null;

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

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

            Utilities.PrintClient(response);
        }
    }
}

Ява

/*
 * 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.DeactivateClientRequest;
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 deactivate a client for the given buyer account ID and client ID.
 */
public class DeactivateClients {

  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()
              .deactivate(name, new DeactivateClientRequest())
              .execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response:%n%s", ex);
      System.exit(1);
    }

    System.out.printf(
        "Deactivated 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("DeactivateClients")
            .build()
            .defaultHelp(true)
            .description(("Deactivate 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.deactivate 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.deactivate 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);
  }
}

Питон

#!/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.

"""Deactivates client with the given with the given account ID and client ID."""


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'Deactivate client "{client_id}" for account "{account_id}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().clients().deactivate(
            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=('Deactivate 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.deactivate '
              '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.deactivate '
              'request.'))

    main(service, parser.parse_args())

Повторно активировать

Вы можете повторно активировать неактивного Client с помощью метода buyers.clients.activate .

Например, вы можете использовать этот метод, если хотите восстановить доступ клиента к пользовательскому интерфейсу торговой площадки авторизованных покупателей после его деактивации.

В следующем примере показано, как можно активировать Client с помощью метода activate .

ОТДЫХ

Запрос

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

Ответ

{
 "name": "buyers/12345678/clients/837492105",
 "role": "CLIENT_DEAL_VIEWER",
 "state": "ACTIVE",
 "displayName": "Demo Viewer 1",
 "sellerVisible": true
}

С#

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

using Google.Apis.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
{
    /// s<ummary<>/span>
    /// Activates client for the given buyer account ID and client ID.
    /// /<summary
>    public class ActivateClients : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// s<ummary<>/span>
        /// Constructor.
        /// /<summary
>        public ActivateClients()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// s<ummary<>/span>
        /// Returns a description about the code example.
        /// /<summary
>        public override string Description
        {
            get = >T"his code example activates a specific client for a buyer account.;"
        }

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

            string accountId = null;
            string clientId = null;

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

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

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

            return parsedArgs;
        }

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

            BuyersResource.ClientsResource.ActivateRequest request =
                mkService.Buyers.Clients.Activate(new ActivateClientRequest(), name);
            Client response = null;

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

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

            Utilities.PrintClient(response);
        }
    }
}

Ява

/*
 * 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.ActivateClientRequest;
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 activate a client for the given buyer account ID and client ID.
 */
public class ActivateClients {

  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()
              .activate(name, new ActivateClientRequest())
              .execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response:%n%s", ex);
      System.exit(1);
    }

    System.out.printf(
        "Activated 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("ActivateClients")
            .build()
            .defaultHelp(true)
            .description(("Activate 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.activate 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.activate 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);
  }
}

Питон

#!/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.

"""Activates client with the given with the given account ID and client ID."""


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'Activate client "{client_id}" for account "{account_id}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().clients().activate(
            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=('Activate 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.activate 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.activate request.'
              ))

    main(service, parser.parse_args())