Nutzerzugriff verwalten

Als Administrator können Sie die Liste der Nutzer mit Zugriff auf ein Konto abrufen, indem Sie Google Ads Query Language-Anweisung, um Alle CustomerUserAccess-Entitäten abfragen die mit einer Kundennummer verknüpft sind. Hier ist eine typische Abfrage:

SELECT
  customer_user_access.user_id,
  customer_user_access.email_address,
  customer_user_access.access_role,
  customer_user_access.access_creation_date_time,
  customer_user_access.inviter_user_email_address
FROM customer_user_access

Sie können auch Nutzer prüfen, die Zugriff auf Ihr Konto haben, und ihre Zugriffsrechte ändern. und Nutzerkonten entfernen. Weitere Informationen zum Kontozugriff Stufen.

Hier ist ein Codebeispiel, das zeigt, wie die Zugriffsrolle eines Nutzers geändert wird. Bei diesem Aufruf wird davon ausgegangen, dass Sie den richtigen Nutzerzugriff identifiziert haben, indem Sie den folgenden Befehl ausführen: wie oben dargestellt.

Java

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.ads.googleads.examples.accountmanagement;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.lib.utils.FieldMasks;
import com.google.ads.googleads.v17.enums.AccessRoleEnum.AccessRole;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.CustomerUserAccess;
import com.google.ads.googleads.v17.services.CustomerUserAccessOperation;
import com.google.ads.googleads.v17.services.CustomerUserAccessServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsRow;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v17.services.GoogleAdsServiceClient.SearchPagedResponse;
import com.google.ads.googleads.v17.services.MutateCustomerUserAccessResponse;
import com.google.ads.googleads.v17.utils.ResourceNames;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import java.util.Optional;

/**
 * Updates the access role of a user, given the email address. Note: Should be run as a user who is
 * an Administrator on the Google Ads account with the specified customer ID. See
 * https://support.google.com/google-ads/answer/9978556 to learn more about account access levels.
 */
public class UpdateUserAccess {

  private static class UpdateUserAccessParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;

    @Parameter(names = ArgumentNames.EMAIL_ADDRESS, required = true)
    private String emailAddress;

