Crea un account

Per creare un nuovo account cliente, invia un oggetto Customer precompilato utilizzando il metodo CreateCustomerClient su CustomerService.

A differenza della creazione di entità standard (ad esempio la creazione di campagne utilizzando le chiamate mutate), devi specificare l'ID cliente dell'account amministratore nella richiesta anziché l'ID del cliente in fase di creazione.

Campi della richiesta e del cliente

Quando chiami CustomerService.CreateCustomerClient, configura CreateCustomerClientRequest e il relativo oggetto Customer nidificato come mostrato nella tabella seguente:

Campo o intestazione Requisito Mutabilità e descrizione
customer_id Obbligatorio L'ID cliente di 10 cifre (senza trattini) dell'account amministratore principale diretto in cui viene creato il nuovo account cliente.
login-customer-id (intestazione) Condizionale Obbligatorio nelle intestazioni della richiesta se l'utente autenticato accede all'account amministratore principale (customer_id) tramite un account amministratore principale di livello superiore nella gerarchia.
customer_client.descriptive_name Obbligatorio Modificabile: nome visualizzato del nuovo account (ad esempio "Acct Created with CustomerService"). Può essere aggiornato in un secondo momento con CustomerService.MutateCustomer.
customer_client.currency_code Obbligatorio Immutabile dopo la creazione: codice valuta di fatturazione ISO 4217 di 3 caratteri (ad esempio, USD o EUR). Consulta i codici valuta supportati.
customer_client.time_zone Obbligatorio Immutabile dopo la creazione: ID del fuso orario dell'account (ad es. America/New_York). Consulta i fusi orari supportati.
email_address e access_role Facoltativo (solo lista consentita) Invita un utente (ADMIN, STANDARD, READ_ONLY o EMAIL_ONLY) all'account creato durante la creazione. Gli account non inclusi nella lista consentita devono invitare gli utenti dopo la creazione utilizzando CustomerUserAccessInvitationService.
validate_only Facoltativo Se impostato su true, convalida i parametri della richiesta e l'idoneità dell'amministratore senza creare l'account.

Codice di esempio

L'esempio seguente mostra come creare un account cliente in un account amministratore esistente:

Java

private void runExample(GoogleAdsClient googleAdsClient, Long managerId) {
  // Formats the current date/time to use as a timestamp in the new customer description.
  String dateTime = ZonedDateTime.now().format(DateTimeFormatter.RFC_1123_DATE_TIME);

  // Initializes a Customer object to be created.
  Customer customer =
      Customer.newBuilder()
          .setDescriptiveName("Account created with CustomerService on '" + dateTime + "'")
          .setCurrencyCode("USD")
          .setTimeZone("America/New_York")
          // Optional: Sets additional attributes of the customer.
          .setTrackingUrlTemplate("{lpurl}?device={device}")
          .setFinalUrlSuffix("keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}")
          .build();

  // Sends the request to create the customer.
  try (CustomerServiceClient client =
      googleAdsClient.getLatestVersion().createCustomerServiceClient()) {
    CreateCustomerClientResponse response =
        client.createCustomerClient(managerId.toString(), customer);
    System.out.printf(
        "Created a customer with resource name '%s' under the manager account with"
            + " customer ID '%d'.%n",
        response.getResourceName(), managerId);
  }
}
      

C#

