创建客户端
您可以使用 buyers.clients.create
方法创建一个代表您的某个客户的 Client
。
以下是您可以使用 Client
资源执行的操作:
- 在与发布商协商时提及客户。
- 将客户端订阅竞价包。
- 管理客户对 Authorized Buyers 市场界面的访问权限。
以下示例演示了如何使用Client
create
方法。
请求
POST https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients?alt=json
Authorization: BearerACCESS_TOKEN
Content-Type: application/json
{
"displayName": "Demo Approver 2",
"role": "CLIENT_DEAL_APPROVER",
"sellerVisible": false
}
响应
{
"name": "buyers/12345678/clients/873721984",
"role": "CLIENT_DEAL_APPROVER",
"state": "ACTIVE",
"displayName": "Demo Approver 2"
}
/* 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>
/// Creates a client for the given buyer account ID.
/// </summary>
public class CreateClients : ExampleBase
{
private AuthorizedBuyersMarketplaceService mkService;
/// <summary>
/// Constructor.
/// </summary>
public CreateClients()
{
mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get => "This code example creates a client for the given buyer account ID.";
}
/// <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 displayName = null;
string partnerClientId = null;
string role = null;
string sellerVisible = null;
OptionSet options = new OptionSet {
"Creates a client for the given buyer account 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 is to be created. This will be used to construct the name used as " +
"a path parameter for the clients.create request."),
a => accountId = a
},
{
"d|display_name=",
("The display name shown to publishers. Must be unique for clients without " +
"partnerClientId specified. The maximum length allowed is 255 characters. " +
"By default, this sample will specify a generated name."),
d => displayName = d
},
{
"p|partner_client_id=",
("Arbitrary unique identifier provided by the buyer. This field can be used " +
"to associate a client with an identifier in the namespace of the buyer. If " +
"present, it must be unique across all the clients. By default, this sample " +
"will not specify a partnerClientId."),
p => partnerClientId = p
},
{
"r|role=",
("The role assigned to the client, which determines its permissions. By " +
"default, this will be set to CLIENT_DEAL_VIEWER. For more details on how " +
"to interpret the different roles, see:" +
"https://developers.google.com/authorized-buyers/apis/marketplace/" +
"reference/rest/v1/buyers.clients#ClientRole"),
r => role = r
},
{
"s|seller_visible=",
("A boolean value indicating whether the client will be visible to " +
"publishers. By default, this will be set to false."),
s => sellerVisible = s
},
};
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["display_name"] = displayName ?? String.Format(
"Test_Client_{0}",
System.Guid.NewGuid());
parsedArgs["partner_client_id"] = partnerClientId;
parsedArgs["role"] = role ?? "CLIENT_DEAL_VIEWER";
if (sellerVisible != null)
{
parsedArgs["seller_visible"] = Boolean.Parse(sellerVisible);
} else
{
parsedArgs["seller_visible"] = false;
}
// 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}";
Client newClient = new Client()
{
DisplayName = (string) parsedArgs["display_name"],
Role = (string) parsedArgs["role"],
SellerVisible = (Boolean) parsedArgs["seller_visible"]
};
string partnerClientId = (string) parsedArgs["partner_client_id"];
if (partnerClientId != null)
{
newClient.PartnerClientId = partnerClientId;
}
BuyersResource.ClientsResource.CreateRequest request =
mkService.Buyers.Clients.Create(newClient, parent);
Client response = null;
Console.WriteLine("Creating client for buyer: {0}", parent);
try
{
response = request.Execute();
}
catch (Exception exception)
{
throw new ApplicationException(
$"Real-time Bidding 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.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
/** Creates a client for the given buyer account ID. */
public class CreateClients {
public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
Long accountId = parsedArgs.getLong("account_id");
String parentBuyerName = String.format("buyers/%d", accountId);
Client newClient = new Client();
newClient.setDisplayName(parsedArgs.getString("display_name"));
newClient.setRole(parsedArgs.getString("role"));
newClient.setSellerVisible(parsedArgs.getBoolean("seller_visible"));
String partnerClientId = parsedArgs.getString("partner_client_id");
if (partnerClientId != null) {
newClient.setPartnerClientId(partnerClientId);
}
Client client = null;
try {
client = marketplaceClient.buyers().clients().create(parentBuyerName, newClient).execute();
} catch (IOException ex) {
System.out.printf("Marketplace API returned error response:%n%s", ex);
System.exit(1);
}
System.out.printf("Created client for buyer Account ID '%d':%n", accountId);
Utils.printClient(client);
}
public static void main(String[] args) {
ArgumentParser parser =
ArgumentParsers.newFor("CreateClients")
.build()
.defaultHelp(true)
.description(("Creates a client for the given buyer account ID."));
parser
.addArgument("-a", "--account_id")
.help("The resource ID of the buyers resource under which the client is to be created. ")
.required(true)
.type(Long.class);
parser
.addArgument("-d", "--display_name")
.help(
"Display name shown to publishers. Must be unique for clients without "
+ "partnerClientId specified. Maximum length of 255 characters is allowed. By "
+ "default, this sample will specify a generated name.")
.type(String.class)
.setDefault(String.format("TEST_CLIENT_%s", UUID.randomUUID()));
parser
.addArgument("-p", "--partner_client_id")
.help(
"Arbitrary unique identifier provided by the buyer. This field can be used to associate"
+ " a client with an identifier in the namespace of the buyer. If present, it must"
+ " be unique across all the clients. By default, this sample will not specify a"
+ "partnerClientId.")
.type(String.class);
parser
.addArgument("-r", "--role")
.help(
"The role assigned to the client, which determines its permissions. By default, this"
+ " will be set to CLIENT_DEAL_VIEWER. For more details on how to interpret the"
+ " different roles, see: "
+ "https://developers.google.com/authorized-buyers/apis/marketplace/reference/rest/v1/buyers.clients#ClientRole")
.type(String.class)
.setDefault("CLIENT_DEAL_VIEWER");
parser
.addArgument("-s", "--seller_visible")
.help(
"Whether the client will be visible to publishers. By default, this sample will "
+ "set this to false.")
.type(Boolean.class)
.setDefault(false);
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.
"""Creates a client for the given buyer account ID."""
import argparse
import os
import pprint
import sys
import uuid
sys.path.insert(0, os.path.abspath('../../..'))
from googleapiclient.errors import HttpError
import util
_BUYER_NAME_TEMPLATE = 'buyers/%s'
DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
def main(marketplace, args):
account_id = args.account_id
client = {
'displayName': args.display_name,
'role': args.role,
'sellerVisible': args.seller_visible
}
partner_client_id = args.partner_client_id
if partner_client_id:
client['partnerClientId'] = partner_client_id
print(f'Creating client for buyer account ID "{account_id}":')
try:
# Construct and execute the request.
response = (marketplace.buyers().clients().create(
parent=_BUYER_NAME_TEMPLATE % account_id, body=client).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)
def valid_role(value):
valid_roles = (
'CLIENT_DEAL_VIEWER', 'CLIENT_DEAL_VIEWER',
'CLIENT_DEAL_NEGOTIATOR', 'CLIENT_DEAL_APPROVER')
upper_input = value.upper()
if upper_input in valid_roles:
return upper_input
else:
raise ValueError(
f'Invalid role specified. Must be one of: {valid_roles}')
def valid_bool(value):
upper_input = value.upper()
if upper_input == 'TRUE':
return True
elif upper_input == 'FALSE':
return False
else:
raise ValueError(
'Invalid value specified. Must be a boolean input.')
parser = argparse.ArgumentParser(
description='Creates a client for the given buyer account 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 is to be created.'))
# Optional fields.
parser.add_argument(
'-n', '--display_name', default='Test Client #%s' % uuid.uuid4(),
help=('The display name shown to publishers. Must be unique for '
'clients without partnerClientId specified. The maximum length '
'allowed is 255 characters. By default, this sample will '
'specify a generated name.'))
parser.add_argument(
'-p', '--partner_client_id', default=None,
help=('Arbitrary unique identifier provided by the buyer. This field '
'can be used to associate a client with an identifier in the '
'namespace of the buyer. If present, it must be unique across '
'all the clients. Be default, this sample will not specify a '
'partnerClientId.'))
parser.add_argument(
'-r', '--role', default='CLIENT_DEAL_VIEWER', type=valid_role,
help=('The role assigned to the client, which determines its '
'permissions. By default, this will be set to '
'CLIENT_DEAL_VIEWER. For more details on how to interpret the '
'different roles, see: https://developers.google.com/'
'authorized-buyers/apis/marketplace/reference/rest/v1/'
'buyers.clients#ClientRole'))
parser.add_argument(
'-s', '--seller_visible', default=False, type=valid_bool,
help=('Whether the client will be visible to publishers. By default, '
'this sample will set this to False.'))
main(service, parser.parse_args())
修补客户端
您可以使用 buyers.clients.patch
方法更新现有 Client
。例如,您可以使用 patch
来
更新 displayName
。以下示例演示了如何更新
使用 patch
方法的 Client
。
请求
PATCH https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/clients/873721984?updateMask=displayName&alt=json
Authorization: BearerACCESS_TOKEN
Content-Type: application/json
{
"displayName": "Test Client #6a1849ca-f8ed-4ead-a3b9-75ef117b043f"
}
响应
{
"name": "buyers/12345678/clients/873721984",
"role": "CLIENT_DEAL_APPROVER",
"state": "ACTIVE",
"displayName": "Test Client #6a1849ca-f8ed-4ead-a3b9-75ef117b043f"
}
/* 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>
/// Patches a client with the specified name.
/// </summary>
public class PatchClients : ExampleBase
{
private AuthorizedBuyersMarketplaceService mkService;
/// <summary>
/// Constructor.
/// </summary>
public PatchClients()
{
mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get => "This code example patches a client having the specified name.";
}
/// <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 displayName = null;
OptionSet options = new OptionSet {
"Patches the specified 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 clients.patch 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.patch request."),
c => clientId = c
},
{
"d|display_name=",
("The display name shown to publishers. Must be unique for clients without " +
"partnerClientId specified. The maximum length allowed is 255 characters. " +
"By default, this sample will specify a generated name that will be used " +
"to patch the client's existing display name."),
d => displayName = d
}
};
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;
parsedArgs["display_name"] = displayName ?? $"Test-Client-{System.Guid.NewGuid()}";
// 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)
{
var accountId = (string) parsedArgs["account_id"];
var clientId = (string) parsedArgs["client_id"];
var name = $"buyers/{accountId}/clients/{clientId}";
Client clientPatch = new Client()
{
DisplayName = (string) parsedArgs["display_name"]
};
BuyersResource.ClientsResource.PatchRequest request =
mkService.Buyers.Clients.Patch(clientPatch, name);
// Configure the update mask such that only the displayName is updated. If not set, the
// patch method would overwrite all other writable fields with a null value.
request.UpdateMask = "displayName";
Client response = null;
Console.WriteLine("Patching client with name: {0}", name);
try
{
response = request.Execute();
}
catch (Exception exception)
{
throw new ApplicationException(
$"Real-time Bidding 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.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;
/** Patches a client with the specified name. */
public class PatchClients {
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 update = new Client();
update.setDisplayName(parsedArgs.getString("display_name"));
String uMask = "displayName";
Client client = null;
try {
client =
marketplaceClient.buyers().clients().patch(name, update).setUpdateMask(uMask).execute();
} catch (IOException ex) {
System.out.printf("Marketplace API returned error response:%n%s", ex);
System.exit(1);
}
System.out.printf("Patched client for buyer Account ID '%d':%n", accountId);
Utils.printClient(client);
}
public static void main(String[] args) {
ArgumentParser parser =
ArgumentParsers.newFor("PatchClients")
.build()
.defaultHelp(true)
.description(("Patches 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.")
.required(true)
.type(Long.class);
parser
.addArgument("-c", "--client_id")
.help("The resource ID of the buyers.clients resource under which the client was created.")
.required(true)
.type(Long.class);
parser
.addArgument("-d", "--display_name")
.help(
"Display name shown to publishers. Must be unique for clients without partnerClientId"
+ " specified. Maximum length of 255 characters is allowed. By default, this sample"
+ " will specify a generated name that will be used to patch the client's existing"
+ " display name.")
.type(String.class)
.setDefault(String.format("TEST_CLIENT_%s", UUID.randomUUID()));
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.
"""Patches a client for the given account ID and client ID."""
import argparse
import os
import pprint
import sys
import uuid
sys.path.insert(0, os.path.abspath('../../..'))
from googleapiclient.errors import HttpError
import util
_CLIENT_NAME_TEMPLATE = 'buyers/%s/clients/%s'
DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
def main(marketplace, args):
account_id = args.account_id
client_id = args.client_id
client = {
'displayName': args.display_name
}
print(f'Patching client {client_id} for buyer account ID "{account_id}":')
try:
# Construct and execute the request.
response = marketplace.buyers().clients().patch(
name=_CLIENT_NAME_TEMPLATE % (account_id, client_id), body=client,
updateMask='displayName').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=(
'Patches 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.'))
parser.add_argument(
'-c', '--client_id', default=DEFAULT_BUYER_RESOURCE_ID,
help=('The resource ID of the buyers.clients resource under which the '
'client was created. This will be used to construct the name '
'used as a path parameter for the buyers.clients.patch request.')
)
# Optional fields.
parser.add_argument(
'-n', '--display_name', default='Test Client #%s' % uuid.uuid4(),
help=('The display name shown to publishers. Must be unique for '
'clients without partnerClientId specified. The maximum length '
'allowed is 255 characters. By default, this sample will '
'specify a generated name that will be used to patch the '
'client\'s existing display name.'))
main(service, parser.parse_args())