Łączenie z kontami menedżera

Konta menedżera to konta Google Ads, które są używane do celów administracyjnych, a nie do wyświetlania reklam. Są one pojedynczymi punktami dostępu do kont, którymi zarządzają, dlatego są używane do konfigurowania płatności skonsolidowanych i innych funkcji na wielu kontach.

Usługi

Dwa interfejsy API Google Ads, które służą do tworzenia połączenia między dwoma kontami, to CustomerClientLinkServiceCustomerManagerLinkService. W

nazwy tych usług, słowo „Klient” odnosi się do bieżącego konta w kontekście żądania.

  • Jeśli jesteś użytkownikiem konta menedżera, który chce sprawdzić konta zarządzanych klientów, użyj CustomerClientLinkService.
  • Jeśli jesteś klientem, który chce połączyć swoje konto z kontem menedżera znajdującym się w hierarchii powyżej, wybierz CustomerManagerLinkService.

Te 2 usługi to w zasadzie 2 różne widoki tego samego linku. Jeśli konto menedżera M zarządza kontem klienta C, to CustomerClientLink wyświetlany z konta M jest tym samym podmiotem co CustomerManagerLink wyświetlany z konta C.

Procedura

Połączenie dwóch kont musi być zawsze inicjowane z poziomu konta menedżera, a następnie zatwierdzane z poziomu konta klienta. Stan linku jest przechowywany w polu status w CustomerClientLink lub CustomerManagerLink. Zobacz listę prawidłowych stanów. Użyj PENDING, aby zainicjować połączenie, a ACTIVE, aby je zaakceptować.

Połączenie 2 istniejących kont Google Ads można wykonać w 3 krokach.

  1. Podczas uwierzytelniania jako konto menedżera wyślij zaproszenie na konto klienta, tworząc obiekt CustomerClientLink ze stanem PENDING.
  2. Podczas uwierzytelniania jako konto menedżera wyślij zapytanie do GoogleAdsService, aby znaleźć manager_link_id utworzonego CustomerClientLink.
  3. Podczas uwierzytelniania jako konto klienta zaakceptuj zaproszenie z konta menedżera, zmieniając wartość CustomerManagerLink na ACTIVE.

Przykład

Poniższy przykład kodu pokazuje, jak nawiązać połączenie między kontem menedżera a jego klientem:

Java

private void runExample(GoogleAdsClient googleAdsClient, long clientCustomerId, long managerId) {
  // This example assumes that the same credentials will work for both customers, but that may not
  // be the case. If you need to use different credentials for each customer, then you may either
  // update the client configuration or instantiate two clients, one for each set of credentials.
  // Always make sure you use a GoogleAdsClient with the proper credentials to fetch any services
  // you need to use.

  // Extend an invitation to the client while authenticating as the manager.
  googleAdsClient = googleAdsClient.toBuilder().setLoginCustomerId(managerId).build();

  CustomerClientLinkOperation.Builder clientLinkOp = CustomerClientLinkOperation.newBuilder();
  clientLinkOp
      .getCreateBuilder()
      .setStatus(ManagerLinkStatus.PENDING)
      .setClientCustomer(ResourceNames.customer(clientCustomerId));

  String pendingLinkResourceName;

  try (CustomerClientLinkServiceClient customerClientLinkServiceClient =
      googleAdsClient.getLatestVersion().createCustomerClientLinkServiceClient()) {
    MutateCustomerClientLinkResponse response =
        customerClientLinkServiceClient.mutateCustomerClientLink(
            String.valueOf(managerId), clientLinkOp.build());

    pendingLinkResourceName = response.getResult().getResourceName();

    System.out.printf(
        "Extended an invitation from customer %s to customer %s with client link resource name"
            + " %s%n",
        managerId, clientCustomerId, pendingLinkResourceName);
  }

  // Find the manager_link_id of the link we just created, so we can construct the resource name
  // for the link from the client side.
  String query =
      "SELECT customer_client_link.manager_link_id FROM customer_client_link WHERE"
          + " customer_client_link.resource_name = '"
          + pendingLinkResourceName
          + "'";
  long managerLinkId;

  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    SearchPagedResponse response =
        googleAdsServiceClient.search(String.valueOf(managerId), query);
    GoogleAdsRow result = response.iterateAll().iterator().next();
    managerLinkId = result.getCustomerClientLink().getManagerLinkId();
  }

  // Accept the link using the client account.
  CustomerManagerLinkOperation.Builder managerLinkOp = CustomerManagerLinkOperation.newBuilder();
  managerLinkOp
      .getUpdateBuilder()
      .setResourceName(
          ResourceNames.customerManagerLink(clientCustomerId, managerId, managerLinkId))
      .setStatus(ManagerLinkStatus.ACTIVE);

  managerLinkOp.setUpdateMask(FieldMasks.allSetFieldsOf(managerLinkOp.getUpdate()));

  googleAdsClient = googleAdsClient.toBuilder().setLoginCustomerId(clientCustomerId).build();

  try (CustomerManagerLinkServiceClient managerLinkServiceClient =
      googleAdsClient.getLatestVersion().createCustomerManagerLinkServiceClient()) {
    MutateCustomerManagerLinkResponse response =
        managerLinkServiceClient.mutateCustomerManagerLink(
            String.valueOf(clientCustomerId), Arrays.asList(managerLinkOp.build()));
    System.out.printf(
        "Client accepted invitation with resource name %s%n",
        response.getResults(0).getResourceName());
  }
}
      

