创建账号

如需创建新的客户账号,请提交预先填充的 Customer 对象 ,并使用 CreateCustomerClient 方法(位于 CustomerService 中)。

与标准实体创建(例如使用 mutate 调用创建广告系列)不同,您必须在请求中指定经理账号的客户 ID ,而不是要创建的客户的 ID。

请求和客户字段

调用 CustomerService.CreateCustomerClient 时,请按照下表所示配置 CreateCustomerClientRequest 及其嵌套的 Customer 对象:

字段或标头 要求 可变性和说明
customer_id 必填 直接父级经理账号 (新客户账号在其下创建)的 10 位数客户 ID(不含连字符)。
login-customer-id(标头) 基于条件 如果经过身份验证的用户通过层次结构中更高级别的祖级经理账号访问父级经理账号 (customer_id),则需要在请求标头中指定此字段。
customer_client.descriptive_name 必填 可变:新账号的显示名称(例如 "Acct Created with CustomerService")。日后可以使用 CustomerService.MutateCustomer 进行更新。
customer_client.currency_code 必填 创建后不可变 :3 个字符的 ISO 4217 结算币种代码(例如 USD 或 EUR)。请参阅支持的币种代码。
customer_client.time_zone 必填 创建后不可变 :账号时区 ID(例如 America/New_York)。请参阅支持的时区。
email_address 和 access_role 可选(仅限许可名单) 在创建期间邀请用户 (ADMIN、STANDARD、READ_ONLY 或 EMAIL_ONLY) 访问所创建的账号。不在许可名单中的账号必须在创建后使用 CustomerUserAccessInvitationService 邀请用户。
validate_only 可选 如果为 true,则验证请求参数和经理资格,而不创建账号。

代码示例

以下示例演示了如何在现有经理账号下创建客户账号:

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
      

响应和后续步骤

如果操作成功,CreateCustomerClient 会返回一个 CreateCustomerClientResponse ,其中包含新创建的账号的 resource_name (customers/{new_customer_id})(如果许可名单中的经理账号包含 email_address 和 access_role ,则还会包含 invitation_link)。然后,您可以使用此资源名称或客户 ID 在层次结构中验证账号、授予用户访问权限、配置结算或填充广告系列。

在经理层次结构中验证创建的账号

使用 GoogleAdsService.SearchStream 针对经理 账号 (customer_id) 查询 customer_client 资源,以检查新创建的子账号:

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}

邀请用户访问新账号

如果您的经理账号不在许可名单中,无法直接在 CreateCustomerClientRequest 上设置 email_address 和 access_role,请使用 CustomerUserAccessInvitationService 中的 MutateCustomerUserAccessInvitation 向新创建的 new_customer_id 发送访问 邀请。通过父级经理账号进行身份验证时,请在 HTTP 请求标头中添加 login-customer-id: {manager_customer_id}:

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

错误处理

对 CreateCustomerClient 的调用可能会返回以下错误:

  • CustomerError:表示账号级创建限制,例如 CREATION_DENIED_INELIGIBLE_MCC(经理账号不符合创建新账号的条件)或 CREATION_DENIED_FOR_POLICY_VIOLATION(由于违反政策,客户创建被拒绝)。
  • ManagerLinkError:表示层次结构或账号限制约束, 例如 TOO_MANY_ACCOUNTS、TOO_MANY_ACCOUNTS_AT_MANAGER 或 MAX_DEPTH_EXCEEDED。
  • AccessInvitationError:如果在 CreateCustomerClientRequest 上提供了可选的 email_address(以及 access_role,仅适用于许可清单中的账号)以邀请用户访问新账号,但邀请失败(例如 INVALID_EMAIL_ADDRESS、GOOGLE_CONSUMER_ACCOUNT_NOT_ALLOWED 或 EMAIL_DOMAIN_POLICY_VIOLATED),则会返回此错误。不在许可清单中的账号应在创建账号后使用 CustomerUserAccessInvitationService 邀请用户。
  • CurrencyCodeError.UNSUPPORTED 或 TimeZoneError.INVALID_TIME_ZONE:当 Customer 对象上指定的 currency_code 或 time_zone 无效或 不受支持时返回。