Creare account

Puoi utilizzare l'API Merchant per creare account Merchant Center, che possono essere collegati a un account avanzato utilizzando accountAggregation, accountManagement o comparisonShopping. Il accounts.createAndConfigure metodo ti consente di creare un account e, facoltativamente, di configurarlo con gli utenti e collegarlo ad altri account tramite i servizi.

Questa guida spiega come utilizzare l'API Merchant per creare account utilizzando servizi come accountManagement, comparisonShopping o accountAggregation. Quando utilizzi accounts.createAndConfigure, devi collegare il nuovo account a un fornitore specificando almeno uno dei servizi accountAggregation, accountManagement o comparisonShopping nel campo service. Puoi specificare accountAggregation e comparisonShopping nella stessa richiesta, ma accountManagement non può essere combinato con accountAggregation o comparisonShopping. Se specifichi accountManagement, devi anche aggiungere almeno un utente a l nuovo account utilizzando il campo user o users.

Prerequisiti

Prima di poter creare account utilizzando l'API Merchant, assicurati di soddisfare i seguenti requisiti a seconda dei servizi che utilizzi:

  • Accesso amministratore: devi disporre dell'accesso amministratore all' account del fornitore quando colleghi un nuovo account utilizzando accountManagement, comparisonShopping o accountAggregation.
  • Account avanzato: se utilizzi accountAggregation, il tuo account del fornitore deve essere un account avanzato configurato per l'aggregazione degli account. Se sei un fornitore di servizi e devi configurare un account avanzato, contatta l'assistenza per ricevere aiuto con la configurazione.

Creare un account (utilizzando la gestione degli account o lo shopping comparativo)

Per creare un nuovo account, chiama accounts.createAndConfigure. Questo è l'approccio consigliato per i partner che aiutano i commercianti a gestire i propri account, in quanto consente ai commercianti di mantenere il controllo e la proprietà completi del proprio account, concedendo al contempo autorizzazioni specifiche ai partner.

Nel corpo della richiesta:

  1. Fornisci i dettagli dell'account che vuoi creare nel account campo.
  2. Nel campo accountName, non utilizzare punteggiatura ripetuta e non necessaria, maiuscole, trattini bassi, tutte le lettere maiuscole, emoji o simboli non alfanumerici come / o _. Evita suffissi aziendali (come "S.p.A." o "GmbH"), testi promozionali, informazioni personali o linguaggio inappropriato. Utilizza un nome breve, chiaro e professionale. Per saperne di più, consulta Aggiungere un nome dell'attività.
  3. Se utilizzi accountManagement, specifica almeno un utente nel user campo che avrà accesso all'account.
  4. Nel campo service , specifica i servizi che vuoi fornire a questo account, ad esempio accountManagement, e imposta provider sul nome della risorsa del tuo account (ad esempio, providers/{YOUR_ACCOUNT_ID}). Per un elenco dei servizi disponibili, come productsManagement o campaignsManagement, consulta Gestire le relazioni tra gli account.

Di seguito è riportato un esempio di richiesta per creare un account denominato "merchantStore" e collegarlo all'account {YOUR_ACCOUNT_ID} per la gestione dell'account e dei prodotti:

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

Una chiamata riuscita crea il nuovo account e lo collega al tuo account per i servizi specificati. Se specifichi i servizi accountManagement, accountAggregation o comparisonShopping durante la creazione, questi vengono approvati automaticamente e lo stato del collegamento è ESTABLISHED. Altri link di servizio potrebbero essere in stato PENDING finché non vengono accettati dall'account creato. Il corpo della risposta contiene la risorsa Account appena creata.

Dopo aver creato un account di questo tipo, devi eseguirne l'onboarding eseguendo passaggi come l' accettazione dei Termini di servizio, la configurazione delle informazioni sull'attività, e la verifica del sito web.

Eliminare la verifica dell'indirizzo email durante la creazione dell'account

Quando crei un account con accounts.createAndConfigure, puoi facoltativamente eliminare le email di verifica per i nuovi utenti aggiunti utilizzando il campo user impostando verificationMailSettings.verificationMailMode su SUPPRESS_VERIFICATION_MAIL nella richiesta per l'utente. Questa opzione è utile se intendi verificare gli utenti per conto del commerciante immediatamente dopo la creazione utilizzando il metodo users.verifySelf. Per impostazione predefinita, verificationMailMode è SEND_VERIFICATION_MAIL e le email di verifica vengono inviate ai nuovi utenti aggiunti durante la creazione dell'account.

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

Se imposti verificationMailMode su SUPPRESS_VERIFICATION_MAIL, devi chiamare users.verifySelf per ogni utente aggiunto durante la creazione per completare la verifica. Questa chiamata deve essere autenticata come l'utente da verificare (l'utente specificato in userId), ad esempio utilizzando un token OAuth dell'utente.

Specificare un alias durante la creazione dell'account