C#

public void Run(GoogleAdsClient client, long managerCustomerId, long clientCustomerId)
{
    // Remarks: For ease of understanding, this code example assumes that managerCustomerId
    // and clientCustomerId have the login email (and hence the same credentials work for
    // both accounts). In real life, this might not be the case, so you'd have a separate
    // GoogleAdsClient for managerCustomerId and clientCustomerId.
    try
    {
        // Extend an invitation to the client while authenticating as the manager.
        string customerClientLinkResourceName = CreateInvitation(client, managerCustomerId,
            clientCustomerId);

        // Retrieve the manager link information.
        string managerLinkResourceName = GetManagerLinkResourceName(client,
            managerCustomerId, clientCustomerId,
            customerClientLinkResourceName);

        // Accept the manager's invitation while authenticating as the client.
        AcceptInvitation(client, clientCustomerId, managerLinkResourceName);
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}

/// <summary>
/// Extends an invitation from a manager customer to a client customer.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <returns>The invitation resource name.</returns>
private string CreateInvitation(GoogleAdsClient client, long managerCustomerId,
    long clientCustomerId)
{
    // Get the CustomerClientLinkService.
    CustomerClientLinkServiceClient customerClientLinkService =
        client.GetService(Services.V22.CustomerClientLinkService);

    // Create a client with the manager customer ID as login customer ID.
    client.Config.LoginCustomerId = managerCustomerId.ToString();

    // Create a customer client link.
    CustomerClientLink customerClientLink = new CustomerClientLink()
    {
        ClientCustomer = ResourceNames.Customer(clientCustomerId),

        // Sets the client customer to invite.
        Status = ManagerLinkStatus.Pending
    };

    // Creates a customer client link operation for creating the one above.
    CustomerClientLinkOperation customerClientLinkOperation =
        new CustomerClientLinkOperation()
        {
            Create = customerClientLink
        };

    // Issue a mutate request to create the customer client link.
    MutateCustomerClientLinkResponse response =
        customerClientLinkService.MutateCustomerClientLink(
            managerCustomerId.ToString(), customerClientLinkOperation);

    // Prints the result.
    string customerClientLinkResourceName = response.Result.ResourceName;
    Console.WriteLine($"An invitation has been extended from the manager " +
        $"customer {managerCustomerId} to the client customer {clientCustomerId} with " +
        $"the customer client link resource name '{customerClientLinkResourceName}'.");

    // Returns the resource name of the created customer client link.
    return customerClientLinkResourceName;
}

/// <summary>
/// Retrieves the manager link resource name of a customer client link given its resource
/// name.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="managerCustomerId">The manager customer ID.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <param name="customerClientLinkResourceName">The customer client link resource
/// name.</param>
/// <returns>The manager link resource name.</returns>
private string GetManagerLinkResourceName(GoogleAdsClient client, long managerCustomerId,
    long clientCustomerId, string customerClientLinkResourceName)
{
    // Get the GoogleAdsService.
    GoogleAdsServiceClient googleAdsService =
        client.GetService(Services.V22.GoogleAdsService);

    // Create a client with the manager customer ID as login customer ID.
    client.Config.LoginCustomerId = managerCustomerId.ToString();

    // Creates the query.
    string query = "SELECT customer_client_link.manager_link_id FROM " +
        "customer_client_link WHERE customer_client_link.resource_name = " +
        $"'{customerClientLinkResourceName}'";

    // Issue a search request by specifying the page size.
    GoogleAdsRow result = googleAdsService.Search(
        managerCustomerId.ToString(), query).First();

    // Gets the ID and resource name associated to the manager link found.
    long managerLinkId = result.CustomerClientLink.ManagerLinkId;
    string managerLinkResourceName = ResourceNames.CustomerManagerLink(
        clientCustomerId, managerCustomerId, managerLinkId);
    // Prints the result.
    Console.WriteLine($"Retrieved the manager link of the customer client link: its ID " +
        $"is {managerLinkId} and its resource name is '{managerLinkResourceName}'.");
    // Returns the resource name of the manager link found.
    return managerLinkResourceName;
}

/// <summary>
/// Accepts the invitation.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="clientCustomerId">The client customer ID.</param>
/// <param name="managerLinkResourceName">The manager link resource name.</param>
private void AcceptInvitation(GoogleAdsClient client, long clientCustomerId,
    string managerLinkResourceName)
{
    // Get the CustomerManagerLinkService.
    CustomerManagerLinkServiceClient customerManagerLinkService =
        client.GetService(Services.V22.CustomerManagerLinkService);

    // Create a client with the client customer ID as login customer ID.
    client.Config.LoginCustomerId = clientCustomerId.ToString();

    // Creates the customer manager link with the updated status.
    CustomerManagerLink customerManagerLink = new CustomerManagerLink()
    {
        ResourceName = managerLinkResourceName,
        Status = ManagerLinkStatus.Active
    };

    // Creates a customer manager link operation for updating the one above.
    CustomerManagerLinkOperation customerManagerLinkOperation =
        new CustomerManagerLinkOperation()
        {
            Update = customerManagerLink,
            UpdateMask = FieldMasks.AllSetFieldsOf(customerManagerLink)
        };

    // Issue a mutate request to update the customer manager link.
    MutateCustomerManagerLinkResponse response =
            customerManagerLinkService.MutateCustomerManagerLink(
        clientCustomerId.ToString(), new[] { customerManagerLinkOperation }
    );

    // Prints the result.
    Console.WriteLine($"The client {clientCustomerId} accepted the invitation with " +
        $"the resource name '{response.Results[0].ResourceName}");
}
      

PHP

public static function runExample(int $managerCustomerId, int $clientCustomerId)
{
    // Extends an invitation to the client while authenticating as the manager.
    $customerClientLinkResourceName = self::createInvitation(
        $managerCustomerId,
        $clientCustomerId
    );

    // Retrieves the manager link information.
    $managerLinkResourceName = self::getManagerLinkResourceName(
        $managerCustomerId,
        $clientCustomerId,
        $customerClientLinkResourceName
    );

    // Accepts the manager's invitation while authenticating as the client.
    self::acceptInvitation($clientCustomerId, $managerLinkResourceName);
}

/**
 * Extends an invitation from a manager customer to a client customer.
 *
 * @param int $managerCustomerId the manager customer ID
 * @param int $clientCustomerId the customer ID
 * @return string the resource name of the customer client link created for the invitation
 */
private static function createInvitation(
    int $managerCustomerId,
    int $clientCustomerId
) {
    // Creates a client with the manager customer ID as login customer ID.
    $googleAdsClient = self::createGoogleAdsClient($managerCustomerId);

    // Creates a customer client link.
    $customerClientLink = new CustomerClientLink([
        // Sets the client customer to invite.
        'client_customer' => ResourceNames::forCustomer($clientCustomerId),
        'status' => ManagerLinkStatus::PENDING
    ]);

    // Creates a customer client link operation for creating the one above.
    $customerClientLinkOperation = new CustomerClientLinkOperation();
    $customerClientLinkOperation->setCreate($customerClientLink);

    // Issues a mutate request to create the customer client link.
    $customerClientLinkServiceClient = $googleAdsClient->getCustomerClientLinkServiceClient();
    $response = $customerClientLinkServiceClient->mutateCustomerClientLink(
        MutateCustomerClientLinkRequest::build(
            $managerCustomerId,
            $customerClientLinkOperation
        )
    );

    // Prints the result.
    $customerClientLinkResourceName = $response->getResult()->getResourceName();
    printf(
        "An invitation has been extended from the manager customer %d" .
        " to the client customer %d with the customer client link resource name '%s'.%s",
        $managerCustomerId,
        $clientCustomerId,
        $customerClientLinkResourceName,
        PHP_EOL
    );

    // Returns the resource name of the created customer client link.
    return $customerClientLinkResourceName;
}

/**
 * Retrieves the manager link resource name of a customer client link given its resource name.
 *
 * @param int $managerCustomerId the manager customer ID
 * @param int $clientCustomerId the customer ID
 * @param string $customerClientLinkResourceName the customer client link resource name
 * @return string the manager link resource name
 */
private static function getManagerLinkResourceName(
    int $managerCustomerId,
    int $clientCustomerId,
    string $customerClientLinkResourceName
) {
    // Creates a client with the manager customer ID as login customer ID.
    $googleAdsClient = self::createGoogleAdsClient($managerCustomerId);

    // Creates the query.
    $query = "SELECT customer_client_link.manager_link_id FROM customer_client_link" .
        " WHERE customer_client_link.resource_name = '$customerClientLinkResourceName'";

    // Issues a search request.
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    $response = $googleAdsServiceClient->search(
        SearchGoogleAdsRequest::build($managerCustomerId, $query)
    );

    // Gets the ID and resource name associated to the manager link found.
    $managerLinkId = $response->getIterator()->current()
        ->getCustomerClientLink()
        ->getManagerLinkId();
    $managerLinkResourceName = ResourceNames::forCustomerManagerLink(
        $clientCustomerId,
        $managerCustomerId,
        $managerLinkId
    );

    // Prints the result.
    printf(
        "Retrieved the manager link of the customer client link:" .
        " its ID is %d and its resource name is '%s'.%s",
        $managerLinkId,
        $managerLinkResourceName,
        PHP_EOL
    );

    // Returns the resource name of the manager link found.
    return $managerLinkResourceName;
}

/**
 * Accepts an invitation.
 *
 * @param int $clientCustomerId the customer ID
 * @param string $managerLinkResourceName the resource name of the manager link to accept
 */
private static function acceptInvitation(
    int $clientCustomerId,
    string $managerLinkResourceName
) {
    // Creates a client with the client customer ID as login customer ID.
    $googleAdsClient = self::createGoogleAdsClient($clientCustomerId);

    // Creates the customer manager link with the updated status.
    $customerManagerLink = new CustomerManagerLink();
    $customerManagerLink->setResourceName($managerLinkResourceName);
    $customerManagerLink->setStatus(ManagerLinkStatus::ACTIVE);

    // Creates a customer manager link operation for updating the one above.
    $customerManagerLinkOperation = new CustomerManagerLinkOperation();
    $customerManagerLinkOperation->setUpdate($customerManagerLink);
    $customerManagerLinkOperation->setUpdateMask(
        FieldMasks::allSetFieldsOf($customerManagerLink)
    );

    // Issues a mutate request to update the customer manager link.
    $customerManagerLinkServiceClient =
        $googleAdsClient->getCustomerManagerLinkServiceClient();
    $response = $customerManagerLinkServiceClient->mutateCustomerManagerLink(
        MutateCustomerManagerLinkRequest::build(
            $clientCustomerId,
            [$customerManagerLinkOperation]
        )
    );

    // Prints the result.
    printf(
        "The client %d accepted the invitation with the resource name '%s'.%s",
        $clientCustomerId,
        $response->getResults()[0]->getResourceName(),
        PHP_EOL
    );
}