    @Parameter(names = ArgumentNames.ACCESS_ROLE, required = true)
    private AccessRole accessRole;
  }

  public static void main(String[] args) {
    UpdateUserAccessParams params = new UpdateUserAccessParams();
    if (!params.parseArguments(args)) {
      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
      params.emailAddress = "INSERT_EMAIL_ADDRESS_HERE";
      params.accessRole = AccessRole.valueOf("INSERT_ACCESS_ROLE_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new UpdateUserAccess()
          .runExample(googleAdsClient, params.customerId, params.emailAddress, params.accessRole);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /**
   * Runs the example.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID to update.
   * @param emailAddress the email address for which to update access role in customer ID.
   * @param accessRole the new access role to set.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String emailAddress,
      AccessRole accessRole) {
    // Obtains the user ID for an email address on a Google Ads account.
    Optional<CustomerUserAccess> accessInfo =
        getCustomerUserAccess(googleAdsClient, customerId, emailAddress);
    // Updates the access to the specified role, if the user is found.
    if (accessInfo.isPresent()) {
      modifyUserAccess(googleAdsClient, customerId, accessInfo.get().getUserId(), accessRole);
    } else {
      System.out.printf(
          "Email address '%s' not found in customer '%s'.%n", emailAddress, customerId);
    }
  }

  /**
   * Gets the user ID associated with an email address on an ad-account.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID in which to lookup user ID.
   * @param emailAddress the email address for which to lookup user ID.
   */
  private Optional<CustomerUserAccess> getCustomerUserAccess(
      GoogleAdsClient googleAdsClient, long customerId, String emailAddress) {
    // Defines a search query to retrieve user access for an email address.
    String query =
        String.format(
            "SELECT "
                + "  customer_user_access.user_id,"
                + "  customer_user_access.email_address,"
                + "  customer_user_access.access_role,"
                + "  customer_user_access.access_creation_date_time "
                + "FROM customer_user_access "
                + "WHERE"
                + "  customer_user_access.email_address LIKE '%s'",
            emailAddress);
    // Connects a new API client to retrieve the access.
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      // Sends the API request.
      SearchPagedResponse response =
          googleAdsServiceClient.search(String.valueOf(customerId), query);
      // Processes the result.
      Iterator<GoogleAdsRow> iterator = response.iterateAll().iterator();
      if (iterator.hasNext()) {
        CustomerUserAccess accessDetails = iterator.next().getCustomerUserAccess();
        System.out.printf(
            "Customer user access with User ID = %d, Email Address = "
                + "%s, Access Role = %s and Creation Time = %s was found in "
                + "Customer ID: %d.%n",
            accessDetails.getUserId(),
            accessDetails.getEmailAddress(),
            accessDetails.getAccessRole(),
            accessDetails.getAccessCreationDateTime(),
            customerId);
        return Optional.of(accessDetails);
      }
      return Optional.empty();
    }
  }

  /**
   * Modifies the user access role to a specified value.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID on which to modify access.
   * @param userId the user ID for which to modify access.
   * @param accessRole the new access role for the user.
   */
  private void modifyUserAccess(
      GoogleAdsClient googleAdsClient, long customerId, long userId, AccessRole accessRole) {
    // Creates an access entity to update.
    CustomerUserAccess updatedAccess =
        CustomerUserAccess.newBuilder()
            .setResourceName(ResourceNames.customerUserAccess(customerId, userId))
            .setAccessRole(accessRole)
            .build();

    // Constructs an update operation.
    CustomerUserAccessOperation operation =
        CustomerUserAccessOperation.newBuilder()
            .setUpdate(updatedAccess)
            .setUpdateMask(FieldMasks.allSetFieldsOf(updatedAccess))
            .build();

    // Connects to the service and issues API request.
    try (CustomerUserAccessServiceClient userAccessServiceClient =
        googleAdsClient.getLatestVersion().createCustomerUserAccessServiceClient()) {
      MutateCustomerUserAccessResponse response =
          userAccessServiceClient.mutateCustomerUserAccess(String.valueOf(customerId), operation);

      // Prints the result.
      System.out.printf(
          "Successfully modified customer user access with resource name '%s' to access level"
              + " '%s'.%n",
          response.getResult().getResourceName(), accessRole);
    }
  }
}

      

C#

// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.Gax.Util;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V17.Enums.AccessRoleEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example updates the access role of a user, given the email address.
    /// Note: This code example should be run as a user who is an Administrator on the Google Ads
    /// account with the specified customer ID. See
    /// https://support.google.com/google-ads/answer/9978556 to learn more about account access
    /// levels.
    /// </summary>
    public class UpdateUserAccess : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="UpdateUserAccess"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// Email address of the user whose access role should be updated.
            /// </summary>
            [Option("emailAddress", Required = true, HelpText =
                "Email address of the user whose access role should be updated.")]
            public string EmailAddress { get; set; }

            /// <summary>
            /// The updated access role.
            /// </summary>
            [Option("accessRole", Required = true, HelpText =
                "The updated access role.")]
            public AccessRole AccessRole { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = ExampleUtilities.ParseCommandLine<Options>(args);

            UpdateUserAccess codeExample = new UpdateUserAccess();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(),
                options.CustomerId,
                options.EmailAddress,
                options.AccessRole);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example updates the access of a user, given the email " +
            "address. Note: This code example should be run as a user who is an Administrator" +
            " on the Google Ads account with the specified customer ID. See " +
            "https://support.google.com/google-ads/answer/9978556 to learn more about account " +
            "access levels.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="emailAddress">Email address of the user whose access role should be
        /// updated.</param>
        /// <param name="accessRole">The updated access role.</param>
        public void Run(GoogleAdsClient client, long customerId, string emailAddress,
            AccessRole accessRole)
        {
            try
            {
                long? userId = GetUserAccess(client, customerId, emailAddress);
                if (userId != null)
                {
                    ModifyUserAccess(client, customerId, userId.Value, accessRole);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Gets the customer user access given an email address.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="emailAddress">Email address of the user whose access role should be
        /// retrieved.</param>
        /// <returns>The user ID if a customer is found, or null if no matching customers were
        /// found.</returns>
        private long? GetUserAccess(GoogleAdsClient client, long customerId, string emailAddress)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient googleAdsService = client.GetService(
                Services.V17.GoogleAdsService);

            // Create the search query. Use the LIKE query for filtering to ignore the text case
            // for email address when searching for a match.
            string searchQuery = "Select customer_user_access.user_id, " +
                "customer_user_access.email_address, customer_user_access.access_role," +
                "customer_user_access.access_creation_date_time from customer_user_access " +
                $"where customer_user_access.email_address LIKE '{emailAddress}'";

            // Retrieves the user accesses.
            PagedEnumerable<SearchGoogleAdsResponse, GoogleAdsRow> searchPagedResponse =
                googleAdsService.Search(customerId.ToString(), searchQuery);

            GoogleAdsRow result = searchPagedResponse.FirstOrDefault();

            // Displays the results.
            if (result != null)
            {
                CustomerUserAccess access = result.CustomerUserAccess;
                Console.WriteLine("Customer user access with User ID = {0}, Email Address = " +
                    "{1}, Access Role = {2} and Creation Time = {3} was found in " +
                    "Customer ID: {4}.", access.UserId, access.EmailAddress, access.AccessRole,
                    access.AccessCreationDateTime, customerId);
                return access.UserId;
            }
            else
            {
                Console.WriteLine("No customer user access with requested email was found.");
                return null;
            }
        }

        /// <summary>
        /// Modifies the user access role to a specified value.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="userId">ID of the user whose access role is modified.</param>
        /// <param name="accessRole">The updated access role.</param>
        private void ModifyUserAccess(GoogleAdsClient client, long customerId, long userId,
            AccessRole accessRole)
        {
            // Get the CustomerUserAccessService.
            CustomerUserAccessServiceClient userAccessService = client.GetService(
                Services.V17.CustomerUserAccessService);

            // Creates the modified user access.
            CustomerUserAccess userAccess = new CustomerUserAccess()
            {
                ResourceName = ResourceNames.CustomerUserAccess(customerId, userId),
                AccessRole = accessRole
            };

            // Creates the operation.
            CustomerUserAccessOperation operation = new CustomerUserAccessOperation()
            {
                Update = userAccess,
                UpdateMask = FieldMasks.AllSetFieldsOf(userAccess)
            };

            // Updates the user access.
            MutateCustomerUserAccessResponse response =
                userAccessService.MutateCustomerUserAccess(
                    customerId.ToString(), operation);

            // Displays the result.
            Console.WriteLine($"Successfully modified customer user access with " +
                $"resource name '{response.Result.ResourceName}'.");
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace Google\Ads\GoogleAds\Examples\AccountManagement;

require __DIR__ . '/../../vendor/autoload.php';

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Enums\AccessRoleEnum\AccessRole;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\CustomerUserAccess;
use Google\Ads\GoogleAds\V17\Services\CustomerUserAccessOperation;
use Google\Ads\GoogleAds\V17\Services\MutateCustomerUserAccessRequest;
use Google\Ads\GoogleAds\V17\Services\SearchGoogleAdsRequest;
use Google\ApiCore\ApiException;

/**
 * This code example updates the access role of a user, given the email address.
 * Note: This code example should be run as a user who is an Administrator on the Google Ads
 * account with the specified customer ID. See
 * https://support.google.com/google-ads/answer/9978556 to learn more about account access
 * levels.
 */
class UpdateUserAccess
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const EMAIL_ADDRESS = 'INSERT_EMAIL_ADDRESS_HERE';
    private const ACCESS_ROLE = 'INSERT_ACCESS_ROLE_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::EMAIL_ADDRESS => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::ACCESS_ROLE => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::EMAIL_ADDRESS] ?: self::EMAIL_ADDRESS,
                $options[ArgumentNames::ACCESS_ROLE] ?: self::ACCESS_ROLE
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $emailAddress the email address of the user whose access role should be updated
     * @param string $accessRole the updated access role
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $emailAddress,
        string $accessRole
    ) {
        $userId = self::getUserAccess($googleAdsClient, $customerId, $emailAddress);
        if (!is_null($userId)) {
            self::modifyUserAccess($googleAdsClient, $customerId, $userId, $accessRole);
        }
    }

    /**
     * Gets the customer user access given an email address.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $emailAddress the email address of the user whose access role should be updated
     * @return int|null the user ID if a customer is found, or null if no matching customers were
     *     found
     */
    private static function getUserAccess(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $emailAddress
    ) {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
        // Creates a query that retrieves all customer user accesses.
        // Use the LIKE query for filtering to ignore the text case for email address when
        // searching for a match.
        $query = "SELECT customer_user_access.user_id, "
            . "customer_user_access.email_address, customer_user_access.access_role,"
            . "customer_user_access.access_creation_date_time FROM customer_user_access "
            . "WHERE customer_user_access.email_address LIKE '$emailAddress'";

        // Issues a search request by to retrieve the customer user accesses.
        $response =
            $googleAdsServiceClient->search(SearchGoogleAdsRequest::build($customerId, $query));
        if (iterator_count($response) > 0) {
            /** @var CustomerUserAccess $customerUserAccess */
            $customerUserAccess = $response->getIterator()->current()->getCustomerUserAccess();
            printf(
                "Customer user access with User ID = %d, Email Address = "
                . "'%s', Access Role = '%s' and Creation Time = %s was found in "
                . "Customer ID: %d.%s",
                $customerUserAccess->getUserId(),
                $customerUserAccess->getEmailAddress(),
                AccessRole::name($customerUserAccess->getAccessRole()),
                $customerUserAccess->getAccessCreationDateTime(),
                $customerId,
                PHP_EOL
            );
            return $customerUserAccess->getUserId();
        } else {
            print 'No customer user access with requested email was found.' . PHP_EOL;
            return null;
        }
    }

    /**
     * Modifies the user access role to a specified value.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param int $userId ID of the user whose access role is modified
     * @param string $accessRole the updated access role
     */
    private static function modifyUserAccess(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $userId,
        string $accessRole
    ) {
        // Creates the modified user access.
        $customerUserAccess = new CustomerUserAccess([
            'resource_name' => ResourceNames::forCustomerUserAccess($customerId, $userId),
            'access_role' => AccessRole::value($accessRole)
        ]);

        // Constructs an operation that will update the customer user access with the specified
        // resource name, using the FieldMasks utility to derive the update mask. This mask tells
        // the Google Ads API which attributes of the customer user access you want to change.
        $customerUserAccessOperation = new CustomerUserAccessOperation();
        $customerUserAccessOperation->setUpdate($customerUserAccess);
        $customerUserAccessOperation->setUpdateMask(
            FieldMasks::allSetFieldsOf($customerUserAccess)
        );

        // Issues a mutate request to update the customer user access.
        $customerUserAccessServiceClient = $googleAdsClient->getCustomerUserAccessServiceClient();
        $response = $customerUserAccessServiceClient->mutateCustomerUserAccess(
            MutateCustomerUserAccessRequest::build($customerId, $customerUserAccessOperation)
        );

        // Prints the resource name of the updated customer user access.
        printf(
            "Successfully modified customer user access with resource name: '%s'%s",
            $response->getResult()->getResourceName(),
            PHP_EOL
        );
    }
}

UpdateUserAccess::main();

      

Python

#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Updates the access role of a user, given the email address.

This code example should be run as a user who is an Administrator on the Google
Ads account with the specified customer ID.

See https://support.google.com/google-ads/answer/9978556 to learn more about
account access levels.
"""

import argparse
import sys

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException

from google.api_core import protobuf_helpers

_ACCESS_ROLES = ["ADMIN", "STANDARD", "READ_ONLY", "EMAIL_ONLY"]


def main(client, customer_id, email_address, access_role):
    """Runs the example.

    Args:
      client: The Google Ads client.
      customer_id: The customer ID.
      email_address: The email address of the user whose access role should
          be updated
      access_role: The updated access role.
    """

    user_id = get_user_access(client, customer_id, email_address)

    if user_id:
        modify_user_access(client, customer_id, user_id, access_role)


def get_user_access(client, customer_id, email_address):
    """Gets the customer user access given an email address.

    Args:
      client: The Google Ads client.
      customer_id: The customer ID.
      email_address: The email address of the user whose access role should
          be updated.

    Returns:
      The user ID integer if a customer is found, otherwise None.
    """
    googleads_service = client.get_service("GoogleAdsService")

    # Creates a query that retrieves all customer user accesses.
    # Use the LIKE query for filtering to ignore the text case for email
    # address when searching for a match.
    query = f"""
        SELECT
          customer_user_access.user_id,
          customer_user_access.email_address,
          customer_user_access.access_role,
          customer_user_access.access_creation_date_time
        FROM customer_user_access
        WHERE customer_user_access.email_address LIKE '{email_address}'"""

    search_request = client.get_type("SearchGoogleAdsRequest")
    search_request.customer_id = customer_id
    search_request.query = query

    response = googleads_service.search(request=search_request)

    try:
        user_access = next(iter(response)).customer_user_access
        print(
            "Customer user access with "
            f"User ID = '{user_access.user_id}', "
            f"Access Role = '{user_access.access_role}', and "
            f"Creation Time = {user_access.access_creation_date_time} "
            f"was found in Customer ID: {customer_id}."
        )
        return user_access.user_id
    except StopIteration:
        # If a StopIteration exception is raised it indicates that the response
        # was empty, no results were found, and this method should return None.
        print("No customer user access with requested email was found.")
        return None


def modify_user_access(client, customer_id, user_id, access_role):
    """Modifies the user access role to a specified value.

    Args:
      client: The Google Ads client.
      customer_id: The customer ID.
      user_id: ID of the user whose access role is being modified.
      access_role: The updated access role.
    """
    customer_user_access_service = client.get_service(
        "CustomerUserAccessService"
    )
    customer_user_access_op = client.get_type("CustomerUserAccessOperation")
    access_role_enum = client.enums.AccessRoleEnum
    customer_user_access = customer_user_access_op.update
    customer_user_access.resource_name = (
        customer_user_access_service.customer_user_access_path(
            customer_id, user_id
        )
    )
    customer_user_access.access_role = getattr(access_role_enum, access_role)
    client.copy_from(
        customer_user_access_op.update_mask,
        protobuf_helpers.field_mask(None, customer_user_access._pb),
    )

    response = customer_user_access_service.mutate_customer_user_access(
        customer_id=customer_id, operation=customer_user_access_op
    )

    print(
        "Successfully modified customer user access with resource name: "
        f"{response.result.resource_name}."
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="This code example updates the access role of a user, "
        "given the email address."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-e",
        "--email_address",
        type=str,
        required=True,
        help="The email address of the user whose access role should be "
        "updated.",
    )
    parser.add_argument(
        "-a",
        "--access_role",
        type=str,
        required=True,
        help="The access role that the given email address should be set to.",
        choices=_ACCESS_ROLES,
    )
    args = parser.parse_args()

    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v17")
    try:
        main(
            googleads_client,
            args.customer_id,
            args.email_address,
            args.access_role,
        )
    except GoogleAdsException as ex:
        print(
            f"Request with ID '{ex.request_id}' failed with status "
            f"'{ex.error.code().name}' and includes the following errors:"
        )
        for error in ex.failure.errors:
            print(f"\tError with message '{error.message}'.")
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Updates the access role of a user, given the email address.
#
# This code example should be run as a user who is an Administrator on the
# Google Ads account with the specified customer ID.
#
# See https://support.google.com/google-ads/answer/9978556 to learn more about
# account access levels.

require 'optparse'
require 'google/ads/google_ads'

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

  if !ACCESS_ROLES.include?(access_role)
    raise "Illegal access role specified. Expected one of " \
      "#{ACCESS_ROLES.join(" ")}"
  end

  user_id = get_user_id(client, customer_id, email_address)

  if user_id
    modify_user_access(client, customer_id, user_id, access_role)
  end
end

def get_user_id(client, customer_id, email_address)
  query = <<~QUERY
    SELECT
      customer_user_access.user_id,
      customer_user_access.email_address,
      customer_user_access.access_role,
      customer_user_access.access_creation_date_time
    FROM customer_user_access
    WHERE customer_user_access.email_address LIKE "#{email_address}"
  QUERY

  response = client.service.google_ads.search(
    customer_id: customer_id,
    query: query,
  )

  result = response.first.customer_user_access
  if result
    puts "Customer user access with User ID #{result.user_id}, Access Role " \
      "#{result.access_role}, Creation Time #{result.access_creation_date_time}, " \
      "was found in customer ID #{customer_id}."

    result.user_id
  else
    puts "No customer user access found with email address #{email_address}."
    nil
  end
end

def modify_user_access(client, customer_id, user_id, access_role)
  operation = client.operation.update_resource.customer_user_access(
      client.path.customer_user_access(customer_id, user_id)) do |ua|
    ua.access_role = access_role.to_sym
  end

  response = client.service.customer_user_access.mutate_customer_user_access(
    customer_id: customer_id,
    operation: operation,
  )

  puts "Successfully updated customer user access with resource name " \
    "#{response.result.resource_name}."
end

if __FILE__ == $0
  ACCESS_ROLES = %w[
    ADMIN
    STANDARD
    READ_ONLY
    EMAIL_ONLY
  ]

  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'
  options[:email_address] = 'INSERT_EMAIL_ADDRESS_HERE'
  options[:access_role] = 'INSERT_ACCESS_ROLE_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %s [options]', File.basename(__FILE__))

    opts.separator ''
    opts.separator 'Options:'

    opts.on('-C', '--customer-id CUSTOMER-ID', String, 'Customer ID') do |v|
      options[:customer_id] = v
    end

    opts.on('-e', '--email-address EMAIL-ADDRESS', String, 'Email Address') do |v|
      options[:email_address] = v
    end

    opts.on('-a', '--access-role ACCESS-ROLE', String, 'Access Role') do |v|
      options[:access_role] = v
    end

    opts.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    update_user_access(
      options.fetch(:customer_id).tr("-", ""),
      options.fetch(:email_address),
      options.fetch(:access_role),
    )
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn field: %s\n", field_path_element.field_name)
        end
      end
      error.error_code.to_h.each do |k, v|
        next if v == :UNSPECIFIED
        STDERR.printf("\tType: %s\n\tCode: %s\n", k, v)
      end
    end
    raise
  end
end

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2020, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example updates the access role of a user, given the email address.
# Note: This code example should be run as a user who is an Administrator on the
# Google Ads account with the specified customer ID. See
# https://support.google.com/google-ads/answer/9978556 to learn more about account
# access levels.

use strict;
use warnings;
use utf8;

use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator;
use Google::Ads::GoogleAds::Utils::FieldMasks;
use Google::Ads::GoogleAds::V17::Resources::CustomerUserAccess;
use
  Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsRequest;
use
  Google::Ads::GoogleAds::V17::Services::CustomerUserAccessService::CustomerUserAccessOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id   = "INSERT_CUSTOMER_ID_HERE";
my $email_address = "INSERT_EMAIL_ADDRESS_HERE";
# See Google::Ads::GoogleAds::V17::Enums::AccessRoleEnum for optional values.
my $access_role = "INSERT_ACCESS_ROLE_HERE";

sub update_user_access {
  my ($api_client, $customer_id, $email_address, $access_role) = @_;

  my $user_id = get_user_access($api_client, $customer_id, $email_address);
  if (defined $user_id) {
    modify_user_access($api_client, $customer_id, $user_id, $access_role);
  }

  return 1;
}

# Gets the customer user access given an email address.
sub get_user_access {
  my ($api_client, $customer_id, $email_address) = @_;

  # Create the search query. Use the LIKE query for filtering to ignore the
  # text case for email address when searching for a match.
  my $search_query =
    "SELECT customer_user_access.user_id, customer_user_access.email_address, "
    . "customer_user_access.access_role, customer_user_access.access_creation_date_time "
    . "FROM customer_user_access "
    . "WHERE customer_user_access.email_address LIKE '$email_address'";

  # Create a search Google Ads request that will retrieve the customer user access.
  my $search_request =
    Google::Ads::GoogleAds::V17::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  if ($iterator->has_next) {
    my $google_ads_row = $iterator->next;
    my $access         = $google_ads_row->{customerUserAccess};

    printf "Customer user access with User ID = %d, Email Address = '%s' " .
      "Access Role = '%s' and Creation Time = %s was found in " .
      "Customer ID: %d.\n",
      $access->{userId}, $access->{emailAddress}, $access->{accessRole},
      $access->{accessCreationDateTime}, $customer_id;
    return $access->{userId};
  } else {
    print "No customer user access with requested email was found.\n";
    return undef;
  }
}

# Modifies the user access role to a specified value.
sub modify_user_access {
  my ($api_client, $customer_id, $user_id, $access_role) = @_;

  # Create the modified user access.
  my $user_access =
    Google::Ads::GoogleAds::V17::Resources::CustomerUserAccess->new({
      resourceName =>
        Google::Ads::GoogleAds::V17::Utils::ResourceNames::customer_user_access(
        $customer_id, $user_id
        ),
      accessRole => $access_role
    });

  # Create the operation.
  my $user_access_operation =
    Google::Ads::GoogleAds::V17::Services::CustomerUserAccessService::CustomerUserAccessOperation
    ->new({
      update     => $user_access,
      updateMask => all_set_fields_of($user_access)});

  # Update the user access.
  my $user_access_response = $api_client->CustomerUserAccessService()->mutate({
    customerId => $customer_id,
    operation  => $user_access_operation
  });

  printf
    "Successfully modified customer user access with resource name '%s'.\n",
    $user_access_response->{result}{resourceName};
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"   => \$customer_id,
  "email_address=s" => \$email_address,
  "access_role=s"   => \$access_role
);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id, $email_address, $access_role);

# Call the example.
update_user_access($api_client, $customer_id =~ s/-//gr,
  $email_address, $access_role);

=pod

=head1 NAME

update_user_access

=head1 DESCRIPTION

This code example updates the access role of a user, given the email address.
Note: This code example should be run as a user who is an Administrator on the
Google Ads account with the specified customer ID. See
https://support.google.com/google-ads/answer/9978556 to learn more about account
access levels.

=head1 SYNOPSIS

update_user_access.pl [options]

    -help             Show the help message.
    -customer_id      The Google Ads customer ID.
    -email_address    Email address of the user whose access role should be modifled.
    -access_role      The updated user access role, e.g. ADMIN, STANDARD, READ_ONLY
                      and EMAIL_ONLY.

=cut