创建和管理子账号

高级 Merchant Center 账号(有时也称为多客户账号)专为管理多个卖家或网域的大型复杂企业而设计。这包括代表客户管理账号的购物平台、跨国零售商或第三方提供商。高级账号的一项关键功能是,能够直接在自己的账号结构下创建和管理子账号

本指南介绍了如何使用 Merchant API 创建和管理这些子账号。子账号是嵌套在高级账号下的各个不同的 Merchant Center 账号,可集中管理,同时保持各自的设置、网站和数据 Feed。您可以使用 Merchant Accounts 子 API 在高级账号下创建新的子账号。

如需创建子账号,您必须先完成高级账号设置。您必须是账号管理员,才能将 Merchant Center 账号转换为高级账号,并且您的账号不得有任何待处理的问题。请注意,您无法使用 Merchant API 将现有的独立 Merchant Center 账号转换为高级账号下的子账号。

创建子账号

如需在高级账号下创建新的子账号,请调用 accounts.createAndConfigure。在请求正文中:

  1. account 字段中提供要创建的子账号的详细信息。
  2. (可选)在 users 字段中指定任何新的获授权用户。子账号的用户访问权限也会从父级高级账号继承。
  3. service 字段中,指定 accountAggregation,并将 provider 设置为高级账号的资源名称(例如 providers/{ADVANCED_ACCOUNT_ID})。这会将高级账号设为新子账号的汇总账号。

下面是一个请求示例,用于在高级账号 {ADVANCED_ACCOUNT_ID} 下创建名为“merchantStore”的子账号:

POST https://merchantapi.googleapis.com/accounts/v1beta/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.v1beta.Account;
import com.google.shopping.merchant.accounts.v1beta.AccountAggregation;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.CreateAndConfigureAccountRequest;
import com.google.shopping.merchant.accounts.v1beta.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 void 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());
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();

    createSubAccount(config);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1beta\Account;
use Google\Shopping\Merchant\Accounts\V1beta\AccountAggregation;
use Google\Shopping\Merchant\Accounts\V1beta\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\CreateAndConfigureAccountRequest;
use Google\Shopping\Merchant\Accounts\V1beta\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_v1beta import Account
from google.shopping.merchant_accounts_v1beta import AccountAggregation
from google.shopping.merchant_accounts_v1beta import AccountsServiceClient
from google.shopping.merchant_accounts_v1beta 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/v1beta/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 字段中提供高级账号的 ID。

以下是请求示例:

GET https://merchantapi.googleapis.com/accounts/v1beta/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.v1beta.Account;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient.ListSubAccountsPagedResponse;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.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 void 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);
    } catch (Exception e) {
      System.out.println("An error has occured: ");
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    listSubAccounts(config);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1beta\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\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_v1beta import AccountsServiceClient
from google.shopping.merchant_accounts_v1beta 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/v1beta/accounts/{ADVANCED_ACCOUNT_ID}:listSubaccounts" \
-H "Authorization: Bearer <YOUR_ACCESS_TOKEN>"

删除子账号

如果您不再需要管理高级账号下的子账号,可以使用 accounts.delete 方法将其删除。

若要执行此方法,您需要对要删除的子账号拥有管理员访问权限

以下是请求示例:

DELETE https://merchantapi.googleapis.com/accounts/v1beta/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.v1beta.AccountName;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceClient;
import com.google.shopping.merchant.accounts.v1beta.AccountsServiceSettings;
import com.google.shopping.merchant.accounts.v1beta.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) 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();

    // Gets the account ID from the config file.
    String accountId = config.getAccountId().toString();

    // Creates account name to identify the account.
    String name =
        AccountName.newBuilder()
            .setAccount(accountId)
            .build()
            .toString();

    // Calls the API and catches and prints any network failures/errors.
    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.");
    } catch (Exception e) {
      System.out.println(e);
    }
  }

  public static void main(String[] args) throws Exception {
    Config config = Config.load();
    deleteAccount(config);
  }
}

PHP

use Google\ApiCore\ApiException;
use Google\Shopping\Merchant\Accounts\V1beta\Client\AccountsServiceClient;
use Google\Shopping\Merchant\Accounts\V1beta\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_v1beta import AccountsServiceClient
from google.shopping.merchant_accounts_v1beta 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/v1beta/accounts/{SUB_ACCOUNT_ID}?force=true" \
-H "Authorization: Bearer <YOUR_ACCESS_TOKEN>"

接受服务条款

子账号会继承父级高级账号签署的 Merchant Center 服务条款 (TOS)

更新您的商家信息

您可以使用 Merchant Accounts API 修改子账号的商家信息