public void Run(GoogleAdsClient client, long managerCustomerId)
{
    // Get the CustomerService.
    CustomerServiceClient customerService = client.GetService(Services.V26.CustomerService);

    Customer customer = new Customer()
    {
        DescriptiveName = $"Account created with CustomerService on '{DateTime.Now}'",

        // For a list of valid currency codes and time zones see this documentation:
        // https://developers.google.com/google-ads/api/reference/data/codes-formats#codes_formats.
        CurrencyCode = "USD",
        TimeZone = "America/New_York",

        // The below values are optional. For more information about URL
        // options see: https://support.google.com/google-ads/answer/6305348.
        TrackingUrlTemplate = "{lpurl}?device={device}",
        FinalUrlSuffix = "keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}"
    };

    try
    {
        // Create the account.
        CreateCustomerClientResponse response = customerService.CreateCustomerClient(
            managerCustomerId.ToString(), customer);

        // Display the result.
        Console.WriteLine($"Created a customer with resource name " +
            $"'{response.ResourceName}' under the manager account with customer " +
            $"ID '{managerCustomerId}'");
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(GoogleAdsClient $googleAdsClient, int $managerCustomerId)
{
    $customer = new Customer([
        'descriptive_name' => 'Account created with CustomerService on ' . date('Ymd h:i:s'),
        // For a list of valid currency codes and time zones see this documentation:
        // https://developers.google.com/google-ads/api/reference/data/codes-formats.
        'currency_code' => 'USD',
        'time_zone' => 'America/New_York',
        // The below values are optional. For more information about URL
        // options see: https://support.google.com/google-ads/answer/6305348.
        'tracking_url_template' => '{lpurl}?device={device}',
        'final_url_suffix' => 'keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}'
    ]);

    // Issues a mutate request to create an account
    $customerServiceClient = $googleAdsClient->getCustomerServiceClient();
    $response = $customerServiceClient->createCustomerClient(
        CreateCustomerClientRequest::build($managerCustomerId, $customer)
    );

    printf(
        'Created a customer with resource name "%s" under the manager account with '
        . 'customer ID %d.%s',
        $response->getResourceName(),
        $managerCustomerId,
        PHP_EOL
    );
}
      

Python

def main(client: GoogleAdsClient, manager_customer_id: str) -> None:
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        manager_customer_id: a manager client customer ID.
    """
    customer_service: CustomerServiceClient = client.get_service(
        "CustomerService"
    )
    customer: Customer = client.get_type("Customer")
    now: str = datetime.today().strftime("%Y%m%d %H:%M:%S")
    customer.descriptive_name = f"Account created with CustomerService on {now}"
    # For a list of valid currency codes and time zones see this documentation:
    # https://developers.google.com/google-ads/api/reference/data/codes-formats
    customer.currency_code = "USD"
    customer.time_zone = "America/New_York"
    # The below values are optional. For more information about URL
    # options see: https://support.google.com/google-ads/answer/6305348
    customer.tracking_url_template = "{lpurl}?device={device}"
    customer.final_url_suffix = (
        "keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}"
    )

    response: CreateCustomerClientResponse = (
        customer_service.create_customer_client(
            customer_id=manager_customer_id, customer_client=customer
        )
    )
    print(
        f'Customer created with resource name "{response.resource_name}" '
        f'under manager account with ID "{manager_customer_id}".'
    )
      

Ruby

def create_customer(manager_customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  customer = client.resource.customer do |c|
    c.descriptive_name = "Account created with CustomerService on #{(Time.new.to_f * 1000).to_i}"

    # For a list of valid currency codes and time zones, see this documentation:
    # https://developers.google.com/google-ads/api/reference/data/codes-formats
    c.currency_code = "USD"
    c.time_zone = "America/New_York"

    # The below values are optional. For more information about URL options, see:
    # https://support.google.com/google-ads/answer/6305348
    c.tracking_url_template = "{lpurl}?device={device}"
    c.final_url_suffix = "keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}"
  end

  response = client.service.customer.create_customer_client(
    customer_id: manager_customer_id,
    customer_client: customer
  )

  puts "Created a customer with resource name #{response.resource_name} under" +
      " the manager account with customer ID #{manager_customer_id}."
end
      

Perl

sub create_customer {
  my ($api_client, $manager_customer_id) = @_;

  # Initialize a customer to be created.
  my $customer = Google::Ads::GoogleAds::V26::Resources::Customer->new({
      descriptiveName => "Account created with CustomerService on #" . uniqid(),

      # For a list of valid currency codes and time zones, see this documentation:
      # https://developers.google.com/google-ads/api/reference/data/codes-formats
      currencyCode => "USD",
      timeZone     => "America/New_York",

      # The below values are optional. For more information about URL options, see:
      # https://support.google.com/google-ads/answer/6305348
      trackingUrlTemplate => "{lpurl}?device={device}",
      finalUrlSuffix      =>
        "keyword={keyword}&matchtype={matchtype}&adgroupid={adgroupid}"
  });

  # Create the customer client.
  my $create_customer_client_response =
    $api_client->CustomerService()->create_customer_client({
      customerId     => $manager_customer_id,
      customerClient => $customer
    });

  printf
    "Created a customer with resource name '%s' under the manager account " .
    "with customer ID %d.\n", $create_customer_client_response->{resourceName},
    $manager_customer_id;

  return 1;
}
      

curl

# Creates a customer client.
#
# Variables:
#   API_VERSION,
#   MANAGER_CUSTOMER_ID,
#   OAUTH2_ACCESS_TOKEN:
#     See https://developers.google.com/google-ads/api/rest/auth#request_headers
#     for details.
#
curl -f --request POST \
"https://googleads.googleapis.com/v${API_VERSION}/customers/${MANAGER_CUSTOMER_ID}:createCustomerClient" \
--header "Content-Type: application/json" \
--header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \
--header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \
--data @- <<EOF
{
  "customerClient": {
    "descriptiveName": "Account created with CustomerService #${RANDOM}",
    "currencyCode": "USD",
    "timeZone": "America/New_York"
  }
}
EOF
      

Risposta e passaggi successivi

In caso di esito positivo, CreateCustomerClient restituisce un CreateCustomerClientResponse contenente il resource_name (customers/{new_customer_id}) dell'account appena creato (più un invitation_link se email_address e access_role sono stati inclusi da un account amministratore nella lista consentita). Puoi quindi utilizzare questo nome risorsa o ID cliente per verificare l'account nella tua gerarchia, concedere l'accesso utente, configurare la fatturazione o compilare le campagne.

Verifica l'account creato nella gerarchia amministratore

Esegui una query sulla risorsa customer_client nell'account amministratore (customer_id) utilizzando GoogleAdsService.SearchStream per esaminare il subaccount appena creato:

SELECT
  customer_client.id,
  customer_client.resource_name,
  customer_client.client_customer,
  customer_client.descriptive_name,
  customer_client.currency_code,
  customer_client.time_zone,
  customer_client.manager,
  customer_client.level,
  customer_client.status
FROM customer_client
WHERE customer_client.level = 1
  AND customer_client.id = {new_customer_id}

Invita utenti nel nuovo account

Se il tuo account amministratore non è incluso nella lista consentita per l'impostazione di email_address e access_role direttamente su CreateCustomerClientRequest, invia un invito di accesso al new_customer_id appena creato utilizzando MutateCustomerUserAccessInvitation su CustomerUserAccessInvitationService. Quando esegui l'autenticazione tramite l'account amministratore principale, includi login-customer-id: {manager_customer_id} nelle intestazioni della richiesta HTTP:

POST https://googleads.googleapis.com/v26/customers/{new_customer_id}/customerUserAccessInvitations:mutate
{
  "operation": {
    "create": {
      "emailAddress": "user@example.com",
      "accessRole": "ADMIN"
    }
  }
}

Gestione degli errori

Le chiamate a CreateCustomerClient possono restituire i seguenti errori:

  • CustomerError: indica le limitazioni alla creazione a livello di account, ad esempio CREATION_DENIED_INELIGIBLE_MCC (l'account amministratore non è idoneo alla creazione di nuovi account) o CREATION_DENIED_FOR_POLICY_VIOLATION (la creazione del cliente è negata a causa di una violazione delle norme).
  • ManagerLinkError: indica i vincoli della gerarchia o dei limiti dell'account, ad esempio TOO_MANY_ACCOUNTS, TOO_MANY_ACCOUNTS_AT_MANAGER o MAX_DEPTH_EXCEEDED.
  • AccessInvitationError: viene restituito se viene fornito un email_address facoltativo (insieme a access_role, disponibile solo per gli account nella lista consentita) su CreateCustomerClientRequest per invitare un utente al nuovo account e l'invito non va a buon fine (ad esempio INVALID_EMAIL_ADDRESS, GOOGLE_CONSUMER_ACCOUNT_NOT_ALLOWED o EMAIL_DOMAIN_POLICY_VIOLATED). Gli account che non sono nella lista consentita devono invitare gli utenti dopo la creazione dell'account utilizzando CustomerUserAccessInvitationService.
  • CurrencyCodeError.UNSUPPORTED o TimeZoneError.INVALID_TIME_ZONE: restituito quando l'oggetto currency_code o time_zone specificato nell'oggetto Customer non è valido o non è supportato.