Puoi specificare un alias per un account nel contesto di un fornitore in CreateAndConfigureAccountRequest utilizzando il campo setAlias. L'alias può essere utilizzato per identificare l'account nel tuo sistema. Se sei un fornitore di servizi, puoi utilizzare l'alias per recuperare l'account utilizzando GET /accounts/v1/accounts/{provider}~{alias}. L'alias deve essere univoco per un determinato fornitore e devi specificare un servizio con lo stesso fornitore nel campo service della richiesta. Per saperne di più sui requisiti degli alias, consulta Gestire le relazioni tra gli account.

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

Se sei un partner che crea un account per conto di un commerciante, ti consigliamo di seguire questo flusso:

  1. Crea account: chiama accounts.createAndConfigure con le tue credenziali di partner per creare un nuovo account.
    • Imposta service in modo da includere accountManagement che rimanda al tuo ID fornitore.
    • Aggiungi il commerciante come utente utilizzando il campo user e imposta verificationMailSettings.verificationMailMode su SUPPRESS_VERIFICATION_MAIL.
  2. Verifica l'utente: con le credenziali del commerciante (ad esempio, utilizzando un token OAuth), chiama users.verifySelf per modificare lo stato dell'utente da PENDING a VERIFIED.
  3. Imposta il paese dell'attività: con le credenziali del commerciante, imposta il paese dell'attività aggiornando address.regionCode utilizzando accounts.updateBusinessInfo. Questo passaggio è obbligatorio prima di accettare i Termini di servizio.
  4. Accetta i Termini di servizio: con le credenziali del commerciante, accetta i Termini di servizio.

Questo flusso consente a un commerciante di eseguire l'onboarding senza problemi all'interno della tua piattaforma senza ricevere email di invito da Google.

Creare un account cliente (utilizzando l'aggregazione degli account)

Gli account cliente sono account Merchant Center distinti collegati al tuo account avanzato utilizzando il servizio accountAggregation, che consente la gestione centralizzata mantenendo separate impostazioni, siti web e feed di dati. Puoi utilizzare la sotto-API Account Merchant per creare nuovi account cliente.

Per creare account cliente, devi prima configurare un account avanzato. Devi essere un amministratore dell'account per convertire il tuo account Merchant Center in un account avanzato e il tuo account non deve avere problemi in attesa di risoluzione.

Per creare un nuovo account cliente, chiama accounts.createAndConfigure. Nel corpo della richiesta:

  1. Fornisci i dettagli dell'account che vuoi creare nel account campo.
  2. Nel campo accountName, non utilizzare punteggiatura, maiuscole, trattini bassi o simboli non alfanumerici ripetuti e non necessari, come "/" o "_". Evita suffissi aziendali (come "S.p.A." o "GmbH"), testi promozionali, informazioni personali o linguaggio inappropriato. Utilizza un nome breve, chiaro e professionale. Per saperne di più, consulta Aggiungere un nome dell'attività.
  3. Facoltativamente, specifica i nuovi utenti autorizzati nel user campo. L'accesso utente per l'account viene ereditato anche dall'account avanzato principale.
  4. Nel service campo, specifica accountAggregation e imposta provider sul nome della risorsa del tuo account avanzato (ad esempio, providers/{ADVANCED_ACCOUNT_ID}). In questo modo, il tuo account avanzato diventa l'aggregatore per il nuovo account.

Di seguito è riportato un esempio di richiesta per creare un account cliente denominato "merchantStore" collegato all'account avanzato {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}"
    }
  ]
}

Una chiamata riuscita crea il nuovo account cliente e lo collega all'account avanzato specificato. Il corpo della risposta conterrà la risorsa Account appena creata.

Gli esempi riportati di seguito mostrano come utilizzare accounts.createAndConfigure per creare un nuovo account cliente.

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

Recuperare gli account cliente

Per elencare tutti gli account cliente di un determinato account avanzato, utilizza il accounts.listSubaccounts metodo. Fornisci l'ID del tuo account avanzato nel campo provider dell'URL della richiesta.

Di seguito è riportata una richiesta di esempio:

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

Di seguito è riportata una risposta di esempio a una chiamata riuscita:

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

Gli esempi riportati di seguito mostrano come elencare tutti gli account cliente del tuo account avanzato.

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

Eliminare un account cliente

Se non hai più bisogno di gestire un account cliente, puoi eliminarlo utilizzando il accounts.delete metodo.

Per eseguire questo metodo è necessario l'accesso amministratore all'account da eliminare.

Di seguito è riportata una richiesta di esempio:

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

In caso di esito positivo, il corpo della risposta è un oggetto JSON vuoto, a indicare che l'account è stato eliminato.

Gli esempi riportati di seguito mostrano come eliminare un account cliente.

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

Accettare i Termini di servizio

Gli account cliente ereditano i Termini di servizio di Merchant Center (TdS) firmati dall'account avanzato principale.

Aggiornare le informazioni sull'attività

Puoi utilizzare la sotto-API Account per modificare le informazioni sull'attività dei tuoi account cliente.