Создать учетные записи

Вы можете использовать Merchant API для создания учетных записей Merchant Center, которые можно связать с расширенной учетной записью с помощью accountAggregation , accountManagement или comparisonShopping . Метод accounts.createAndConfigure позволяет создать учетную запись и при необходимости настроить ее с помощью пользователей, а также связать ее с другими учетными записями через сервисы.

This guide explains how to use Merchant API to create accounts using services such as accountManagement , comparisonShopping , or accountAggregation . When using accounts.createAndConfigure , you must link the new account to a provider by specifying at least one of accountAggregation , accountManagement , or comparisonShopping in the service field. You can specify accountAggregation and comparisonShopping in the same request, but accountManagement cannot be combined with either accountAggregation or comparisonShopping . If you specify accountManagement , you must also add at least one user to the new account using the user or users field.

Предварительные требования

Прежде чем создавать учетные записи с помощью Merchant API, убедитесь, что вы соответствуете следующим требованиям в зависимости от используемых вами сервисов:

  • Доступ администратора : Для привязки новой учетной записи с помощью accountManagement , comparisonShopping или accountAggregation вам необходим доступ администратора к учетной записи поставщика.
  • Расширенная учетная запись : Если вы используете accountAggregation , ваша учетная запись поставщика услуг должна быть расширенной учетной записью, настроенной для агрегации учетных записей. Если вы являетесь поставщиком услуг и вам необходимо настроить расширенную учетную запись, обратитесь в службу поддержки за помощью в настройке.

Создайте учетную запись (используя управление учетными записями или сравнение цен).

Для создания новой учетной записи вызовите метод accounts.createAndConfigure . Это рекомендуемый подход для партнеров, помогающих продавцам управлять своими учетными записями, поскольку он позволяет продавцам сохранять полный контроль и право собственности на свою учетную запись, предоставляя при этом партнерам определенные права доступа.

В теле запроса:

  1. В поле account укажите данные учетной записи, которую вы хотите создать.
  2. В поле accountName не используйте повторяющиеся и ненужные знаки препинания, заглавные буквы, подчеркивания, заглавные буквы, эмодзи или небуквенно-цифровые символы, такие как / или _ . Избегайте суффиксов названия компании (например, "Inc." или "GmbH"), рекламного текста, личной информации или неподобающего языка. Используйте короткое, понятное и профессиональное название. Для получения дополнительной информации см. раздел "Добавление названия компании" .
  3. Если вы используете accountManagement , укажите в поле user как минимум одного пользователя, который будет иметь доступ к учетной записи.
  4. В поле service укажите все услуги, которые вы хотите предоставить этой учетной записи, например accountManagement , и установите provider в качестве имени ресурса вашей учетной записи (например, providers/ {YOUR_ACCOUNT_ID} ). Список доступных услуг, таких как productsManagement или campaignsManagement см. в разделе «Управление связями учетных записей» .

Вот пример запроса на создание учетной записи с именем "merchantStore" и привязку ее к учетной записи {YOUR_ACCOUNT_ID} для управления учетными записями и товарами:

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}"
    }
  ]
}

A successful call creates the new account and links it to your account for the specified services. If you specify accountManagement , accountAggregation , or comparisonShopping services during creation, they are automatically approved and the link state is ESTABLISHED . Other service links might be in PENDING state until accepted by the created account. The response body contains the newly created Account resource.

В следующем примере показано, как использовать accounts.createAndConfigure для создания и настройки учетной записи:

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);
  }
}

After creating such an account, you need to onboard it by performing steps such as accepting Terms of Service , setting up business information , and verifying website .

Отключить подтверждение электронной почты при создании учетной записи.

When creating an account with accounts.createAndConfigure , you can optionally suppress verification emails for new users added using the user field by setting verificationMailSettings.verificationMailMode to SUPPRESS_VERIFICATION_MAIL in the request for that user. This is useful if you intend to verify users on behalf of the merchant immediately after creation using the users.verifySelf method. By default, verificationMailMode is SEND_VERIFICATION_MAIL , and verification emails are sent to new users added during account creation.

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}"
    }
  ]
}

Если вы установите verificationMailMode в значение SUPPRESS_VERIFICATION_MAIL , вам потребуется вызвать users.verifySelf для каждого пользователя, добавленного при создании, чтобы завершить проверку. Этот вызов должен быть аутентифицирован как пользователь, подлежащий проверке (пользователь, указанный в userId ), например, с использованием токена OAuth от пользователя.

Укажите псевдоним при создании учетной записи.

You can specify an alias for an account in the context of a provider in CreateAndConfigureAccountRequest using the setAlias field. The alias can be used to identify the account in your system. If you are a service provider, you can use the alias to retrieve the account using GET /accounts/v1/accounts/{provider}~{alias} . The alias must be unique for a given provider, and you must specify a service with the same provider in the service field of the request. For more information on alias requirements, see Manage account relationships .

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"
    }
  ]
}

Если вы являетесь партнером и создаете учетную запись от имени продавца, мы рекомендуем следующий порядок действий:

  1. Создание учетной записи : вызовите accounts.createAndConfigure , используя учетные данные вашего партнера, чтобы создать новую учетную запись.
    • Настройте service таким образом, чтобы он включал привязку accountManagement к идентификатору вашего провайдера.
    • Добавьте продавца в качестве пользователя, используя поле user , и установите параметр verificationMailSettings.verificationMailMode в значение SUPPRESS_VERIFICATION_MAIL .
  2. Проверка пользователя : Используя учетные данные продавца (например, токен OAuth), вызовите метод users.verifySelf , чтобы изменить состояние пользователя с PENDING на VERIFIED .
  3. Установка страны ведения бизнеса : Используя учетные данные продавца, установите страну ведения бизнеса, обновив значение address.regionCode с помощью accounts.updateBusinessInfo . Это необходимо сделать перед принятием Условий предоставления услуг.
  4. Примите условия обслуживания : Используя учетные данные продавца, примите условия обслуживания .

