创建帐号

您可以使用 Merchant API 创建 Merchant Center 账号,这些账号可以使用 accountAggregationaccountManagementcomparisonShopping 关联到高级账号。借助 accounts.createAndConfigure 方法,您可以创建账号,并可以选择性地配置用户,以及通过服务将该账号与其他账号相关联。

本指南介绍了如何使用 Merchant API 通过 accountManagementcomparisonShoppingaccountAggregation 等服务创建账号。使用 accounts.createAndConfigure 时,您必须通过在 service 字段中指定 accountAggregationaccountManagementcomparisonShopping 中的至少一个,将新账号与提供商相关联。 您可以在同一请求中指定 accountAggregationcomparisonShopping,但 accountManagement 不能与 accountAggregationcomparisonShopping 组合使用。 如果您指定了 accountManagement,还必须使用 userusers 字段向新账号添加至少一位用户。

前提条件

在使用 Merchant API 创建账号之前,请确保您满足以下要求(具体取决于您使用的服务):

  • 管理员权限:使用 accountManagementcomparisonShoppingaccountAggregation 关联新账号时,您必须拥有提供商账号的管理员权限。
  • 高级账号:如果您使用 accountAggregation,您的提供商账号必须是已配置为支持账号汇总的高级账号。如果您是服务提供商,并且需要设置高级账号,请与支持团队联系,以获取配置方面的帮助。

创建账号(使用账号管理或比较购物)

如需创建新账号,请调用 accounts.createAndConfigure。 对于帮助商家管理其账号的合作伙伴,我们建议采用这种方法,因为这样一来,商家既可以保留对其账号的完全控制权和所有权,又可以向合作伙伴授予特定权限。

在请求正文中:

  1. account 字段中提供您要创建的账号的详细信息。
  2. 如果您使用的是 accountManagement,请在 user 字段中指定至少一个有权访问相应账号的用户。
  3. service 字段中,指定您要向相应账号提供的任何服务,例如 accountManagement,并将 provider 设置为您的账号的资源名称(例如 providers/{YOUR_ACCOUNT_ID})。如需查看可用服务(例如 productsManagementcampaignsManagement)的列表,请参阅管理账号关系

以下是一个示例请求,用于创建名为“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}"
    }
  ]
}

如果调用成功,系统会创建新账号并将其与您账号的指定服务相关联。如果您在创建时指定了 accountManagementaccountAggregationcomparisonShopping 服务,系统会自动批准这些服务,并将关联状态设置为 ESTABLISHED。其他服务关联可能处于 PENDING 状态,直到创建的账号接受关联。响应正文包含新创建的 Account 资源。

创建此类账号后,您需要通过执行接受服务条款设置商家信息验证网站等步骤来完成账号启用。

在账号创建期间禁止进行电子邮件验证

创建使用 accounts.createAndConfigure 的账号时,您可以选择性地禁止向使用 user 字段添加的新用户发送验证电子邮件,方法是在针对该用户的请求中将 verificationMailSettings.verificationMailMode 设置为 SUPPRESS_VERIFICATION_MAIL。如果您打算在创建用户后立即使用 users.verifySelf 方法代表商家验证用户,则此参数非常有用。默认情况下,verificationMailModeSEND_VERIFICATION_MAIL,并且系统会向在创建账号期间添加的新用户发送验证电子邮件。

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 令牌。

在创建账号期间指定别名

您可以使用 setAlias 字段在 CreateAndConfigureAccountRequest 中指定提供方上下文中的账号别名。别名可用于在您的系统中标识相应账号。如果您是服务提供商,可以使用别名通过 GET /accounts/v1/accounts/{provider}~{alias} 检索账号。别名对于给定的提供方必须是唯一的,并且您必须在请求的 service 字段中指定具有相同提供方的服务。如需详细了解别名要求,请参阅管理账号关系

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 以包含指向您的提供方 ID 的 accountManagement 链接。
    • 使用 user 字段将商家添加为用户,并将 verificationMailSettings.verificationMailMode 设置为 SUPPRESS_VERIFICATION_MAIL
  2. 验证用户:使用商家的凭据(例如,使用 OAuth 令牌),调用 users.verifySelf 将用户状态从 PENDING 更改为 VERIFIED
  3. 设置商家所在国家/地区:使用商家凭据,通过使用 accounts.updateBusinessInfo 更新 address.regionCode 来设置商家所在国家/地区。 这是接受服务条款之前必须完成的步骤。
  4. 接受服务条款:使用商家凭据接受服务条款

此流程可让商家在您的平台内顺利完成注册,而无需接收来自 Google 的邀请电子邮件。

创建客户账号(使用账号汇总)

客户账号是与高级账号相关联的独立 Merchant Center 账号,通过 accountAggregation 服务进行关联,可实现集中管理,同时保持单独的设置、网站和数据 Feed。您可以使用 Merchant Accounts 子 API 创建新的客户账号。

若要创建客户账号,您必须先完成高级账号设置。您必须是账号管理员才能将 Merchant Center 账号转换为高级账号,并且您的账号不得有任何待解决的问题

如需创建新的客户账号,请调用 accounts.createAndConfigure。 在请求正文中:

  1. account 字段中提供您要创建的账号的详细信息。
  2. (可选)在 user 字段中指定任何新的授权用户。账号的用户访问权限也继承自父级高级账号。
  3. 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 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\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 字段中提供您的高级账号的 ID。

以下是示例请求:

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 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\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) 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\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>"

接受服务条款

客户账号会沿用父级高级账号签署的 Merchant Center 服务条款 (TOS)

更新商家信息

您可以使用 Merchant Accounts API 编辑客户账号的商家信息