Za pomocą interfejsu Merchant API możesz tworzyć konta Merchant Center, które można połączyć z kontem zaawansowanym za pomocą accountAggregation, accountManagement lub comparisonShopping. Metoda accounts.createAndConfigure umożliwia utworzenie konta i opcjonalnie skonfigurowanie go z użytkownikami oraz połączenie go z innymi kontami za pomocą usług.
Ten przewodnik wyjaśnia, jak używać interfejsu Merchant API do tworzenia kont za pomocą accountAggregation, accountManagement lub comparisonShopping:
accountAggregation: używane przez platformy handlowe, sprzedawców oferujących produkty wielu marek, sprzedawców międzynarodowych i partnerów tworzących subkonta w ramach multikonta klientów na koncie zaawansowanym.accountManagement: używane przez agencje tworzące samodzielne konta należące do sprzedawcy.comparisonShopping: używany przez usługi porównywania cen, które tworzą konta w Europejskim Obszarze Gospodarczym i krajach, w których dostępna jest usługa porównywania cen.
Gdy używasz accounts.createAndConfigure, musisz połączyć nowe konto z dostawcą, podając co najmniej 1 z tych wartości: accountAggregation, accountManagement lub comparisonShopping w polu service. Możesz określić accountAggregation i comparisonShopping w tym samym żądaniu, ale nie możesz połączyć accountManagement z accountAggregation ani z comparisonShopping. Jeśli podasz accountManagement, dodaj do nowego konta co najmniej 1 użytkownika, korzystając z pola user lub users.
Wymagania wstępne
Zanim utworzysz konta za pomocą interfejsu Merchant API, upewnij się, że spełniasz te wymagania w zależności od usług, z których korzystasz:
- Dostęp administratora: aby połączyć nowe konto za pomocą
accountManagement,comparisonShoppinglubaccountAggregation, musisz mieć dostęp administratora do konta dostawcy. - Konto zaawansowane: jeśli korzystasz z
accountAggregation, Twoje konto dostawcy musi być kontem zaawansowanym skonfigurowanym do agregacji kont. Jeśli jesteś usługodawcą i chcesz skonfigurować konto zaawansowane, skontaktuj się z zespołem pomocy, aby uzyskać pomoc w konfiguracji.
Utwórz konto (za pomocą zarządzania kontem lub porównywania cen)
Aby utworzyć nowe konto, zadzwoń pod numer accounts.createAndConfigure.
Jest to zalecane podejście dla partnerów, którzy pomagają sprzedawcom zarządzać ich kontami, ponieważ pozwala sprzedawcom zachować pełną kontrolę nad kontem i jego własność, a jednocześnie przyznać partnerom określone uprawnienia.
W treści żądania:
- W polu
accountpodaj szczegóły konta, które chcesz utworzyć. - W polu
accountNamenie używaj powtarzających się ani niepotrzebnych znaków interpunkcyjnych, wielkich liter, podkreśleń, samych wielkich liter, emotikonów ani symboli niealfanumerycznych, takich jak/czy_. Unikaj sufiksów związanych z określeniem firmy (takich jak „Inc.” lub „GmbH”), tekstu promocyjnego, danych osobowych i nieodpowiedniego języka. Użyj krótkiej, jasnej i profesjonalnej nazwy. Więcej informacji znajdziesz w artykule o dodawaniu nazwy firmy. - Jeśli używasz
accountManagement, w poluuserpodaj co najmniej 1 użytkownika, który będzie miał dostęp do konta. - W polu
serviceokreśl usługi, które chcesz udostępnić temu kontu, na przykładaccountManagement, i ustawproviderna nazwę zasobu swojego konta (na przykładproviders/{YOUR_ACCOUNT_ID}). Listę dostępnych usług, takich jakproductsManagementlubcampaignsManagement, znajdziesz w artykule Zarządzanie relacjami między kontami.
Poniżej znajduje się przykładowe żądanie utworzenia konta o nazwie „merchantStore” i połączenia go z kontem {YOUR_ACCOUNT_ID} w celu zarządzania kontem i produktami:
POST https://merchantapi.googleapis.com/accounts/v1/accounts:createAndConfigure
{
"account": {
"accountName": "merchantStore",
"adultContent": false,
"timeZone": {
"id": "America/New_York"
},
"languageCode": "en-US"
},
"user": [
{
"userId": "test@example.com",
"user": {
"accessRights": ["ADMIN"]
}
}
],
"service": [
{
"accountManagement": {},
"provider": "providers/{YOUR_ACCOUNT_ID}"
},
{
"productsManagement": {},
"provider": "providers/{YOUR_ACCOUNT_ID}"
}
]
}
Prawidłowe wywołanie powoduje utworzenie nowego konta i połączenie go z Twoim kontem w przypadku określonych usług. Jeśli podczas tworzenia określisz usługi accountManagement, accountAggregation lub comparisonShopping, zostaną one automatycznie zatwierdzone, a stan połączenia będzie miał wartość ESTABLISHED. Inne linki do usług mogą być w stanie PENDING, dopóki nie zostaną zaakceptowane przez utworzone konto. Treść odpowiedzi zawiera nowo utworzony zasób Account.
Poniższy przykład pokazuje, jak użyć accounts.createAndConfigure do utworzenia i skonfigurowania konta:
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccessRight;
import com.google.shopping.merchant.accounts.v1.Account;
import com.google.shopping.merchant.accounts.v1.AccountManagement;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest;
import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest.AddAccountService;
import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest.AddUser;
import com.google.shopping.merchant.accounts.v1.ProductsManagement;
import com.google.shopping.merchant.accounts.v1.User;
import com.google.type.TimeZone;
import java.util.List;
import shopping.merchant.samples.utils.Authenticator;
/**
* This class demonstrates how to create a new Merchant Center account and configure it with various
* services.
*/
public class CreateAndConfigureAccountSample {
public static void createAndConfigureAccount(
long providerId, String newAccountName, String userEmail) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
AccountsServiceSettings accountsServiceSettings =
AccountsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Calls the API and catches and prints any network failures/errors.
try (AccountsServiceClient accountsServiceClient =
AccountsServiceClient.create(accountsServiceSettings)) {
// The account to be created.
Account account =
Account.newBuilder()
.setAccountName(newAccountName)
.setTimeZone(TimeZone.newBuilder().setId("Europe/Zurich").build())
.setLanguageCode("en-US")
.build();
// The services to be added to the new account.
// This sample shows how to configure a new account with account management and
// product management.
// For more information about the different services, see:
// https://developers.google.com/merchant/api/guides/accounts/services
AddAccountService accountManagementService =
AddAccountService.newBuilder()
.setProvider("accounts/" + providerId)
.setExternalAccountId("external_account_id")
.setAccountManagement(AccountManagement.newBuilder().build())
.build();
// This part is optional. You can also omit this and link the account later.
AddAccountService productsManagementService =
AddAccountService.newBuilder()
.setProvider("accounts/" + providerId)
.setExternalAccountId("external_account_id")
.setProductsManagement(ProductsManagement.newBuilder().build())
.build();
// For sub-account creation, use the AccountAggregation service. For an example on how to do
// this, see the `CreateSubAccount` sample.
// The user to be added to the new account.
// This part is optional.
AddUser user =
AddUser.newBuilder()
.setUserId(userEmail)
.setUser(User.newBuilder().addAccessRights(AccessRight.STANDARD).build())
.build();
CreateAndConfigureAccountRequest request =
CreateAndConfigureAccountRequest.newBuilder()
.setAccount(account)
.addAllService(List.of(accountManagementService, productsManagementService))
.addUser(user)
.build();
System.out.println("Sending Create and Configure Account request:");
Account response = accountsServiceClient.createAndConfigureAccount(request);
System.out.println("Created Account below");
System.out.println(response);
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws Exception {
// This is the provider ID of the e-commerce platform.
long providerId = 123L;
// This is the name of the new account to be created.
String newAccountName = "MyNewShop";
// This is the email of a user to be added to the new account.
String userEmail = "test-user@gmail.com";
createAndConfigureAccount(providerId, newAccountName, userEmail);
}
}
Po utworzeniu takiego konta musisz je skonfigurować, wykonując takie czynności jak zaakceptowanie Warunków korzystania z usługi , skonfigurowanie informacji o firmie i zweryfikowanie witryny.
Pomiń potwierdzanie adresu e-mail podczas tworzenia konta
Podczas tworzenia konta za pomocą accounts.createAndConfigure możesz opcjonalnie pominąć e-maile weryfikacyjne dla nowych użytkowników dodanych za pomocą pola user, ustawiając verificationMailSettings.verificationMailMode na SUPPRESS_VERIFICATION_MAIL w żądaniu dotyczącym danego użytkownika. Jest to przydatne, jeśli chcesz zweryfikować użytkowników w imieniu sprzedawcy natychmiast po utworzeniu za pomocą metody users.verifySelf. Domyślnie parametr verificationMailMode ma wartość SEND_VERIFICATION_MAIL, a e-maile weryfikacyjne są wysyłane do nowych użytkowników dodanych podczas tworzenia konta.
POST https://merchantapi.googleapis.com/accounts/v1/accounts:createAndConfigure
{
"account": {
"accountName": "merchantStore",
"adultContent": false,
"timeZone": {
"id": "America/New_York"
},
"languageCode": "en-US"
},
"user": [
{
"userId": "test@example.com",
"user": {
"accessRights": ["ADMIN"]
},
"verificationMailSettings": {
"verificationMailMode": "SUPPRESS_VERIFICATION_MAIL"
}
}
],
"service": [
{
"accountManagement": {},
"provider": "providers/{YOUR_ACCOUNT_ID}"
}
]
}
Jeśli ustawisz parametr verificationMailMode na SUPPRESS_VERIFICATION_MAIL, musisz wywołać users.verifySelf dla każdego użytkownika dodanego podczas tworzenia, aby dokończyć weryfikację. To wywołanie musi zostać uwierzytelnione jako weryfikowany użytkownik (użytkownik określony w userId), na przykład za pomocą tokena OAuth od użytkownika.
Określanie aliasu podczas tworzenia konta
Możesz określić alias konta w kontekście dostawcy w CreateAndConfigureAccountRequest, używając pola setAlias. Alias może służyć do identyfikacji konta w Twoim systemie. Jeśli jesteś dostawcą usług, możesz użyć aliasu, aby pobrać konto za pomocą GET /accounts/v1/accounts/{provider}~{alias}. Alias musi być unikalny dla danego dostawcy, a w polu service żądania musisz określić usługę tego samego dostawcy. Więcej informacji o wymaganiach dotyczących aliasów znajdziesz w artykule Zarządzanie relacjami między kontami.
POST https://merchantapi.googleapis.com/accounts/v1/accounts:createAndConfigure
{
"account": {
"accountName": "merchantStore",
"adultContent": false,
"timeZone": {
"id": "America/New_York"
},
"languageCode": "en-US"
},
"service": [
{
"accountManagement": {},
"provider": "providers/{YOUR_ACCOUNT_ID}"
}
],
"setAlias": [
{
"provider": "providers/{YOUR_ACCOUNT_ID}",
"accountIdAlias": "my-merchant-alias"
}
]
}
Zalecany proces wprowadzenia
Jeśli jesteś partnerem tworzącym konto w imieniu sprzedawcy, zalecamy wykonanie tych czynności:
- Utwórz konto: wywołaj
accounts.createAndConfigure, podając dane logowania partnera, aby utworzyć nowe konto.- Ustaw
servicetak, aby zawierałaccountManagementz linkiem do identyfikatora dostawcy. - Dodaj sprzedawcę jako użytkownika, korzystając z pola
user, i ustawverificationMailSettings.verificationMailModenaSUPPRESS_VERIFICATION_MAIL.
- Ustaw
- Weryfikacja użytkownika: za pomocą danych logowania od sprzedawcy (np. tokena OAuth) wywołaj metodę
users.verifySelf, aby zmienić stan użytkownika zPENDINGnaVERIFIED. - Ustawianie kraju prowadzenia działalności: za pomocą danych logowania sprzedawcy ustaw kraj prowadzenia działalności, aktualizując
address.regionCodeza pomocąaccounts.updateBusinessInfo. Jest to wymagane przed zaakceptowaniem Warunków korzystania z usługi . - Zaakceptuj Warunki korzystania z usługi: za pomocą danych logowania sprzedawcy zaakceptuj Warunki korzystania z usługi .
Ten proces umożliwia bezproblemowe wprowadzenie sprzedawcy na platformę bez konieczności wysyłania e-maili z zaproszeniem od Google.
Tworzenie konta klienta (za pomocą agregacji kont)
Konta klientów to oddzielne konta Merchant Center połączone z kontem zaawansowanym za pomocą usługi accountAggregation, co umożliwia scentralizowane zarządzanie przy zachowaniu oddzielnych ustawień, witryn i plików danych. Do tworzenia nowych kont klientów możesz używać podrzędnego interfejsu API Merchant Accounts.
Aby utworzyć konta klientów, musisz najpierw skonfigurować konto zaawansowane. Aby przekształcić konto Merchant Center w konto zaawansowane, musisz być administratorem konta. Na koncie nie może być też żadnych oczekujących problemów.
Aby utworzyć nowe konto klienta, wywołaj metodę accounts.createAndConfigure.
W treści żądania:
- W polu
accountpodaj szczegóły konta, które chcesz utworzyć. - W polu
accountNamenie używaj powtarzających się ani niepotrzebnych znaków interpunkcyjnych, wielkich liter, podkreśleń ani symboli niealfanumerycznych (takich jak „/” lub „_”). Unikaj sufiksów związanych z określeniem firmy (np. „Inc.” lub „GmbH”), tekstu promocyjnego, danych osobowych i nieodpowiedniego języka. Użyj krótkiej, jasnej i profesjonalnej nazwy. Więcej informacji znajdziesz w artykule o dodawaniu nazwy firmy. - Opcjonalnie określ nowych autoryzowanych użytkowników w polu
user. Dostęp użytkowników do konta jest również dziedziczony z nadrzędnego konta zaawansowanego. - W polu
servicewpiszaccountAggregationi ustawproviderna nazwę zasobu konta zaawansowanego (np.providers/{ADVANCED_ACCOUNT_ID}). Dzięki temu konto zaawansowane zostanie ustanowione jako agregator nowego konta.
Poniżej znajduje się przykładowe żądanie utworzenia konta klienta o nazwie „merchantStore” połączonego z kontem zaawansowanym {ADVANCED_ACCOUNT_ID}:
POST https://merchantapi.googleapis.com/accounts/v1/accounts:createAndConfigure
{
"account": {
"accountName": "merchantStore",
"adultContent": false,
"timeZone": {
"id": "America/New_York"
},
"languageCode": "en-US"
},
"service": [
{
"accountAggregation": {},
"provider": "providers/{ADVANCED_ACCOUNT_ID}"
}
]
}
Prawidłowe wywołanie tworzy nowe konto klienta i łączy je z określonym kontem zaawansowanym. Treść odpowiedzi będzie zawierać nowo utworzony zasób Account.
Przykłady poniżej pokazują, jak za pomocą accounts.createAndConfigure utworzyć nowe konto klienta.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.Account;
import com.google.shopping.merchant.accounts.v1.AccountAggregation;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest;
import com.google.shopping.merchant.accounts.v1.CreateAndConfigureAccountRequest.AddAccountService;
import com.google.type.TimeZone;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to create a sub-account under an advanced account. */
public class CreateSubAccountSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static Account createSubAccount(Config config) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
AccountsServiceSettings accountsServiceSettings =
AccountsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent/provider to identify the advanced account into which to insert the subaccount.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (AccountsServiceClient accountsServiceClient =
AccountsServiceClient.create(accountsServiceSettings)) {
CreateAndConfigureAccountRequest request =
CreateAndConfigureAccountRequest.newBuilder()
.setAccount(
Account.newBuilder()
.setAccountName("Demo Business")
.setAdultContent(false)
.setTimeZone(TimeZone.newBuilder().setId("America/New_York").build())
.setLanguageCode("en-US")
.build())
.addService(
AddAccountService.newBuilder()
.setProvider(parent)
.setAccountAggregation(AccountAggregation.getDefaultInstance())
.build())
.build();
System.out.println("Sending Create SubAccount request");
Account response = accountsServiceClient.createAndConfigureAccount(request);
System.out.println("Inserted Account Name below");
// Format: `accounts/{account}`
System.out.println(response.getName());
return response;
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
createSubAccount(config);
}
}
PHP
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Account;
use Google\Shopping\Merchant\Accounts\V1\AccountAggregation;
use Google\Shopping\Merchant\Accounts\V1\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\CreateAndConfigureAccountRequest;
use Google\Shopping\Merchant\Accounts\V1\CreateAndConfigureAccountRequest\AddAccountService;
use Google\Type\TimeZone;
/**
* This class demonstrates how to create a sub-account under an MCA account.
*/
class CreateSubAccount
{
private static function getParent(string $accountId): string
{
return sprintf("accounts/%s", $accountId);
}
public static function createSubAccount(array $config): void
{
// Gets the OAuth credentials to make the request.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates options config containing credentials for the client to use.
$options = ['credentials' => $credentials];
// Creates a client.
$accountsServiceClient = new AccountsServiceClient($options);
// Creates parent/provider to identify the MCA account into which to insert the subaccount.
$parent = self::getParent($config['accountId']);
// Calls the API and catches and prints any network failures/errors.
try {
$request = new CreateAndConfigureAccountRequest([
'account' => (new Account([
'account_name' => 'Demo Business',
'adult_content' => false,
'time_zone' => (new TimeZone(['id' => 'America/New_York'])),
'language_code' => 'en-US',
])),
'service' => [
(new AddAccountService([
'provider' => $parent,
'account_aggregation' => new AccountAggregation,
])),
],
]);
print "Sending Create SubAccount request\n";
$response = $accountsServiceClient->createAndConfigureAccount($request);
print "Inserted Account Name below\n";
// Format: `accounts/{account}
print $response->getName() . PHP_EOL;
} catch (ApiException $e) {
print $e->getMessage();
}
}
public function callSample(): void
{
$config = Config::generateConfig();
self::createSubAccount($config);
}
}
$sample = new CreateSubAccount();
$sample->callSample();
Python
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import Account
from google.shopping.merchant_accounts_v1 import AccountAggregation
from google.shopping.merchant_accounts_v1 import AccountsServiceClient
from google.shopping.merchant_accounts_v1 import CreateAndConfigureAccountRequest
def get_parent(account_id):
return f"accounts/{account_id}"
def create_sub_account(account_id: str) -> Account:
"""Creates a sub-account under an advanced account."""
# Get OAuth credentials.
credentials = generate_user_credentials.main()
# Create a client.
client = AccountsServiceClient(credentials=credentials)
# Get the parent advanced account ID.
parent = get_parent(account_id)
# Create the request.
request = CreateAndConfigureAccountRequest(
account=Account(
account_name="Demo Business",
adult_content=False,
time_zone={"id": "America/New_York"},
language_code="en-US",
),
service=[
CreateAndConfigureAccountRequest.AddAccountService(
provider=parent,
account_aggregation=AccountAggregation(),
)
],
)
# Make the request and print the response.
try:
print("Sending Create SubAccount request")
response = client.create_and_configure_account(request=request)
print("Inserted Account Name below")
print(response.name)
return response
except RuntimeError as e:
print(e)
raise
if __name__ == "__main__":
_account_id = configuration.Configuration().read_merchant_info()
create_sub_account(_account_id)
cURL
curl -X POST \
"https://merchantapi.googleapis.com/accounts/v1/accounts:createAndConfigure" \
-H "Authorization: Bearer {YOUR_ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"account": {
"accountName": "Demo Business",
"adultContent": false,
"timeZone": {
"id": "America/New_York"
},
"languageCode": "en-US"
},
"service": [
{
"accountAggregation": {},
"provider": "providers/{ADVANCED_ACCOUNT_ID}"
}
]
}'
Pobieranie kont klientów
Aby wyświetlić listę wszystkich kont klientów danego konta zaawansowanego, użyj metody accounts.listSubaccounts. Podaj identyfikator konta zaawansowanego w polu provider adresu URL żądania.
Oto przykładowe żądanie:
GET https://merchantapi.googleapis.com/accounts/v1/accounts/{ADVANCED_ACCOUNT_ID}:listSubaccounts
Oto przykładowa odpowiedź na udane wywołanie:
{
"accounts": [
{
"name": "accounts/<var class=\"readonly\">{SUB_ACCOUNT_ID_1}</var>",
"accountId": "<var class=\"readonly\">{SUB_ACCOUNT_ID_1}</var>",
"accountName": "<var class=\"readonly\">{SUB_ACCOUNT_NAME_1}</var>",
"timeZone": {
"id": "America/Los_Angeles"
},
"languageCode": "en-US"
},
{
"name": "accounts/<var class=\"readonly\">{SUB_ACCOUNT_ID_2}</var>",
"accountId": "<var class=\"readonly\">{SUB_ACCOUNT_ID_2}</var>",
"accountName": "<var class=\"readonly\">{SUB_ACCOUNT_NAME_2}</var>",
"timeZone": {
"id": "America/Los_Angeles"
},
"languageCode": "en-US"
}
]
}
Poniższe przykłady pokazują, jak wyświetlić listę wszystkich kont klientów na koncie zaawansowanym.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.Account;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient.ListSubAccountsPagedResponse;
import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.ListSubAccountsRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to list all the subaccounts of an advanced account. */
public class ListSubAccountsSample {
private static String getParent(String accountId) {
return String.format("accounts/%s", accountId);
}
public static ListSubAccountsPagedResponse listSubAccounts(Config config) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
AccountsServiceSettings accountsServiceSettings =
AccountsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates parent/provider to identify the advanced account from which to list all sub-accounts.
String parent = getParent(config.getAccountId().toString());
// Calls the API and catches and prints any network failures/errors.
try (AccountsServiceClient accountsServiceClient =
AccountsServiceClient.create(accountsServiceSettings)) {
// The parent has the format: accounts/{account}
ListSubAccountsRequest request =
ListSubAccountsRequest.newBuilder().setProvider(parent).build();
System.out.println("Sending list subaccounts request:");
ListSubAccountsPagedResponse response = accountsServiceClient.listSubAccounts(request);
int count = 0;
// Iterates over all rows in all pages and prints the datasource in each row.
// Automatically uses the `nextPageToken` if returned to fetch all pages of data.
for (Account account : response.iterateAll()) {
System.out.println(account);
count++;
}
System.out.print("The following count of accounts were returned: ");
System.out.println(count);
return response;
}
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
listSubAccounts(config);
}
}
PHP
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\ListSubAccountsRequest;
/**
* This class demonstrates how to list all the subaccounts of an advanced account.
*/
class ListSubAccounts
{
private static function getParent(string $accountId): string
{
return sprintf("accounts/%s", $accountId);
}
public static function listSubAccounts(array $config): void
{
// Gets the OAuth credentials to make the request.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates options config containing credentials for the client to use.
$options = ['credentials' => $credentials];
// Creates a client.
$accountsServiceClient = new AccountsServiceClient($options);
// Creates parent/provider to identify the advanced account from which
//to list all accounts.
$parent = self::getParent($config['accountId']);
// Calls the API and catches and prints any network failures/errors.
try {
// The parent has the format: accounts/{account}
$request = new ListSubAccountsRequest(['provider' => $parent]);
print "Sending list subaccounts request:\n";
$response = $accountsServiceClient->listSubAccounts($request);
$count = 0;
// Iterates over all rows in all pages and prints the datasource in each row.
// Automatically uses the `nextPageToken` if returned to fetch all pages of data.
foreach ($response->iterateAllElements() as $account) {
print_r($account);
$count++;
}
print "The following count of accounts were returned: ";
print $count . PHP_EOL;
} catch (ApiException $e) {
print "An error has occured: \n";
print $e->getMessage();
}
}
public function callSample(): void
{
$config = Config::generateConfig();
self::listSubAccounts($config);
}
}
$sample = new ListSubAccounts();
$sample->callSample();
Python
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import AccountsServiceClient
from google.shopping.merchant_accounts_v1 import ListSubAccountsRequest
def get_parent(account_id):
return f"accounts/{account_id}"
def list_sub_accounts(account_id: str):
"""Lists all the subaccounts of an advanced account."""
# Get OAuth credentials.
credentials = generate_user_credentials.main()
# Create a client.
client = AccountsServiceClient(credentials=credentials)
# Get the parent advanced account ID.
parent = get_parent(account_id)
# Create the request.
request = ListSubAccountsRequest(provider=parent)
# Make the request and print the response.
try:
print("Sending list subaccounts request:")
response = client.list_sub_accounts(request=request)
count = 0
for account in response:
print(account)
count += 1
print(f"The following count of accounts were returned: {count}")
return response
except RuntimeError as e:
print("An error has occured: ")
print(e)
raise
if __name__ == "__main__":
_account_id = configuration.Configuration().read_merchant_info()
list_sub_accounts(_account_id)
cURL
curl -X GET \
"https://merchantapi.googleapis.com/accounts/v1/accounts/{ADVANCED_ACCOUNT_ID}:listSubaccounts" \
-H "Authorization: Bearer {YOUR_ACCESS_TOKEN}" \
Usuwanie konta klienta
Jeśli nie musisz już zarządzać kontem klienta, możesz je usunąć za pomocą metody accounts.delete.
Wykonanie tej metody wymaga dostępu administratora do usuwanego konta.
Oto przykładowe żądanie:
DELETE https://merchantapi.googleapis.com/accounts/v1/accounts/{SUB_ACCOUNT_ID}
Jeśli operacja się powiedzie, treść odpowiedzi będzie pustym obiektem JSON, co oznacza, że konto zostało usunięte.
Poniższe przykłady pokazują, jak usunąć konto klienta.
Java
import com.google.api.gax.core.FixedCredentialsProvider;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.shopping.merchant.accounts.v1.AccountName;
import com.google.shopping.merchant.accounts.v1.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1.DeleteAccountRequest;
import shopping.merchant.samples.utils.Authenticator;
import shopping.merchant.samples.utils.Config;
/** This class demonstrates how to delete a given Merchant Center account. */
public class DeleteAccountSample {
// This method can delete a standalone, advanced account or sub-account. If you delete an advanced
// account,
// all sub-accounts will also be deleted.
// Admin user access is required to execute this method.
public static void deleteAccount(Config config, String accountId) throws Exception {
// Obtains OAuth token based on the user's configuration.
GoogleCredentials credential = new Authenticator().authenticate();
// Creates service settings using the credentials retrieved above.
AccountsServiceSettings accountsServiceSettings =
AccountsServiceSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(credential))
.build();
// Creates account name to identify the account.
String name =
AccountName.newBuilder()
.setAccount(accountId)
.build()
.toString();
// Calls the API.
try (AccountsServiceClient accountsServiceClient =
AccountsServiceClient.create(accountsServiceSettings)) {
DeleteAccountRequest request =
DeleteAccountRequest.newBuilder()
.setName(name)
// Optional. If set to true, the account will be deleted even if it has offers or
// provides services to other accounts. Defaults to 'false'.
.setForce(true)
.build();
System.out.println("Sending Delete Account request");
accountsServiceClient.deleteAccount(request); // No response returned on success.
System.out.println("Delete successful.");
}
}
public static void deleteAccount(Config config) throws Exception {
deleteAccount(config, config.getAccountId().toString());
}
public static void main(String[] args) throws Exception {
Config config = Config.load();
deleteAccount(config);
}
}
PHP
use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1\DeleteAccountRequest;
/**
* This class demonstrates how to delete a given Merchant Center account.
*/
class DeleteAccount
{
private static function getParent(string $accountId): string
{
return sprintf("accounts/%s", $accountId);
}
// This method can delete a standalone, advanced account or sub-account.
// If you delete an advanced account, all sub-accounts will also be deleted.
// Admin user access is required to execute this method.
public static function deleteAccount(array $config): void
{
// Gets the OAuth credentials to make the request.
$credentials = Authentication::useServiceAccountOrTokenFile();
// Creates options config containing credentials for the client to use.
$options = ['credentials' => $credentials];
// Creates a client.
$accountsServiceClient = new AccountsServiceClient($options);
// Gets the account ID from the config file.
$accountId = $config['accountId'];
// Creates account name to identify the account.
$name = self::getParent($accountId);
// Calls the API and catches and prints any network failures/errors.
try {
$request = new DeleteAccountRequest([
'name' => $name,
// Optional. If set to true, the account will be deleted even if it has offers or
// provides services to other accounts. Defaults to 'false'.
'force' => true,
]);
print "Sending Delete Account request\n";
$accountsServiceClient->deleteAccount($request); // No response returned on success.
print "Delete successful.\n";
} catch (ApiException $e) {
print $e->getMessage();
}
}
public function callSample(): void
{
$config = Config::generateConfig();
self::deleteAccount($config);
}
}
$sample = new DeleteAccount();
$sample->callSample();
Python
from examples.authentication import configuration
from examples.authentication import generate_user_credentials
from google.shopping.merchant_accounts_v1 import AccountsServiceClient
from google.shopping.merchant_accounts_v1 import DeleteAccountRequest
def get_parent(account_id):
return f"accounts/{account_id}"
def delete_account(account_id: str):
"""Deletes a given Merchant Center account."""
# Get OAuth credentials.
credentials = generate_user_credentials.main()
# Create a client.
client = AccountsServiceClient(credentials=credentials)
# Create the account name.
name = get_parent(account_id)
# Create the request.
request = DeleteAccountRequest(name=name, force=True)
# Make the request and print the response.
try:
print("Sending Delete Account request")
client.delete_account(request=request)
print("Delete successful.")
except RuntimeError as e:
print(e)
raise
if __name__ == "__main__":
_account_id = configuration.Configuration().read_merchant_info()
delete_account(_account_id)
cURL
curl -X DELETE \
"https://merchantapi.googleapis.com/accounts/v1/accounts/{SUB_ACCOUNT_ID}?force=true" \
-H "Authorization: Bearer {YOUR_ACCESS_TOKEN}" \
Zaakceptuj Warunki korzystania z usługi
Konta klientów dziedziczą Warunki korzystania z usługi Merchant Center, które zostały zaakceptowane na nadrzędnym koncie zaawansowanym.
Aktualizacja informacji o firmie
Za pomocą interfejsu Merchant Accounts API możesz edytować informacje o firmie na kontach klientów.
- Aby wyświetlić informacje o firmie na koncie, wywołaj metodę
accounts.getBusinessInfo. - Aby edytować informacje o firmie na koncie, zadzwoń pod numer
accounts.updateBusinessInfo.