Этот процесс позволяет продавцу беспрепятственно зарегистрироваться на вашей платформе, не получая пригласительных писем от Google.

Создайте клиентский аккаунт (используя агрегацию аккаунтов).

Клиентские аккаунты — это отдельные аккаунты Merchant Center, связанные с вашим расширенным аккаунтом с помощью сервиса accountAggregation , что позволяет централизованно управлять ими, сохраняя при этом отдельные настройки, веб-сайты и потоки данных. Вы можете использовать под-API Merchant Accounts для создания новых клиентских аккаунтов.

Для создания клиентских аккаунтов необходимо сначала настроить расширенный аккаунт . Для преобразования аккаунта Merchant Center в расширенный аккаунт необходимо иметь права администратора аккаунта, а также в аккаунте не должно быть незавершенных операций .

Для создания новой учетной записи клиента вызовите метод accounts.createAndConfigure . В теле запроса:

  1. В поле account укажите данные учетной записи, которую вы хотите создать.
  2. В поле accountName не используйте повторяющиеся и ненужные знаки препинания, заглавные буквы, подчеркивания или небуквенно-цифровые символы (например, "/" или "_"). Избегайте суффиксов названия компании (например, "Inc." или "GmbH"), рекламного текста, личной информации или неподобающего языка. Используйте короткое, понятное и профессиональное название. Для получения дополнительной информации см. раздел "Добавление названия компании" .
  3. При желании укажите любых новых авторизованных пользователей в поле user . Доступ пользователя к учетной записи также наследуется от родительской расширенной учетной записи.
  4. В поле service укажите accountAggregation и задайте provider в качестве имени ресурса вашей расширенной учетной записи (например, providers/ {ADVANCED_ACCOUNT_ID} ). Это установит вашу расширенную учетную запись в качестве агрегатора для новой учетной записи.

Вот пример запроса на создание клиентского аккаунта с именем "merchantStore", связанного с расширенным аккаунтом {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}"
    }
  ]
}

Успешный вызов создает новую учетную запись клиента и связывает ее с указанной вами расширенной учетной записью. Тело ответа будет содержать вновь созданный ресурс Account .

В следующих примерах показано, как использовать метод accounts.createAndConfigure для создания новой учетной записи клиента.

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

_ACCOUNT = configuration.Configuration().read_merchant_info()


def get_parent(account_id):
  return f"accounts/{account_id}"


def create_sub_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)

  # 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)
  except RuntimeError as e:
    print(e)


if __name__ == "__main__":
  create_sub_account()

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}"
    }
  ]
}'

Получение клиентских счетов

Чтобы вывести список всех учетных записей клиентов для заданной расширенной учетной записи, используйте метод accounts.listSubaccounts . Укажите идентификатор вашей расширенной учетной записи в поле provider URL-адреса запроса.

Вот пример запроса:

GET https://merchantapi.googleapis.com/accounts/v1/accounts/{ADVANCED_ACCOUNT_ID}:listSubaccounts

Вот пример ответа после успешного звонка:

{
"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"
    }
  ]
}

Приведенные ниже примеры демонстрируют, как отобразить список всех учетных записей клиентов вашей расширенной учетной записи.

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

_ACCOUNT = configuration.Configuration().read_merchant_info()


def get_parent(account_id):
  return f"accounts/{account_id}"


def list_sub_accounts():
  """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)

  # 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}")

  except RuntimeError as e:
    print("An error has occured: ")
    print(e)


if __name__ == "__main__":
  list_sub_accounts()

cURL

curl -X GET \
"https://merchantapi.googleapis.com/accounts/v1/accounts/{ADVANCED_ACCOUNT_ID}:listSubaccounts" \
-H "Authorization: Bearer {YOUR_ACCESS_TOKEN}" \

Удаление учетной записи клиента

Если вам больше не нужно управлять учетной записью клиента, вы можете удалить ее, используя метод accounts.delete .

Для выполнения этого метода требуются права администратора для удаляемой учетной записи.

Вот пример запроса:

DELETE https://merchantapi.googleapis.com/accounts/v1/accounts/{SUB_ACCOUNT_ID}

В случае успеха тело ответа представляет собой пустой JSON-объект, указывающий на то, что учетная запись была удалена.

Следующие примеры демонстрируют, как удалить учетную запись клиента.

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

_ACCOUNT = configuration.Configuration().read_merchant_info()


def get_parent(account_id):
  return f"accounts/{account_id}"


def delete_account():
  """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)

  # 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)


if __name__ == "__main__":
  delete_account()

cURL

curl -X DELETE \
"https://merchantapi.googleapis.com/accounts/v1/accounts/{SUB_ACCOUNT_ID}?force=true" \
-H "Authorization: Bearer {YOUR_ACCESS_TOKEN}" \

Примите Условия предоставления услуг

Клиентские аккаунты наследуют Условия предоставления услуг (TOS) Merchant Center, подписанные родительским аккаунтом с расширенными возможностями.

Обновите информацию о вашей компании.

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

  • Для просмотра информации о компании, зарегистрированной в учетной записи, вызовите метод accounts.getBusinessInfo .
  • Для редактирования информации о компании в учетной записи вызовите функцию accounts.updateBusinessInfo .