Add Customer Match User List

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.remarketing;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

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.v13.common.CrmBasedUserListInfo;
import com.google.ads.googleads.v13.common.CustomerMatchUserListMetadata;
import com.google.ads.googleads.v13.common.OfflineUserAddressInfo;
import com.google.ads.googleads.v13.common.UserData;
import com.google.ads.googleads.v13.common.UserIdentifier;
import com.google.ads.googleads.v13.enums.CustomerMatchUploadKeyTypeEnum.CustomerMatchUploadKeyType;
import com.google.ads.googleads.v13.enums.OfflineUserDataJobStatusEnum.OfflineUserDataJobStatus;
import com.google.ads.googleads.v13.enums.OfflineUserDataJobTypeEnum.OfflineUserDataJobType;
import com.google.ads.googleads.v13.errors.GoogleAdsError;
import com.google.ads.googleads.v13.errors.GoogleAdsException;
import com.google.ads.googleads.v13.errors.GoogleAdsFailure;
import com.google.ads.googleads.v13.resources.OfflineUserDataJob;
import com.google.ads.googleads.v13.resources.UserList;
import com.google.ads.googleads.v13.services.AddOfflineUserDataJobOperationsRequest;
import com.google.ads.googleads.v13.services.AddOfflineUserDataJobOperationsResponse;
import com.google.ads.googleads.v13.services.CreateOfflineUserDataJobResponse;
import com.google.ads.googleads.v13.services.GoogleAdsRow;
import com.google.ads.googleads.v13.services.GoogleAdsServiceClient;
import com.google.ads.googleads.v13.services.MutateUserListsResponse;
import com.google.ads.googleads.v13.services.OfflineUserDataJobOperation;
import com.google.ads.googleads.v13.services.OfflineUserDataJobServiceClient;
import com.google.ads.googleads.v13.services.SearchGoogleAdsStreamRequest;
import com.google.ads.googleads.v13.services.SearchGoogleAdsStreamResponse;
import com.google.ads.googleads.v13.services.UserListOperation;
import com.google.ads.googleads.v13.services.UserListServiceClient;
import com.google.ads.googleads.v13.utils.ErrorUtils;
import com.google.ads.googleads.v13.utils.ResourceNames;
import com.google.api.gax.rpc.ServerStream;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Creates operations to add members to a user list (a.k.a. audience) using an OfflineUserDataJob,
 * and if requested, runs the job.
 *
 * <p>If a job ID is specified, this example adds operations to that job. Otherwise, it creates a
 * new job for the operations.
 *
 * <p>IMPORTANT: Your application should create a single job containing <em>all</em> of the
 * operations for a user list. This will be far more efficient than creating and running multiple
 * jobs that each contain a small set of operations.
 *
 * <p><em>Notes:</em>
 *
 * <ul>
 *   <li>This feature is only available to accounts that meet the requirements described at
 *       https://support.google.com/adspolicy/answer/6299717.
 *   <li>It may take up to several hours for the list to be populated with members.
 *   <li>Email addresses must be associated with a Google account.
 *   <li>For privacy purposes, the user list size will show as zero until the list has at least
 *       1,000 members. After that, the size will be rounded to the two most significant digits.
 * </ul>
 */
public class AddCustomerMatchUserList {

  private static class AddCustomerMatchUserListParams extends CodeSampleParams {

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

    @Parameter(
        names = ArgumentNames.RUN_JOB,
        required = true,
        arity = 1,
        description =
            "If true, runs the OfflineUserDataJob after adding operations. The default value is"
                + " false.")
    private boolean runJob = true;

    @Parameter(
        names = ArgumentNames.USER_LIST_ID,
        required = false,
        description =
            "The ID of an existing user list. If not specified, this example will create a new user"
                + " list.")
    private Long userListId;

    @Parameter(
        names = ArgumentNames.OFFLINE_USER_DATA_JOB_ID,
        required = false,
        description =
            "The ID of an existing OfflineUserDataJob in the PENDING state. If not specified, this"
                + " example will create a new job.")
    private Long offlineUserDataJobId;
  }

  public static void main(String[] args) throws UnsupportedEncodingException {
    AddCustomerMatchUserListParams params = new AddCustomerMatchUserListParams();
    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.runJob = Boolean.parseBoolean("INSERT_RUN_JOB_HERE");

      // Optional parameters:
      // params.userListId = Long.parseLong("INSERT_USER_LIST_ID_HERE");
      // params.offlineUserDataJobId = Long.parseLong("INSERT_OFFLINE_USER_DATA_JOB_ID_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 AddCustomerMatchUserList()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.runJob,
              params.userListId,
              params.offlineUserDataJobId);
    } 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 Google Ads API client.
   * @param customerId the client customer ID.
   * @param runJob if true, runs the OfflineUserDataJob after adding operations. Otherwise, only
   *     adds operations to the job.
   * @param userListId optional ID of an existing user list. If {@code null}, creates a new user
   *     list.
   * @param offlineUserDataJobId optional ID of an existing OfflineUserDataJob in the PENDING state.
   *     If {@code null}, creates a new job.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      boolean runJob,
      Long userListId,
      Long offlineUserDataJobId)
      throws UnsupportedEncodingException {
    String userListResourceName = null;
    if (offlineUserDataJobId == null) {
      if (userListId == null) {
        // Creates a Customer Match user list.
        userListResourceName = createCustomerMatchUserList(googleAdsClient, customerId);
      } else if (userListId != null) {
        // Uses the specified Customer Match user list.
        userListResourceName = ResourceNames.userList(customerId, userListId);
      }
    }

    // Adds members to the user list.
    addUsersToCustomerMatchUserList(
        googleAdsClient, customerId, runJob, userListResourceName, offlineUserDataJobId);
  }

  /**
   * Creates a Customer Match user list.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @return the resource name of the newly created user list.
   */
  private String createCustomerMatchUserList(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates the new user list.
    UserList userList =
        UserList.newBuilder()
            .setName("Customer Match list #" + getPrintableDateTime())
            .setDescription("A list of customers that originated from email addresses")
            // Customer Match user lists can use a membership life span of 10,000 to indicate
            // unlimited; otherwise normal values apply.
            // Sets the membership life span to 30 days.
            .setMembershipLifeSpan(30)
            // Sets the upload key type to indicate the type of identifier that will be used to
            // add users to the list. This field is immutable and required for a CREATE operation.
            .setCrmBasedUserList(
                CrmBasedUserListInfo.newBuilder()
                    .setUploadKeyType(CustomerMatchUploadKeyType.CONTACT_INFO))
            .build();

    // Creates the operation.
    UserListOperation operation = UserListOperation.newBuilder().setCreate(userList).build();

    // Creates the service client.
    try (UserListServiceClient userListServiceClient =
        googleAdsClient.getLatestVersion().createUserListServiceClient()) {
      // Adds the user list.
      MutateUserListsResponse response =
          userListServiceClient.mutateUserLists(
              Long.toString(customerId), ImmutableList.of(operation));
      // Prints the response.
      System.out.printf(
          "Created Customer Match user list with resource name: %s.%n",
          response.getResults(0).getResourceName());
      return response.getResults(0).getResourceName();
    }
  }

  /**
   * Creates and executes an asynchronous job to add users to the Customer Match user list.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param runJob if true, runs the OfflineUserDataJob after adding operations. Otherwise, only
   *     adds operations to the job.
   * @param userListResourceName the resource name of the Customer Match user list to add members
   *     to.
   * @param offlineUserDataJobId optional ID of an existing OfflineUserDataJob in the PENDING state.
   *     If {@code null}, creates a new job.
   */
  private void addUsersToCustomerMatchUserList(
      GoogleAdsClient googleAdsClient,
      long customerId,
      boolean runJob,
      String userListResourceName,
      Long offlineUserDataJobId)
      throws UnsupportedEncodingException {
    try (OfflineUserDataJobServiceClient offlineUserDataJobServiceClient =
        googleAdsClient.getLatestVersion().createOfflineUserDataJobServiceClient()) {
      String offlineUserDataJobResourceName;
      if (offlineUserDataJobId == null) {
        // Creates a new offline user data job.
        OfflineUserDataJob offlineUserDataJob =
            OfflineUserDataJob.newBuilder()
                .setType(OfflineUserDataJobType.CUSTOMER_MATCH_USER_LIST)
                .setCustomerMatchUserListMetadata(
                    CustomerMatchUserListMetadata.newBuilder().setUserList(userListResourceName))
                .build();

        // Issues a request to create the offline user data job.
        CreateOfflineUserDataJobResponse createOfflineUserDataJobResponse =
            offlineUserDataJobServiceClient.createOfflineUserDataJob(
                Long.toString(customerId), offlineUserDataJob);
        offlineUserDataJobResourceName = createOfflineUserDataJobResponse.getResourceName();
        System.out.printf(
            "Created an offline user data job with resource name: %s.%n",
            offlineUserDataJobResourceName);
      } else {
        // Reuses the specified offline user data job.
        offlineUserDataJobResourceName =
            ResourceNames.offlineUserDataJob(customerId, offlineUserDataJobId);
      }

      // Issues a request to add the operations to the offline user data job. This example
      // only adds a few operations, so it only sends one AddOfflineUserDataJobOperations request.
      // If your application is adding a large number of operations, split the operations into
      // batches and send multiple AddOfflineUserDataJobOperations requests for the SAME job. See
      // https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
      // and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
      // for more information on the per-request limits.
      List<OfflineUserDataJobOperation> userDataJobOperations = buildOfflineUserDataJobOperations();
      AddOfflineUserDataJobOperationsResponse response =
          offlineUserDataJobServiceClient.addOfflineUserDataJobOperations(
              AddOfflineUserDataJobOperationsRequest.newBuilder()
                  .setResourceName(offlineUserDataJobResourceName)
                  .setEnablePartialFailure(true)
                  .addAllOperations(userDataJobOperations)
                  .build());

      // Prints the status message if any partial failure error is returned.
      // NOTE: The details of each partial failure error are not printed here, you can refer to
      // the example HandlePartialFailure.java to learn more.
      if (response.hasPartialFailureError()) {
        GoogleAdsFailure googleAdsFailure =
            ErrorUtils.getInstance().getGoogleAdsFailure(response.getPartialFailureError());
        System.out.printf(
            "Encountered %d partial failure errors while adding %d operations to the offline user "
                + "data job: '%s'. Only the successfully added operations will be executed when "
                + "the job runs.%n",
            googleAdsFailure.getErrorsCount(),
            userDataJobOperations.size(),
            response.getPartialFailureError().getMessage());
      } else {
        System.out.printf(
            "Successfully added %d operations to the offline user data job.%n",
            userDataJobOperations.size());
      }

      if (!runJob) {
        System.out.printf(
            "Not running offline user data job '%s', as requested.%n",
            offlineUserDataJobResourceName);
        return;
      }

      // Issues an asynchronous request to run the offline user data job for executing
      // all added operations.
      offlineUserDataJobServiceClient.runOfflineUserDataJobAsync(offlineUserDataJobResourceName);

      // BEWARE! The above call returns an OperationFuture. The execution of that future depends on
      // the thread pool which is owned by offlineUserDataJobServiceClient. If you use this future,
      // you *must* keep the service client in scope too.
      // See https://developers.google.com/google-ads/api/docs/client-libs/java/lro for more detail.

      // Offline user data jobs may take 6 hours or more to complete, so instead of waiting for the
      // job to complete, retrieves and displays the job status once. If the job is completed
      // successfully, prints information about the user list. Otherwise, prints the query to use
      // to check the job again later.
      checkJobStatus(googleAdsClient, customerId, offlineUserDataJobResourceName);
    }
  }

  /**
   * Creates a list of offline user data job operations that will add users to the list.
   *
   * @return a list of operations.
   */
  private List<OfflineUserDataJobOperation> buildOfflineUserDataJobOperations()
      throws UnsupportedEncodingException {
    MessageDigest sha256Digest;
    try {
      sha256Digest = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("Missing SHA-256 algorithm implementation", e);
    }

    // Creates a raw input list of unhashed user information, where each element of the list
    // represents a single user and is a map containing a separate entry for the keys "email",
    // "phone", "firstName", "lastName", "countryCode", and "postalCode". In your application, this
    // data might come from a file or a database.
    List<Map<String, String>> rawRecords = new ArrayList<>();
    // The first user data has an email address and a phone number.
    Map<String, String> rawRecord1 =
        ImmutableMap.<String, String>builder()
            .put("email", "test@gmail.com")
            // Phone number to be converted to E.164 format, with a leading '+' as required. This
            // includes whitespace that will be removed later.
            .put("phone", "+1 234 5678910")
            .build();
    // The second user data has an email address, a mailing address, and a phone number.
    Map<String, String> rawRecord2 =
        ImmutableMap.<String, String>builder()
            // Email address that includes a period (.) before the Gmail domain.
            .put("email", "test.2@gmail.com")
            // Address that includes all four required elements: first name, last name, country
            // code, and postal code.
            .put("firstName", "John")
            .put("lastName", "Doe")
            .put("countryCode", "US")
            .put("postalCode", "10011")
            // Phone number to be converted to E.164 format, with a leading '+' as required.
            .put("phone", "+1 234 5678911")
            .build();
    // The third user data only has an email address.
    Map<String, String> rawRecord3 =
        ImmutableMap.<String, String>builder().put("email", "test3@gmail.com").build();
    // Adds the raw records to the raw input list.
    rawRecords.add(rawRecord1);
    rawRecords.add(rawRecord2);
    rawRecords.add(rawRecord3);

    // Iterates over the raw input list and creates a UserData object for each record.
    List<UserData> userDataList = new ArrayList<>();
    for (Map<String, String> rawRecord : rawRecords) {
      // Creates a builder for the UserData object that represents a member of the user list.
      UserData.Builder userDataBuilder = UserData.newBuilder();
      // Checks if the record has email, phone, or address information, and adds a SEPARATE
      // UserIdentifier object for each one found. For example, a record with an email address and a
      // phone number will result in a UserData with two UserIdentifiers.

      // IMPORTANT: Since the identifier attribute of UserIdentifier
      // (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) is a
      // oneof
      // (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set only ONE of
      // hashedEmail, hashedPhoneNumber, mobileId, thirdPartyUserId, or addressInfo. Setting more
      // than one of these attributes on the same UserIdentifier will clear all the other members
      // of the oneof. For example, the following code is INCORRECT and will result in a
      // UserIdentifier with ONLY a hashedPhoneNumber.
      //
      // UserIdentifier incorrectlyPopulatedUserIdentifier =
      //     UserIdentifier.newBuilder()
      //         .setHashedEmail("...")
      //         .setHashedPhoneNumber("...")
      //         .build();
      //
      // The separate 'if' statements below demonstrate the correct approach for creating a UserData
      // for a member with multiple UserIdentifiers.

      // Checks if the record has an email address, and if so, adds a UserIdentifier for it.
      if (rawRecord.containsKey("email")) {
        UserIdentifier hashedEmailIdentifier =
            UserIdentifier.newBuilder()
                .setHashedEmail(normalizeAndHash(sha256Digest, rawRecord.get("email"), true))
                .build();
        // Adds the hashed email identifier to the UserData object's list.
        userDataBuilder.addUserIdentifiers(hashedEmailIdentifier);
      }

      // Checks if the record has a phone number, and if so, adds a UserIdentifier for it.
      if (rawRecord.containsKey("phone")) {
        UserIdentifier hashedPhoneNumberIdentifier =
            UserIdentifier.newBuilder()
                .setHashedPhoneNumber(normalizeAndHash(sha256Digest, rawRecord.get("phone"), true))
                .build();
        // Adds the hashed phone number identifier to the UserData object's list.
        userDataBuilder.addUserIdentifiers(hashedPhoneNumberIdentifier);
      }

      // Checks if the record has all the required mailing address elements, and if so, adds a
      // UserIdentifier for the mailing address.
      if (rawRecord.containsKey("firstName")) {
        // Checks if the record contains all the other required elements of a mailing address.
        Set<String> missingAddressKeys = new HashSet<>();
        for (String addressKey : new String[] {"lastName", "countryCode", "postalCode"}) {
          if (!rawRecord.containsKey(addressKey)) {
            missingAddressKeys.add(addressKey);
          }
        }

        if (!missingAddressKeys.isEmpty()) {
          System.out.printf(
              "Skipping addition of mailing address information because the following required keys"
                  + " are missing: %s%n",
              missingAddressKeys);
        } else {
          // Creates an OfflineUserAddressInfo object that contains all the required elements of a
          // mailing address.
          OfflineUserAddressInfo addressInfo =
              OfflineUserAddressInfo.newBuilder()
                  .setHashedFirstName(
                      normalizeAndHash(sha256Digest, rawRecord.get("firstName"), false))
                  .setHashedLastName(
                      normalizeAndHash(sha256Digest, rawRecord.get("lastName"), false))
                  .setCountryCode(rawRecord.get("countryCode"))
                  .setPostalCode(rawRecord.get("postalCode"))
                  .build();
          UserIdentifier addressIdentifier =
              UserIdentifier.newBuilder().setAddressInfo(addressInfo).build();
          // Adds the address identifier to the UserData object's list.
          userDataBuilder.addUserIdentifiers(addressIdentifier);
        }
      }

      if (!userDataBuilder.getUserIdentifiersList().isEmpty()) {
        // Builds the UserData and adds it to the list.
        userDataList.add(userDataBuilder.build());
      }
    }

    // Creates the operations to add users.
    List<OfflineUserDataJobOperation> operations = new ArrayList<>();
    for (UserData userData : userDataList) {
      operations.add(OfflineUserDataJobOperation.newBuilder().setCreate(userData).build());
    }

    return operations;
  }

  /**
   * Returns the result of normalizing and then hashing the string using the provided digest.
   * Private customer data must be hashed during upload, as described at
   * https://support.google.com/google-ads/answer/7474263.
   *
   * @param digest the digest to use to hash the normalized string.
   * @param s the string to normalize and hash.
   * @param trimIntermediateSpaces if true, removes leading, trailing, and intermediate spaces from
   *     the string before hashing. If false, only removes leading and trailing spaces from the
   *     string before hashing.
   */
  private String normalizeAndHash(MessageDigest digest, String s, boolean trimIntermediateSpaces)
      throws UnsupportedEncodingException {
    // Normalizes by first converting all characters to lowercase, then trimming spaces.
    String normalized = s.toLowerCase();
    if (trimIntermediateSpaces) {
      // Removes leading, trailing, and intermediate spaces.
      normalized = normalized.replaceAll("\\s+", "");
    } else {
      // Removes only leading and trailing spaces.
      normalized = normalized.trim();
    }
    // Hashes the normalized string using the hashing algorithm.
    byte[] hash = digest.digest(normalized.getBytes("UTF-8"));
    StringBuilder result = new StringBuilder();
    for (byte b : hash) {
      result.append(String.format("%02x", b));
    }

    return result.toString();
  }

  /**
   * Retrieves, checks, and prints the status of the offline user data job.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param offlineUserDataJobResourceName the resource name of the OfflineUserDataJob to get the
   *     status for.
   */
  private void checkJobStatus(
      GoogleAdsClient googleAdsClient, long customerId, String offlineUserDataJobResourceName) {
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      String query =
          String.format(
              "SELECT offline_user_data_job.resource_name, "
                  + "offline_user_data_job.id, "
                  + "offline_user_data_job.status, "
                  + "offline_user_data_job.type, "
                  + "offline_user_data_job.failure_reason, "
                  + "offline_user_data_job.customer_match_user_list_metadata.user_list "
                  + "FROM offline_user_data_job "
                  + "WHERE offline_user_data_job.resource_name = '%s'",
              offlineUserDataJobResourceName);
      // Issues the query and gets the GoogleAdsRow containing the job from the response.
      GoogleAdsRow googleAdsRow =
          googleAdsServiceClient
              .search(Long.toString(customerId), query)
              .iterateAll()
              .iterator()
              .next();
      OfflineUserDataJob offlineUserDataJob = googleAdsRow.getOfflineUserDataJob();
      System.out.printf(
          "Offline user data job ID %d with type '%s' has status: %s%n",
          offlineUserDataJob.getId(), offlineUserDataJob.getType(), offlineUserDataJob.getStatus());
      OfflineUserDataJobStatus jobStatus = offlineUserDataJob.getStatus();
      if (OfflineUserDataJobStatus.SUCCESS == jobStatus) {
        // Prints information about the user list.
        printCustomerMatchUserListInfo(
            googleAdsClient,
            customerId,
            offlineUserDataJob.getCustomerMatchUserListMetadata().getUserList());
      } else if (OfflineUserDataJobStatus.FAILED == jobStatus) {
        System.out.printf("  Failure reason: %s%n", offlineUserDataJob.getFailureReason());
      } else if (OfflineUserDataJobStatus.PENDING == jobStatus
          || OfflineUserDataJobStatus.RUNNING == jobStatus) {
        System.out.println();
        System.out.printf(
            "To check the status of the job periodically, use the following GAQL query with"
                + " GoogleAdsService.search:%n%s%n",
            query);
      }
    }
  }

  /**
   * Prints information about the Customer Match user list.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID .
   * @param userListResourceName the resource name of the Customer Match user list.
   */
  private void printCustomerMatchUserListInfo(
      GoogleAdsClient googleAdsClient, long customerId, String userListResourceName) {
    try (GoogleAdsServiceClient googleAdsServiceClient =
        googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
      // Creates a query that retrieves the user list.
      String query =
          String.format(
              "SELECT user_list.size_for_display, user_list.size_for_search "
                  + "FROM user_list "
                  + "WHERE user_list.resource_name = '%s'",
              userListResourceName);

      // Constructs the SearchGoogleAdsStreamRequest.
      SearchGoogleAdsStreamRequest request =
          SearchGoogleAdsStreamRequest.newBuilder()
              .setCustomerId(Long.toString(customerId))
              .setQuery(query)
              .build();

      // Issues the search stream request.
      ServerStream<SearchGoogleAdsStreamResponse> stream =
          googleAdsServiceClient.searchStreamCallable().call(request);

      // Gets the first and only row from the response.
      GoogleAdsRow googleAdsRow = stream.iterator().next().getResultsList().get(0);
      UserList userList = googleAdsRow.getUserList();
      System.out.printf(
          "User list '%s' has an estimated %d users for Display and %d users for Search.%n",
          userList.getResourceName(), userList.getSizeForDisplay(), userList.getSizeForSearch());
      System.out.println(
          "Reminder: It may take several hours for the user list to be populated with the users.");
    }
  }
}

      

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.GoogleAds.Lib;
using Google.Ads.GoogleAds.V13.Common;
using Google.Ads.GoogleAds.V13.Errors;
using Google.Ads.GoogleAds.V13.Resources;
using Google.Ads.GoogleAds.V13.Services;
using Google.Api.Gax;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using static Google.Ads.GoogleAds.V13.Enums.CustomerMatchUploadKeyTypeEnum.Types;
using static Google.Ads.GoogleAds.V13.Enums.OfflineUserDataJobStatusEnum.Types;
using static Google.Ads.GoogleAds.V13.Enums.OfflineUserDataJobTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V13
{
    /// <summary>
    /// Creates operations to add members to a user list (a.k.a. audience) using an
    /// OfflineUserDataJob, and if requested, runs the job.
    ///
    /// <p>If a job ID is specified, this example adds operations to that job.
    /// Otherwise, it creates a new job for the operations.</p>
    ///
    /// <p>IMPORTANT: Your application should create a single job containing
    /// <em>all</em> of the operations for a user list. This will be far more efficient
    /// than creating and running multiple jobs that each contain a small set of
    /// operations.</p>
    ///
    ///  Note: It may take up to several hours for the list to be populated with users.
    ///  Email addresses must be associated with a Google account.
    ///  For privacy purposes, the user list size will show as zero until the list has
    ///  at least 1,000 users. After that, the size will be rounded to the two most
    ///  significant digits.
    /// </summary>
    public class AddCustomerMatchUserList : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddCustomerMatchUserList"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the user list is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the user list is added.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// If true, runs the OfflineUserDataJob after adding operations. The default value is
            /// false.
            /// </summary>
            [Option("runJob", Required = false, HelpText =
                "If true, runs the OfflineUserDataJob after adding operations. The default value " +
                "is false.")]
            public bool RunJob { get; set; } = false;

            /// <summary>
            /// The ID of an existing user list. If not specified, this example will create a new
            /// user list.
            /// </summary>
            [Option("userListId", Required = false, HelpText =
                "The ID of an existing user list. If not specified, this example will create a " +
                "new user list.")]
            public long? UserListId { get; set; }

            /// <summary>
            /// The ID of an existing OfflineUserDataJob in the PENDING state. If not specified,
            /// this example will create a new job.
            /// </summary>
            [Option("offlineUserDataJobId", Required = false, HelpText =
                "The ID of an existing OfflineUserDataJob in the PENDING state. If not specified," +
                "this example will create a new job.")]
            public long? OfflineUserDataJobId { 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);

            AddCustomerMatchUserList codeExample = new AddCustomerMatchUserList();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId,
                options.RunJob, options.UserListId, options.OfflineUserDataJobId);
        }

        private static SHA256 digest = SHA256.Create();

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example uses Customer Match to create a new user list (a.k.a. audience) " +
            "and adds users to it. \nNote: It may take up to several hours for the list to be " +
            "populated with users. Email addresses must be associated with a Google account. For " +
            "privacy purposes, the user list size will show as zero until the list has at least " +
            "1,000 users. After that, the size will be rounded to the two most significant digits.";

        /// <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 user list is
        /// added.</param>
        /// <param name="runJob">If true, runs the offlineUserDataJob after adding operations.
        /// </param>
        /// <param name="userListId">The ID of an existing user list.</param>
        /// <param name="offlineUserDataJobId">The ID of an existing OfflineUserDataJob.</param>
        public void Run(GoogleAdsClient client, long customerId, bool runJob,
            long? userListId, long? offlineUserDataJobId)
        {
            try
            {
                string userListResourceName = null;
                if (offlineUserDataJobId == null)
                {
                    if (userListId == null)
                    {
                        userListResourceName = CreateCustomerMatchUserList(client, customerId);
                    }
                    else
                    {
                        userListResourceName = ResourceNames.UserList(customerId, userListId.Value);
                    }
                }

                string offlineUserDataJobResourceName = AddUsersToCustomerMatchUserList(
                    client, customerId, userListResourceName, runJob, offlineUserDataJobId);

                // Since offline user data jobs may take 24 hours or more to complete, you may need
                // to call this function periodically until the job completes.
                if (runJob)
                {
                    CheckJobStatusAndPrintResults(client, customerId,
                        offlineUserDataJobResourceName);
                }
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates the customer match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the user list is added.
        /// </param>
        /// <returns>The resource name of the newly created user list</returns>
        private string CreateCustomerMatchUserList(GoogleAdsClient client, long customerId)
        {
            // Get the UserListService.
            UserListServiceClient service = client.GetService(Services.V13.UserListService);

            // Creates the user list.
            UserList userList = new UserList()
            {
                Name = $"Customer Match list# {ExampleUtilities.GetShortRandomString()}",
                Description = "A list of customers that originated from email and physical" +
                    " addresses",
                // Customer Match user lists can use a membership life span of 10000 to
                // indicate unlimited; otherwise normal values apply.
                // Sets the membership life span to 30 days.
                MembershipLifeSpan = 30,
                CrmBasedUserList = new CrmBasedUserListInfo()
                {
                    UploadKeyType = CustomerMatchUploadKeyType.ContactInfo
                }
            };
            // Creates the user list operation.
            UserListOperation operation = new UserListOperation()
            {
                Create = userList
            };

            // Issues a mutate request to add the user list and prints some information.
            MutateUserListsResponse response = service.MutateUserLists(
                customerId.ToString(), new[] { operation });
            string userListResourceName = response.Results[0].ResourceName;
            Console.WriteLine($"User list with resource name '{userListResourceName}' " +
                $"was created.");
            return userListResourceName;
        }

        /// <summary>
        /// Creates and executes an asynchronous job to add users to the Customer Match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="userListResourceName">The resource name of the Customer Match user list
        /// to add users to</param>
        /// <param name="runJob">If true, runs the offlineUserDataJob after adding operations.
        /// </param>
        /// <param name="offlineUserDataJobId">The ID of an existing OfflineUserDataJob.</param>
        /// <remarks>Resource of the offline user data job.</remarks>
        private static string AddUsersToCustomerMatchUserList(GoogleAdsClient client,
            long customerId, string userListResourceName, bool runJob,
            long? offlineUserDataJobId)
        {
            // Get the OfflineUserDataJobService.
            OfflineUserDataJobServiceClient service = client.GetService(
                Services.V13.OfflineUserDataJobService);

            string offlineUserDataJobResourceName;
            if (offlineUserDataJobId == null)
            {
                // Creates a new offline user data job.
                OfflineUserDataJob offlineUserDataJob = new OfflineUserDataJob()
                {
                    Type = OfflineUserDataJobType.CustomerMatchUserList,
                    CustomerMatchUserListMetadata = new CustomerMatchUserListMetadata()
                    {
                        UserList = userListResourceName
                    }
                };

                // Issues a request to create the offline user data job.
                CreateOfflineUserDataJobResponse response1 = service.CreateOfflineUserDataJob(
                    customerId.ToString(), offlineUserDataJob);
                offlineUserDataJobResourceName = response1.ResourceName;
                Console.WriteLine($"Created an offline user data job with resource name: " +
                    $"'{offlineUserDataJobResourceName}'.");
            } else {
                // Reuses the specified offline user data job.
                offlineUserDataJobResourceName =
                    ResourceNames.OfflineUserDataJob(customerId, offlineUserDataJobId.Value);
            }

            AddOfflineUserDataJobOperationsRequest request =
                new AddOfflineUserDataJobOperationsRequest()
                {
                    ResourceName = offlineUserDataJobResourceName,
                    Operations = { BuildOfflineUserDataJobOperations() },
                    EnablePartialFailure = true,
                };
            // Issues a request to add the operations to the offline user data job. This example
            // only adds a few operations, so it only sends one AddOfflineUserDataJobOperations
            // request.
            // If your application is adding a large number of operations, split the operations into
            // batches and send multiple AddOfflineUserDataJobOperations requests for the SAME job.
            // See https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
            // and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
            // for more information on the per-request limits.
            AddOfflineUserDataJobOperationsResponse response2 =
                service.AddOfflineUserDataJobOperations(request);

            // Prints the status message if any partial failure error is returned.
            // Note: The details of each partial failure error are not printed here,
            // you can refer to the example HandlePartialFailure.cs to learn more.
            if (response2.PartialFailureError != null)
            {
                // Extracts the partial failure from the response status.
                GoogleAdsFailure partialFailure = response2.PartialFailure;
                Console.WriteLine($"{partialFailure.Errors.Count} partial failure error(s) " +
                    $"occurred");
            }
            Console.WriteLine("The operations are added to the offline user data job.");

            if (!runJob)
            {
                Console.WriteLine($"Not running offline user data job " +
                    "'{offlineUserDataJobResourceName}', as requested.");
                return offlineUserDataJobResourceName;
            }

            // Issues an asynchronous request to run the offline user data job for executing
            // all added operations.
            Operation<Empty, OfflineUserDataJobMetadata> operationResponse =
                service.RunOfflineUserDataJob(offlineUserDataJobResourceName);

            Console.WriteLine("Asynchronous request to execute the added operations started.");

            // Since offline user data jobs may take 24 hours or more to complete, it may not be
            // practical to do operationResponse.PollUntilCompleted() to wait for the results.
            // Instead, we save the offlineUserDataJobResourceName and use GoogleAdsService.Search
            // to check for the job status periodically.
            // In case you wish to follow the PollUntilCompleted or PollOnce approach, make sure
            // you keep both operationResponse and service variables alive until the polling
            // completes.

            return offlineUserDataJobResourceName;
        }

        /// <summary>
        /// Retrieves, checks, and prints the status of the offline user data job.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="offlineUserDataJobResourceName">Resource name of the of the offline user
        /// data job.</param>
        private static void CheckJobStatusAndPrintResults(GoogleAdsClient client, long customerId,
            string offlineUserDataJobResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient service = client.GetService(Services.V13.GoogleAdsService);

            string query = "SELECT offline_user_data_job.resource_name, " +
                "offline_user_data_job.id, offline_user_data_job.status, " +
                "offline_user_data_job.type, offline_user_data_job.failure_reason " +
                "offline_user_data_job.customer_match_user_list_metadata_user_list " +
                "FROM offline_user_data_job WHERE " +
                $"offline_user_data_job.resource_name = '{offlineUserDataJobResourceName}'";

            // Issues the query and gets the GoogleAdsRow containing the job from the response.
            GoogleAdsRow googleAdsRow = service.Search(customerId.ToString(), query).First();

            OfflineUserDataJob offlineUserDataJob = googleAdsRow.OfflineUserDataJob;
            Console.WriteLine($"Offline user data job ID {offlineUserDataJob.Id} with type " +
                $"'{offlineUserDataJob.Type}' has status: {offlineUserDataJob.Status}");

            switch (offlineUserDataJob.Status)
            {
                case OfflineUserDataJobStatus.Success:
                    // Prints information about the user list.
                    PrintCustomerMatchUserListInfo(client, customerId,
                        offlineUserDataJob.CustomerMatchUserListMetadata.UserList);
                    break;

                case OfflineUserDataJobStatus.Failed:
                    Console.WriteLine($"  Failure reason: {offlineUserDataJob.FailureReason}");
                    break;

                case OfflineUserDataJobStatus.Pending:
                case OfflineUserDataJobStatus.Running:
                    Console.WriteLine("To check the status of the job periodically, use the " +
                        $"following GAQL query with GoogleAdsService.search:\n\n{query}");
                    break;
            }
        }

        /// <summary>
        /// Builds and returns offline user data job operations to add one user identified by an
        /// email address and one user identified based on a physical address.
        /// </summary>
        /// <returns>An array with the operations</returns>
        private static OfflineUserDataJobOperation[] BuildOfflineUserDataJobOperations()
        {

            // Creates a raw input list of unhashed user information, where each element of the list
            // represents a single user and is a map containing a separate entry for the keys
            // "email", "phone", "firstName", "lastName", "countryCode", and "postalCode".
            // In your application, this data might come from a file or a database.
            List<Dictionary<string, string>> rawRecords = new List<Dictionary<string, string>>();

            // The first user data has an email address and a phone number.
            Dictionary<string, string> rawRecord1 = new Dictionary<string, string>();
            rawRecord1.Add("email", "test@gmail.com");
            // Phone number to be converted to E.164 format, with a leading '+' as required.
            // This includes whitespace that will be removed later.
            rawRecord1.Add("phone", "+1 234 5678910");

            // The second user data has an email address, a mailing address, and a phone number.
            Dictionary<string, string> rawRecord2 = new Dictionary<string, string>();
            // Email address that includes a period (.) before the Gmail domain.
            rawRecord2.Add("email", "test.2@gmail.com");
            // Address that includes all four required elements: first name, last name, country
            // code, and postal code.
            rawRecord2.Add("firstName", "John");
            rawRecord2.Add("lastName", "Doe");
            rawRecord2.Add("countryCode", "US");
            rawRecord2.Add("postalCode", "10011");
            // Phone number to be converted to E.164 format, with a leading '+' as required.
            // This includes whitespace that will be removed later.
            rawRecord2.Add("phone", "+1 234 5678911");

            // The third user data only has an email address.
            Dictionary<string, string> rawRecord3 = new Dictionary<string, string>();
            rawRecord3.Add("email", "test3@gmail.com");

            // Adds the raw records to the raw input list.
            rawRecords.Add(rawRecord1);
            rawRecords.Add(rawRecord2);
            rawRecords.Add(rawRecord3);

            // Iterates over the raw input list and creates a UserData object for each record.
            List<UserData> userDataList = new List<UserData>();
            foreach (Dictionary<string, string> rawRecord in rawRecords) {
                // Creates a UserData object that represents a member of the user list.
                UserData userData = new UserData();
                // Checks if the record has email, phone, or address information, and adds a
                // SEPARATE UserIdentifier object for each one found.
                // For example, a record with an email address and a phone number will result in a
                // UserData with two UserIdentifiers.

                // IMPORTANT: Since the identifier attribute of UserIdentifier
                // (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier)
                // is a oneof
                // (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set
                // only ONE of hashedEmail, hashedPhoneNumber, mobileId, thirdPartyUserId,
                // or addressInfo.
                // Setting more than one of these attributes on the same UserIdentifier will clear
                // all the other members of the oneof.
                // For example, the following code is INCORRECT and will result in a UserIdentifier
                // with ONLY a hashedPhoneNumber.
                //
                // UserIdentifier incorrectlyPopulatedUserIdentifier = new UserIdentifier()
                // {
                //      HashedEmail = "...",
                //      HashedPhoneNumber = "..."
                // };
                //
                // The separate 'if' statements below demonstrate the correct approach for creating
                // a UserData for a member with multiple UserIdentifiers.

                // Checks if the record has an email address, and if so, adds a UserIdentifier
                // for it.
                if (rawRecord.ContainsKey("email")) {
                    UserIdentifier hashedEmailIdentifier = new UserIdentifier()
                    {
                        HashedEmail = NormalizeAndHash(rawRecord["email"], true)
                    };

                    userData.UserIdentifiers.Add(hashedEmailIdentifier);
                }

                // Checks if the record has a phone number, and if so, adds a UserIdentifier for it.
                if (rawRecord.ContainsKey("phone")) {
                    UserIdentifier hashedPhoneNumberIdentifier = new UserIdentifier()
                    {
                        HashedPhoneNumber = NormalizeAndHash(rawRecord["phone"], true)
                    };

                    // Adds the hashed phone number identifier to the UserData object's list.
                    userData.UserIdentifiers.Add(hashedPhoneNumberIdentifier);
                }

                // Checks if the record has all the required mailing address elements, and if so,
                // adds a UserIdentifier for the mailing address.
                if (rawRecord.ContainsKey("firstName")) {
                    // Checks if the record contains all the other required elements of a mailing
                    // address.
                    HashSet<string> missingAddressKeys = new HashSet<string>();
                    foreach (string addressKey in new string[] {"lastName", "countryCode",
                        "postalCode"}) {
                    if (!rawRecord.ContainsKey(addressKey)) {
                        missingAddressKeys.Add(addressKey);
                    }
                    }

                    if (!missingAddressKeys.Any()) {
                    Console.WriteLine(
                        $"Skipping addition of mailing address information because the following " +
                            "required keys are missing: {missingAddressKeys}");
                    } else {
                        // Creates an OfflineUserAddressInfo object that contains all the required
                        // elements of a mailing address.
                        OfflineUserAddressInfo addressInfo = new OfflineUserAddressInfo()
                        {
                            HashedFirstName = NormalizeAndHash(rawRecord["firstName"]),
                            HashedLastName = NormalizeAndHash(rawRecord["lastName"]),
                            CountryCode = rawRecord["countryCode"],
                            PostalCode = rawRecord["postalCode"]
                        };

                        UserIdentifier addressIdentifier = new UserIdentifier()
                        {
                            AddressInfo = addressInfo
                        };

                        // Adds the address identifier to the UserData object's list.
                        userData.UserIdentifiers.Add(addressIdentifier);
                    }
                }

                if (userData.UserIdentifiers.Any())
                {
                    userDataList.Add(userData);
                }
            }

            // Creates the operations to add the users.
            List<OfflineUserDataJobOperation> operations = new List<OfflineUserDataJobOperation>();
            foreach(UserData userData in userDataList)
            {
                operations.Add(new OfflineUserDataJobOperation()
                {
                    Create = userData
                });
            }
            return operations.ToArray();
        }

        /// <summary>
        /// Prints information about the Customer Match user list.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which calls are made.
        /// </param>
        /// <param name="userListResourceName">The resource name of the Customer Match user list
        /// to print information about.</param>
        private static void PrintCustomerMatchUserListInfo(GoogleAdsClient client, long customerId,
            string userListResourceName)
        {
            // Get the GoogleAdsService.
            GoogleAdsServiceClient service =
                client.GetService(Services.V13.GoogleAdsService);

            // Creates a query that retrieves the user list.
            string query =
                "SELECT user_list.size_for_display, user_list.size_for_search " +
                "FROM user_list " +
                $"WHERE user_list.resource_name = '{userListResourceName}'";
            // Issues a search stream request.
            service.SearchStream(customerId.ToString(), query,
               delegate (SearchGoogleAdsStreamResponse resp)
               {
                   // Display the results.
                   foreach (GoogleAdsRow userListRow in resp.Results)
                   {
                       UserList userList = userListRow.UserList;
                       Console.WriteLine("The estimated number of users that the user list " +
                           $"'{userList.ResourceName}' has is {userList.SizeForDisplay}" +
                           $" for Display and {userList.SizeForSearch} for Search.");
                   }
               }
           );

            Console.WriteLine("Reminder: It may take several hours for the user list to be " +
                "populated with the users so getting zeros for the estimations is expected.");
        }

        /// <summary>
        /// Normalizes and hashes a string value.
        /// </summary>
        /// <param name="value">The value to normalize and hash.</param>
        /// <param name="trimIntermediateSpaces">If true, removes leading, trailing and intermediate
        /// spaces from the string before hashing. Otherwise, only removes leading and trailing
        /// spaces before hashing.</param>
        /// <returns>The normalized and hashed value.</returns>
        private static string NormalizeAndHash(string value, bool trimIntermediateSpaces = false)
        {
            string normalized;
            if (trimIntermediateSpaces)
            {
                normalized = value.Replace(" ", "").ToLower();
            }
            else
            {
                normalized = ToNormalizedValue(value);
            }
            return ToSha256String(digest, normalized);
        }

        /// <summary>
        /// Hash a string value using SHA-256 hashing algorithm.
        /// </summary>
        /// <param name="digest">Provides the algorithm for SHA-256.</param>
        /// <param name="value">The string value (e.g. an email address) to hash.</param>
        /// <returns>The hashed value.</returns>
        private static string ToSha256String(SHA256 digest, string value)
        {
            byte[] digestBytes = digest.ComputeHash(Encoding.UTF8.GetBytes(value));
            // Convert the byte array into an unhyphenated hexadecimal string.
            return BitConverter.ToString(digestBytes).Replace("-", string.Empty);
        }

        /// <summary>
        /// Removes leading and trailing whitespace and converts all characters to
        /// lower case.
        /// </summary>
        /// <param name="value">The value to normalize.</param>
        /// <returns>The normalized value.</returns>
        private static string ToNormalizedValue(string value)
        {
            return value.Trim().ToLower();
        }
    }
}

      

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\Remarketing;

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\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V13\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\V13\GoogleAdsServerStreamDecorator;
use Google\Ads\GoogleAds\Util\V13\GoogleAdsFailures;
use Google\Ads\GoogleAds\Util\V13\ResourceNames;
use Google\Ads\GoogleAds\V13\Common\CrmBasedUserListInfo;
use Google\Ads\GoogleAds\V13\Common\CustomerMatchUserListMetadata;
use Google\Ads\GoogleAds\V13\Common\OfflineUserAddressInfo;
use Google\Ads\GoogleAds\V13\Common\UserData;
use Google\Ads\GoogleAds\V13\Common\UserIdentifier;
use Google\Ads\GoogleAds\V13\Enums\CustomerMatchUploadKeyTypeEnum\CustomerMatchUploadKeyType;
use Google\Ads\GoogleAds\V13\Enums\OfflineUserDataJobStatusEnum\OfflineUserDataJobStatus;
use Google\Ads\GoogleAds\V13\Enums\OfflineUserDataJobTypeEnum\OfflineUserDataJobType;
use Google\Ads\GoogleAds\V13\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V13\Resources\OfflineUserDataJob;
use Google\Ads\GoogleAds\V13\Resources\UserList;
use Google\Ads\GoogleAds\V13\Services\AddOfflineUserDataJobOperationsResponse;
use Google\Ads\GoogleAds\V13\Services\CreateOfflineUserDataJobResponse;
use Google\Ads\GoogleAds\V13\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V13\Services\OfflineUserDataJobOperation;
use Google\Ads\GoogleAds\V13\Services\UserListOperation;
use Google\ApiCore\ApiException;

/**
 * Creates operations to add members to a user list (a.k.a. audience) using an OfflineUserDataJob,
 * and if requested, runs the job.
 *
 * If a job ID is specified, this example adds operations to that job. Otherwise, it creates a
 * new job for the operations.
 *
 * IMPORTANT: Your application should create a single job containing all of the operations for a
 * user list. This will be far more efficient than creating and running multiple jobs that each
 * contain a small set of operations.
 *
 * Note:
 * - This feature is only available to accounts that meet the requirements described at
 *   https://support.google.com/adspolicy/answer/6299717.
 * - It may take up to several hours for the list to be populated with users.
 * - Email addresses must be associated with a Google account.
 * - For privacy purposes, the user list size will show as zero until the list has
 *   at least 1,000 users. After that, the size will be rounded to the two most
 *   significant digits.
 */
class AddCustomerMatchUserList
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Optional: The ID of an existing user list. If not specified, this example will create a new
    // user list.
    private const USER_LIST_ID = null;
    // Optional: The ID of an existing offline user data job in the PENDING state. If not specified,
    // this example will create a new job.
    private const OFFLINE_USER_DATA_JOB_ID = null;
    // Optional: If true, runs the offline user data job after adding operations. The default value
    // is false.
    private const RUN_JOB = false;

    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::RUN_JOB => GetOpt::OPTIONAL_ARGUMENT,
            ArgumentNames::USER_LIST_ID => GetOpt::OPTIONAL_ARGUMENT,
            ArgumentNames::OFFLINE_USER_DATA_JOB_ID => GetOpt::OPTIONAL_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)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                filter_var(
                    $options[ArgumentNames::RUN_JOB] ?: self::RUN_JOB,
                    FILTER_VALIDATE_BOOLEAN
                ),
                $options[ArgumentNames::USER_LIST_ID] ?: self::USER_LIST_ID,
                $options[ArgumentNames::OFFLINE_USER_DATA_JOB_ID] ?: self::OFFLINE_USER_DATA_JOB_ID
            );
        } 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 bool $runJob if true, run the offline user data job after adding operations.
     *     Otherwise, only adds operations to the job
     * @param int|null $userListId optional ID of an existing user list. If `null`, creates a new
     *     user list
     * @param int|null $offlineUserDataJobId optional ID of an existing OfflineUserDataJob in the
     *     PENDING state. If `null`, create a new job
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        bool $runJob,
        ?int $userListId,
        ?int $offlineUserDataJobId
    ) {
        $userListResourceName = null;
        if (is_null($offlineUserDataJobId)) {
            if (is_null($userListId)) {
                // Creates a Customer Match user list.
                $userListResourceName =
                    self::createCustomerMatchUserList($googleAdsClient, $customerId);
            } else {
                // Uses the specified Customer Match user list.
                $userListResourceName = ResourceNames::forUserList($customerId, $userListId);
            }
        }
        self::addUsersToCustomerMatchUserList(
            $googleAdsClient,
            $customerId,
            $runJob,
            $userListResourceName,
            $offlineUserDataJobId
        );
    }

    /**
     * Creates a Customer Match user list.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the resource name of the newly created user list
     */
    private static function createCustomerMatchUserList(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ): string {
        // Creates the user list.
        $userList = new UserList([
            'name' => 'Customer Match list #' . Helper::getPrintableDatetime(),
            'description' => 'A list of customers that originated from email '
                . 'and physical addresses',
            // Customer Match user lists can use a membership life span of 10000 to
            // indicate unlimited; otherwise normal values apply.
            // Sets the membership life span to 30 days.
            'membership_life_span' => 30,
            'crm_based_user_list' => new CrmBasedUserListInfo([
                // Sets the upload key type to indicate the type of identifier that will be used to
                // add users to the list. This field is immutable and required for a CREATE
                // operation.
                'upload_key_type' => CustomerMatchUploadKeyType::CONTACT_INFO
            ])
        ]);

        // Creates the user list operation.
        $operation = new UserListOperation();
        $operation->setCreate($userList);

        // Issues a mutate request to add the user list and prints some information.
        $userListServiceClient = $googleAdsClient->getUserListServiceClient();
        $response = $userListServiceClient->mutateUserLists($customerId, [$operation]);
        $userListResourceName = $response->getResults()[0]->getResourceName();
        printf("User list with resource name '%s' was created.%s", $userListResourceName, PHP_EOL);

        return $userListResourceName;
    }

    /**
     * Creates and executes an asynchronous job to add users to the Customer Match user list.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param bool $runJob if true, run the offline user data job after adding operations.
     *     Otherwise, only adds operations to the job
     * @param int|null $userListId optional ID of an existing user list. If `null`, creates a new
     *     user list
     * @param int|null $offlineUserDataJobId optional ID of an existing OfflineUserDataJob in the
     *     PENDING state. If `null`, create a new job
     */
    private static function addUsersToCustomerMatchUserList(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        bool $runJob,
        ?string $userListResourceName,
        ?int $offlineUserDataJobId
    ) {
        $offlineUserDataJobResourceName = null;
        $offlineUserDataJobServiceClient =
            $googleAdsClient->getOfflineUserDataJobServiceClient();

        if (is_null($offlineUserDataJobId)) {
            // Creates a new offline user data job.
            $offlineUserDataJob = new OfflineUserDataJob([
                'type' => OfflineUserDataJobType::CUSTOMER_MATCH_USER_LIST,
                'customer_match_user_list_metadata' => new CustomerMatchUserListMetadata([
                    'user_list' => $userListResourceName
                ])
            ]);

            // Issues a request to create the offline user data job.
            /** @var CreateOfflineUserDataJobResponse $createOfflineUserDataJobResponse */
            $createOfflineUserDataJobResponse =
                $offlineUserDataJobServiceClient->createOfflineUserDataJob(
                    $customerId,
                    $offlineUserDataJob
                );
            $offlineUserDataJobResourceName = $createOfflineUserDataJobResponse->getResourceName();
            printf(
                "Created an offline user data job with resource name: '%s'.%s",
                $offlineUserDataJobResourceName,
                PHP_EOL
            );
        } else {
            // Reuses the specified offline user data job.
            $offlineUserDataJobResourceName =
                ResourceNames::forOfflineUserDataJob($customerId, $offlineUserDataJobId);
        }

        // Issues a request to add the operations to the offline user data job. This example
        // only adds a few operations, so it only sends one AddOfflineUserDataJobOperations request.
        // If your application is adding a large number of operations, split the operations into
        // batches and send multiple AddOfflineUserDataJobOperations requests for the SAME job. See
        // https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
        // and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
        // for more information on the per-request limits.
        /** @var AddOfflineUserDataJobOperationsResponse $operationResponse */
        $response = $offlineUserDataJobServiceClient->addOfflineUserDataJobOperations(
            $offlineUserDataJobResourceName,
            self::buildOfflineUserDataJobOperations(),
            ['enablePartialFailure' => true]
        );

        // Prints the status message if any partial failure error is returned.
        // Note: The details of each partial failure error are not printed here, you can refer to
        // the example HandlePartialFailure.php to learn more.
        if ($response->hasPartialFailureError()) {
            // Extracts the partial failure from the response status.
            $partialFailure = GoogleAdsFailures::fromAny(
                $response->getPartialFailureError()->getDetails()->getIterator()->current()
            );
            printf(
                "%d partial failure error(s) occurred: %s.%s",
                count($partialFailure->getErrors()),
                $response->getPartialFailureError()->getMessage(),
                PHP_EOL
            );
        } else {
            print 'The operations are added to the offline user data job.' . PHP_EOL;
        }

        if ($runJob === false) {
            printf(
                "Not running offline user data job '%s', as requested.%s",
                $offlineUserDataJobResourceName,
                PHP_EOL
            );
            return;
        }

        // Issues an asynchronous request to run the offline user data job for executing all added
        // operations. The result is OperationResponse. Visit the OperationResponse.php file for
        // more details.
        $offlineUserDataJobServiceClient->runOfflineUserDataJob($offlineUserDataJobResourceName);

        // Offline user data jobs may take 6 hours or more to complete, so instead of waiting
        // for the job to complete, retrieves and displays the job status once. If the job is
        // completed successfully, prints information about the user list. Otherwise, prints the
        // query to use to check the job again later.
        self::checkJobStatus($googleAdsClient, $customerId, $offlineUserDataJobResourceName);
    }

    /**
     * Builds and returns offline user data job operations to add one user identified by an
     * email address and one user identified based on a physical address.
     *
     * @return OfflineUserDataJobOperation[] an array with the operations
     */
    private static function buildOfflineUserDataJobOperations(): array
    {
        // Creates a raw input list of unhashed user information, where each element of the list
        // represents a single user and is a map containing a separate entry for the keys 'email',
        // 'phone', 'firstName', 'lastName', 'countryCode', and 'postalCode'. In your application,
        // this data might come from a file or a database.
        $rawRecords = [];
        // The first user data has an email address and a phone number.
        $rawRecord1 = [
            // The first user data has an email address and a phone number.
            'email' => 'dana@example.com',
            // Phone number to be converted to E.164 format, with a leading '+' as required. This
            // includes whitespace that will be removed later.
            'phone' => '+1 800 5550101'
        ];
        $rawRecords[] = $rawRecord1;

        // The second user data has an email address, a mailing address, and a phone number.
        $rawRecord2 = [
            // Email address that includes a period (.) before the Gmail domain.
            'email' => 'alex.2@example.com',
            // Address that includes all four required elements: first name, last name, country
            // code, and postal code.
            'firstName' => 'Alex',
            'lastName' => 'Quinn',
            'countryCode' => 'US',
            'postalCode' => '94045',
            // Phone number to be converted to E.164 format, with a leading '+' as required.
            'phone' => '+1 800 5550102',
        ];
        $rawRecords[] = $rawRecord2;

        // The third user data only has an email address.
        $rawRecord3 = ['email' => 'charlie@example.com'];
        $rawRecords[] = $rawRecord3;

        // Iterates over the raw input list and creates a UserData object for each record.
        $userDataList = [];
        foreach ($rawRecords as $rawRecord) {
            // Checks if the record has email, phone, or address information, and adds a SEPARATE
            // UserIdentifier object for each one found. For example, a record with an email address
            // and a phone number will result in a UserData with two UserIdentifiers.

            // IMPORTANT: Since the identifier attribute of UserIdentifier
            // (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier) is
            // a oneof
            // (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set only
            // ONE of 'hashed_email, 'hashed_phone_number', 'mobile_id', 'third_party_user_id', or
            // 'address_info'.
            // Setting more than one of these attributes on the same UserIdentifier will clear all
            // the other members of the oneof. For example, the following code is INCORRECT and will
            // result in a UserIdentifier with ONLY a 'hashed_phone_number'.
            //
            // $incorrectlyPopulatedUserIdentifier = new UserIdentifier();
            // $incorrectlyPopulatedUserIdentifier->setHashedEmail('...');
            // $incorrectlyPopulatedUserIdentifier->setHashedPhoneNumber('...');
            //
            // The separate 'if' statements below demonstrate the correct approach for creating a
            // UserData for a member with multiple UserIdentifiers.

            $userIdentifiers = [];
            // Checks if the record has an email address, and if so, adds a UserIdentifier for it.
            if (array_key_exists('email', $rawRecord)) {
                $hashedEmailIdentifier = new UserIdentifier([
                    'hashed_email' => self::normalizeAndHash($rawRecord['email'], true)
                ]);
                // Adds the hashed email identifier to the user identifiers list.
                $userIdentifiers[] = $hashedEmailIdentifier;
            }

            // Checks if the record has a phone number, and if so, adds a UserIdentifier for it.
            if (array_key_exists('phone', $rawRecord)) {
                $hashedPhoneNumberIdentifier = new UserIdentifier([
                    'hashed_phone_number' => self::normalizeAndHash($rawRecord['phone'], true)
                ]);
                // Adds the hashed email identifier to the user identifiers list.
                $userIdentifiers[] = $hashedPhoneNumberIdentifier;
            }

            // Checks if the record has all the required mailing address elements, and if so, adds a
            // UserIdentifier for the mailing address.
            if (array_key_exists('firstName', $rawRecord)) {
                // Checks if the record contains all the other required elements of a mailing
                // address.
                $missingAddressKeys = [];
                foreach (['lastName', 'countryCode', 'postalCode'] as $addressKey) {
                    if (!array_key_exists($addressKey, $rawRecord)) {
                        $missingAddressKeys[] = $addressKey;
                    }
                }
                if (!empty($missingAddressKeys)) {
                    printf(
                        "Skipping addition of mailing address information because the "
                        . "following required keys are missing: %s%s",
                        json_encode($missingAddressKeys),
                        PHP_EOL
                    );
                } else {
                    // Creates an OfflineUserAddressInfo object that contains all the required
                    // elements of a mailing address.
                    $addressIdentifier = new UserIdentifier([
                       'address_info' => new OfflineUserAddressInfo([
                           'hashed_first_name' => self::normalizeAndHash(
                               $rawRecord['firstName'],
                               false
                           ),
                           'hashed_last_name' => self::normalizeAndHash(
                               $rawRecord['lastName'],
                               false
                           ),
                           'country_code' => $rawRecord['countryCode'],
                           'postal_code' => $rawRecord['postalCode']
                       ])
                    ]);
                    // Adds the address identifier to the user identifiers list.
                    $userIdentifiers[] = $addressIdentifier;
                }
            }
            if (!empty($userIdentifiers)) {
                // Builds the UserData and adds it to the list.
                $userDataList[] = new UserData(['user_identifiers' => $userIdentifiers]);
            }
        }

        // Creates the operations to add users.
        $operations = array_map(
            function (UserData $userData) {
                return new OfflineUserDataJobOperation(['create' => $userData]);
            },
            $userDataList
        );
        return $operations;
    }

    /**
     * Retrieves, checks, and prints the status of the offline user data job.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $offlineUserDataJobResourceName the resource name of the offline user data job
     *     to get the status for
     */
    private static function checkJobStatus(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $offlineUserDataJobResourceName
    ) {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();

        // Creates a query that retrieves the offline user data job.
        $query = "SELECT offline_user_data_job.resource_name, "
              . "offline_user_data_job.id, "
              . "offline_user_data_job.status, "
              . "offline_user_data_job.type, "
              . "offline_user_data_job.failure_reason, "
              . "offline_user_data_job.customer_match_user_list_metadata.user_list "
              . "FROM offline_user_data_job "
              . "WHERE offline_user_data_job.resource_name = '$offlineUserDataJobResourceName'";

        // Issues a search request to get the GoogleAdsRow containing the job from the response.
        /** @var GoogleAdsRow $googleAdsRow */
        $googleAdsRow =
            $googleAdsServiceClient->search($customerId, $query)->getIterator()->current();
        $offlineUserDataJob = $googleAdsRow->getOfflineUserDataJob();

        // Prints out some information about the offline user data job.
        $offlineUserDataJobStatus = $offlineUserDataJob->getStatus();
        printf(
            "Offline user data job ID %d with type '%s' has status: %s.%s",
            $offlineUserDataJob->getId(),
            OfflineUserDataJobType::name($offlineUserDataJob->getType()),
            OfflineUserDataJobStatus::name($offlineUserDataJobStatus),
            PHP_EOL
        );

        if ($offlineUserDataJobStatus === OfflineUserDataJobStatus::SUCCESS) {
            // Prints information about the user list.
            self::printCustomerMatchUserListInfo(
                $googleAdsClient,
                $customerId,
                $offlineUserDataJob->getCustomerMatchUserListMetadata()->getUserList()
            );
        } elseif ($offlineUserDataJobStatus === OfflineUserDataJobStatus::FAILED) {
            printf("  Failure reason: %s.%s", $offlineUserDataJob->getFailureReason(), PHP_EOL);
        } elseif (
            $offlineUserDataJobStatus === OfflineUserDataJobStatus::PENDING
            || $offlineUserDataJobStatus === OfflineUserDataJobStatus::RUNNING
        ) {
            printf(
                '%1$sTo check the status of the job periodically, use the following GAQL query with'
                . ' GoogleAdsService.search:%1$s%2$s%1$s',
                PHP_EOL,
                $query
            );
        }
    }

    /**
     * Prints information about the Customer Match user list.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $userListResourceName the resource name of the Customer Match user list to
     *     print information about
     */
    private static function printCustomerMatchUserListInfo(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $userListResourceName
    ) {
        $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();

        // Creates a query that retrieves the user list.
        $query =
            "SELECT user_list.size_for_display, user_list.size_for_search " .
            "FROM user_list " .
            "WHERE user_list.resource_name = '$userListResourceName'";

        // Issues a search stream request.
        /** @var GoogleAdsServerStreamDecorator $stream */
        $stream = $googleAdsServiceClient->searchStream($customerId, $query);

        // Prints out some information about the user list.
        /** @var GoogleAdsRow $googleAdsRow */
        $googleAdsRow = $stream->iterateAllElements()->current();
        printf(
            "The estimated number of users that the user list '%s' has is %d for Display " .
             "and %d for Search.%s",
            $googleAdsRow->getUserList()->getResourceName(),
            $googleAdsRow->getUserList()->getSizeForDisplay(),
            $googleAdsRow->getUserList()->getSizeForSearch(),
            PHP_EOL
        );
        print 'Reminder: It may take several hours for the user list to be populated with the ' .
            'users so getting zeros for the estimations is expected.' . PHP_EOL;
    }

    /**
     * Normalizes and hashes a string value.
     *
     * @param string $value the value to normalize and hash
     * @param bool $trimIntermediateSpaces if true, removes leading, trailing, and intermediate
     *     spaces from the string before hashing. If false, only removes leading and trailing
     *     spaces from the string before hashing.
     * @return string the normalized and hashed value
     */
    private static function normalizeAndHash(string $value, bool $trimIntermediateSpaces): string
    {
        // Normalizes by first converting all characters to lowercase, then trimming spaces.
        $normalized = strtolower($value);
        if ($trimIntermediateSpaces === true) {
            // Removes leading, trailing, and intermediate spaces.
            $normalized = str_replace(' ', '', $normalized);
        } else {
            // Removes only leading and trailing spaces.
            $normalized = trim($normalized);
        }
        return hash('sha256', $normalized);
    }
}

AddCustomerMatchUserList::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.
"""Creates operations to add members to a user list (a.k.a. audience).

The example uses an OfflineUserDataJob, and if requested, runs the job. If a
job ID is specified, the example adds operations to that job. Otherwise, it
creates a new job for the operations.

IMPORTANT: Your application should create a single job containing all of the
operations for a user list. This will be far more efficient than creating and
running multiple jobs that each contain a small set of operations.

This feature is only available to accounts that meet the requirements described
at: https://support.google.com/adspolicy/answer/6299717.
"""

import argparse
import hashlib
import sys
import uuid

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


def main(client, customer_id, run_job, user_list_id, offline_user_data_job_id):
    """Uses Customer Match to create and add users to a new user list.

    Args:
        client: The Google Ads client.
        customer_id: The ID for the customer that owns the user list.
        run_job: if True, runs the OfflineUserDataJob after adding operations.
            Otherwise, only adds operations to the job.
        user_list_id: ID of an existing user list. If None, a new user list is
            created.
        offline_user_data_job_id: ID of an existing OfflineUserDataJob in the
            PENDING state. If None, a new job is created.
    """
    googleads_service = client.get_service("GoogleAdsService")

    if not offline_user_data_job_id:
        if user_list_id:
            # Uses the specified Customer Match user list.
            user_list_resource_name = googleads_service.user_list_path(
                customer_id, user_list_id
            )
        else:
            # Creates a Customer Match user list.
            user_list_resource_name = create_customer_match_user_list(
                client, customer_id
            )

    add_users_to_customer_match_user_list(
        client,
        customer_id,
        user_list_resource_name,
        run_job,
        offline_user_data_job_id,
    )


def create_customer_match_user_list(client, customer_id):
    """Creates a Customer Match user list.

    Args:
        client: The Google Ads client.
        customer_id: The ID for the customer that owns the user list.

    Returns:
        The string resource name of the newly created user list.
    """
    # Creates the UserListService client.
    user_list_service_client = client.get_service("UserListService")

    # Creates the user list operation.
    user_list_operation = client.get_type("UserListOperation")

    # Creates the new user list.
    user_list = user_list_operation.create
    user_list.name = f"Customer Match list #{uuid.uuid4()}"
    user_list.description = (
        "A list of customers that originated from email and physical addresses"
    )
    # Sets the upload key type to indicate the type of identifier that is used
    # to add users to the list. This field is immutable and required for a
    # CREATE operation.
    user_list.crm_based_user_list.upload_key_type = (
        client.enums.CustomerMatchUploadKeyTypeEnum.CONTACT_INFO
    )
    # Customer Match user lists can set an unlimited membership life span;
    # to do so, use the special life span value 10000. Otherwise, membership
    # life span must be between 0 and 540 days inclusive. See:
    # https://developers.devsite.corp.google.com/google-ads/api/reference/rpc/latest/UserList#membership_life_span
    # Sets the membership life span to 30 days.
    user_list.membership_life_span = 30

    response = user_list_service_client.mutate_user_lists(
        customer_id=customer_id, operations=[user_list_operation]
    )
    user_list_resource_name = response.results[0].resource_name
    print(
        f"User list with resource name '{user_list_resource_name}' was created."
    )

    return user_list_resource_name


def add_users_to_customer_match_user_list(
    client,
    customer_id,
    user_list_resource_name,
    run_job,
    offline_user_data_job_id,
):
    """Uses Customer Match to create and add users to a new user list.

    Args:
        client: The Google Ads client.
        customer_id: The ID for the customer that owns the user list.
        user_list_resource_name: The resource name of the user list to which to
            add users.
        run_job: If true, runs the OfflineUserDataJob after adding operations.
            Otherwise, only adds operations to the job.
        offline_user_data_job_id: ID of an existing OfflineUserDataJob in the
            PENDING state. If None, a new job is created.
    """
    # Creates the OfflineUserDataJobService client.
    offline_user_data_job_service_client = client.get_service(
        "OfflineUserDataJobService"
    )

    if offline_user_data_job_id:
        # Reuses the specified offline user data job.
        offline_user_data_job_resource_name = offline_user_data_job_service_client.offline_user_data_job_path(
            customer_id, offline_user_data_job_id
        )
    else:
        # Creates a new offline user data job.
        offline_user_data_job = client.get_type("OfflineUserDataJob")
        offline_user_data_job.type_ = (
            client.enums.OfflineUserDataJobTypeEnum.CUSTOMER_MATCH_USER_LIST
        )
        offline_user_data_job.customer_match_user_list_metadata.user_list = (
            user_list_resource_name
        )
        # Issues a request to create an offline user data job.
        create_offline_user_data_job_response = offline_user_data_job_service_client.create_offline_user_data_job(
            customer_id=customer_id, job=offline_user_data_job
        )
        offline_user_data_job_resource_name = (
            create_offline_user_data_job_response.resource_name
        )
        print(
            "Created an offline user data job with resource name: "
            f"'{offline_user_data_job_resource_name}'."
        )

    # Issues a request to add the operations to the offline user data job.

    # Best Practice: This example only adds a few operations, so it only sends
    # one AddOfflineUserDataJobOperations request. If your application is adding
    # a large number of operations, split the operations into batches and send
    # multiple AddOfflineUserDataJobOperations requests for the SAME job. See
    # https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
    # and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
    # for more information on the per-request limits.
    request = client.get_type("AddOfflineUserDataJobOperationsRequest")
    request.resource_name = offline_user_data_job_resource_name
    request.operations = build_offline_user_data_job_operations(client)
    request.enable_partial_failure = True

    # Issues a request to add the operations to the offline user data job.
    response = offline_user_data_job_service_client.add_offline_user_data_job_operations(
        request=request
    )

    # Prints the status message if any partial failure error is returned.
    # Note: the details of each partial failure error are not printed here.
    # Refer to the error_handling/handle_partial_failure.py example to learn
    # more.
    # Extracts the partial failure from the response status.
    partial_failure = getattr(response, "partial_failure_error", None)
    if getattr(partial_failure, "code", None) != 0:
        error_details = getattr(partial_failure, "details", [])
        for error_detail in error_details:
            failure_message = client.get_type("GoogleAdsFailure")
            # Retrieve the class definition of the GoogleAdsFailure instance
            # in order to use the "deserialize" class method to parse the
            # error_detail string into a protobuf message object.
            failure_object = type(failure_message).deserialize(
                error_detail.value
            )

            for error in failure_object.errors:
                print(
                    "A partial failure at index "
                    f"{error.location.field_path_elements[0].index} occurred.\n"
                    f"Error message: {error.message}\n"
                    f"Error code: {error.error_code}"
                )

    print("The operations are added to the offline user data job.")

    if not run_job:
        print(
            "Not running offline user data job "
            f"'{offline_user_data_job_resource_name}', as requested."
        )
        return

    # Issues a request to run the offline user data job for executing all
    # added operations.
    offline_user_data_job_service_client.run_offline_user_data_job(
        resource_name=offline_user_data_job_resource_name
    )

    # Retrieves and displays the job status.
    check_job_status(client, customer_id, offline_user_data_job_resource_name)


def build_offline_user_data_job_operations(client):
    """Creates a raw input list of unhashed user information.

    Each element of the list represents a single user and is a dict containing a
    separate entry for the keys "email", "phone", "first_name", "last_name",
    "country_code", and "postal_code". In your application, this data might come
    from a file or a database.

    Args:
        client: The Google Ads client.

    Returns:
        A list containing the operations.
    """
    # The first user data has an email address and a phone number.
    raw_record_1 = {
        "email": "dana@example.com",
        # Phone number to be converted to E.164 format, with a leading '+' as
        # required. This includes whitespace that will be removed later.
        "phone": "+1 800 5550101",
    }

    # The second user data has an email address, a mailing address, and a phone
    # number.
    raw_record_2 = {
        # Email address that includes a period (.) before the email domain.
        "email": "alex.2@example.com",
        # Address that includes all four required elements: first name, last
        # name, country code, and postal code.
        "first_name": "Alex",
        "last_mame": "Quinn",
        "country_code": "US",
        "postal_code": "94045",
        # Phone number to be converted to E.164 format, with a leading '+' as
        # required.
        "phone": "+1 800 5550102",
    }

    # The third user data only has an email address.
    raw_record_3 = {"email": "charlie@example.com"}

    # Adds the raw records to a raw input list.
    raw_records = [raw_record_1, raw_record_2, raw_record_3]

    operations = []
    # Iterates over the raw input list and creates a UserData object for each
    # record.
    for record in raw_records:
        # Creates a UserData object that represents a member of the user list.
        user_data = client.get_type("UserData")

        # Checks if the record has email, phone, or address information, and
        # adds a SEPARATE UserIdentifier object for each one found. For example,
        # a record with an email address and a phone number will result in a
        # UserData with two UserIdentifiers.

        # IMPORTANT: Since the identifier attribute of UserIdentifier
        # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier)
        # is a oneof
        # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you
        # must set only ONE of hashed_email, hashed_phone_number, mobile_id,
        # third_party_user_id, or address-info. Setting more than one of these
        # attributes on the same UserIdentifier will clear all the other members
        # of the oneof. For example, the following code is INCORRECT and will
        # result in a UserIdentifier with ONLY a hashed_phone_number:

        # incorrect_user_identifier = client.get_type("UserIdentifier")
        # incorrect_user_identifier.hashed_email = "..."
        # incorrect_user_identifier.hashed_phone_number = "..."

        # The separate 'if' statements below demonstrate the correct approach
        # for creating a UserData object for a member with multiple
        # UserIdentifiers.

        # Checks if the record has an email address, and if so, adds a
        # UserIdentifier for it.
        if "email" in record:
            user_identifier = client.get_type("UserIdentifier")
            user_identifier.hashed_email = normalize_and_hash(
                record["email"], True
            )
            # Adds the hashed email identifier to the UserData object's list.
            user_data.user_identifiers.append(user_identifier)

        # Checks if the record has a phone number, and if so, adds a
        # UserIdentifier for it.
        if "phone" in record:
            user_identifier = client.get_type("UserIdentifier")
            user_identifier.hashed_phone_number = normalize_and_hash(
                record["phone"], True
            )
            # Adds the hashed phone number identifier to the UserData object's
            # list.
            user_data.user_identifiers.append(user_identifier)

        # Checks if the record has all the required mailing address elements,
        # and if so, adds a UserIdentifier for the mailing address.
        if "first_name" in record:
            required_keys = ("last_name", "country_code", "postal_code")
            # Checks if the record contains all the other required elements of
            # a mailing address.
            if not all(key in record for key in required_keys):
                # Determines which required elements are missing from the
                # record.
                missing_keys = record.keys() - required_keys
                print(
                    "Skipping addition of mailing address information "
                    "because the following required keys are missing: "
                    f"{missing_keys}"
                )
            else:
                user_identifier = client.get_type("UserIdentifier")
                address_info = user_identifier.address_info
                address_info.hashed_first_name = normalize_and_hash(
                    record["first_name"], False
                )
                address_info.hashed_last_name = normalize_and_hash(
                    record["first_last"], False
                )
                address_info.country_code = record["country_code"]
                address_info.postal_code = record["postal_code"]
                user_data.user_identifiers.append(user_identifier)

        # If the user_identifiers repeated field is not empty, create a new
        # OfflineUserDataJobOperation and add the UserData to it.
        if user_data.user_identifiers:
            operation = client.get_type("OfflineUserDataJobOperation")
            operation.create = user_data
            operations.append(operation)

    return operations


def check_job_status(client, customer_id, offline_user_data_job_resource_name):
    """Retrieves, checks, and prints the status of the offline user data job.

    If the job is completed successfully, information about the user list is
    printed. Otherwise, a GAQL query will be printed, which can be used to
    check the job status at a later date.

    Offline user data jobs may take 6 hours or more to complete, so checking the
    status periodically, instead of waiting, can be more efficient.

    Args:
        client: The Google Ads client.
        customer_id: The ID for the customer that owns the user list.
        offline_user_data_job_resource_name: The resource name of the offline
            user data job to get the status of.
    """
    query = f"""
        SELECT
          offline_user_data_job.resource_name,
          offline_user_data_job.id,
          offline_user_data_job.status,
          offline_user_data_job.type,
          offline_user_data_job.failure_reason,
          offline_user_data_job.customer_match_user_list_metadata.user_list
        FROM offline_user_data_job
        WHERE offline_user_data_job.resource_name =
          '{offline_user_data_job_resource_name}'
        LIMIT 1"""

    # Issues a search request using streaming.
    google_ads_service = client.get_service("GoogleAdsService")
    results = google_ads_service.search(customer_id=customer_id, query=query)
    offline_user_data_job = next(iter(results)).offline_user_data_job
    status_name = offline_user_data_job.status.name
    user_list_resource_name = (
        offline_user_data_job.customer_match_user_list_metadata.user_list
    )

    print(
        f"Offline user data job ID '{offline_user_data_job.id}' with type "
        f"'{offline_user_data_job.type_.name}' has status: {status_name}"
    )

    if status_name == "SUCCESS":
        print_customer_match_user_list_info(
            client, customer_id, user_list_resource_name
        )
    elif status_name == "FAILED":
        print(f"\tFailure Reason: {offline_user_data_job.failure_reason}")
    elif status_name in ("PENDING", "RUNNING"):
        print(
            "To check the status of the job periodically, use the following "
            f"GAQL query with GoogleAdsService.Search: {query}"
        )


def print_customer_match_user_list_info(
    client, customer_id, user_list_resource_name
):
    """Prints information about the Customer Match user list.

    Args:
        client: The Google Ads client.
        customer_id: The ID for the customer that owns the user list.
        user_list_resource_name: The resource name of the user list to which to
            add users.
    """
    googleads_service_client = client.get_service("GoogleAdsService")

    # Creates a query that retrieves the user list.
    query = f"""
        SELECT
          user_list.size_for_display,
          user_list.size_for_search
        FROM user_list
        WHERE user_list.resource_name = '{user_list_resource_name}'"""

    # Issues a search request.
    search_results = googleads_service_client.search(
        customer_id=customer_id, query=query
    )

    # Prints out some information about the user list.
    user_list = next(iter(search_results)).user_list
    print(
        "The estimated number of users that the user list "
        f"'{user_list.resource_name}' has is "
        f"{user_list.size_for_display} for Display and "
        f"{user_list.size_for_search} for Search."
    )
    print(
        "Reminder: It may take several hours for the user list to be "
        "populated. Estimates of size zero are possible."
    )


def normalize_and_hash(s, remove_all_whitespace):
    """Normalizes and hashes a string with SHA-256.

    Args:
        s: The string to perform this operation on.
        remove_all_whitespace: If true, removes leading, trailing, and
            intermediate spaces from the string before hashing. If false, only
            removes leading and trailing spaces from the string before hashing.

    Returns:
        A normalized (lowercase, remove whitespace) and SHA-256 hashed string.
    """
    # Normalizes by first converting all characters to lowercase, then trimming
    # spaces.
    if remove_all_whitespace:
        # Removes leading, trailing, and intermediate whitespace.
        s = "".join(s.split())
    else:
        # Removes only leading and trailing spaces.
        s = s.strip().lower()

    # Hashes the normalized string using the hashing algorithm.
    return hashlib.sha256(s.encode()).hexdigest()


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v13")

    parser = argparse.ArgumentParser(
        description="Adds a customer match user list for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The ID for the customer that owns the user list.",
    )
    parser.add_argument(
        "-r",
        "--run_job",
        type=bool,
        required=True,
        help=(
            "If true, runs the OfflineUserDataJob after adding operations. "
            "The default value is False."
        ),
    )
    parser.add_argument(
        "-u",
        "--user_list_id",
        type=str,
        required=False,
        help=(
            "The ID of an existing user list. If not specified, this example "
            "will create a new user list."
        ),
    )
    parser.add_argument(
        "-j",
        "--offline_user_data_job_id",
        type=str,
        required=False,
        help=(
            "The ID of an existing OfflineUserDataJob in the PENDING state. If "
            "not specified, this example will create a new job."
        ),
    )

    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.run_job,
            args.user_list_id,
            args.offline_user_data_job_id,
        )
    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.
#
# This example uses Customer Match to create a new user list (a.k.a. audience)
# and adds users to it.
#
# This feature is only available to accounts that meet the requirements described at
#     https://support.google.com/adspolicy/answer/6299717.
#
# Note: It may take up to several hours for the list to be populated with users.
# Email addresses must be associated with a Google account.
# For privacy purposes, the user list size will show as zero until the list has
# at least 1,000 users. After that, the size will be rounded to the two most
# significant digits.

require 'optparse'
require 'google/ads/google_ads'
require 'date'
require 'digest'

def add_customer_match_user_list(customer_id, run_job, user_list_id, job_id)
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  if job_id.nil?
    if user_list_id.nil?
      list_name = create_customer_match_user_list(client, customer_id)
    else
      list_name = client.path.user_list(customer_id, user_list_id)
    end
  end
  add_users_to_customer_match_user_list(client, customer_id, run_job, list_name, job_id)
end

def create_customer_match_user_list(client, customer_id)
  # Creates the user list.
  operation = client.operation.create_resource.user_list do |ul|
    ul.name = "Customer Match List #{(Time.new.to_f * 1000).to_i}"
    ul.description = "A list of customers that originated from email and " \
      "physical addresses"
    # Customer Match user lists can use a membership life span of 10000 to
    # indicate unlimited; otherwise normal values apply.
    # Sets the membership life span to 30 days.
    ul.membership_life_span = 30
    ul.crm_based_user_list = client.resource.crm_based_user_list_info do |crm|
      crm.upload_key_type = :CONTACT_INFO
    end
  end

  # Issues a mutate request to add the user list and prints some information.
  response = client.service.user_list.mutate_user_lists(
    customer_id: customer_id,
    operations: [operation],
  )

  # Prints out some information about the newly created user list.
  resource_name = response.results.first.resource_name
  puts "User list with resource name #{resource_name} was created."

  resource_name
end

def add_users_to_customer_match_user_list(client, customer_id, run_job, user_list, job_id)
  offline_user_data_service = client.service.offline_user_data_job

  job_name = if job_id.nil?
    # Creates the offline user data job.
    offline_user_data_job = client.resource.offline_user_data_job do |job|
      job.type = :CUSTOMER_MATCH_USER_LIST
      job.customer_match_user_list_metadata =
        client.resource.customer_match_user_list_metadata do |m|
          m.user_list = user_list
        end
    end

    # Issues a request to create the offline user data job.
    response = offline_user_data_service.create_offline_user_data_job(
      customer_id: customer_id,
      job: offline_user_data_job,
    )
    offline_user_data_job_resource_name = response.resource_name
    puts "Created an offline user data job with resource name: " \
      "#{offline_user_data_job_resource_name}"

    offline_user_data_job_resource_name
  else
    client.path.offline_user_data_job(customer_id, job_id)
  end

  # Issues a request to add the operations to the offline user data job. This
  # example only adds a few operations, so it only sends one
  # AddOfflineUserDataJobOperations request.  If your application is adding a
  # large number of operations, split the operations into batches and send
  # multiple AddOfflineUserDataJobOperations requests for the SAME job. See
  # https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
  # and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
  # for more information on the per-request limits.
  response = offline_user_data_service.add_offline_user_data_job_operations(
    resource_name: offline_user_data_job_resource_name,
    enable_partial_failure: true,
    operations: build_offline_user_data_job_operations(client),
  )

  # Prints errors if any partial failure error is returned.
  if response.partial_failure_error
    failures = client.decode_partial_failure_error(response.partial_failure_error)
    failures.each do |failure|
      failure.errors.each do |error|
        human_readable_error_path = error
          .location
          .field_path_elements
          .map { |location_info|
            if location_info.index
              "#{location_info.field_name}[#{location_info.index}]"
            else
              "#{location_info.field_name}"
            end
          }.join(" > ")

        errmsg =  "error occured while adding operations " \
          "#{human_readable_error_path}" \
          " with value: #{error.trigger.string_value}" \
          " because #{error.message.downcase}"
        puts errmsg
      end
    end
  end
  puts "The operations are added to the offline user data job."

  unless run_job
    puts "Not running offline user data job #{job_name}, as requested."
    return
  end

  # Issues an asynchronous request to run the offline user data job
  # for executing all added operations.
  response = offline_user_data_service.run_offline_user_data_job(
    resource_name: offline_user_data_job_resource_name
  )
  puts "Asynchronous request to execute the added operations started."
  puts "Waiting until operation completes."

  # Offline user data jobs may take 6 hours or more to complete, so instead of
  # waiting for the job to complete, retrieves and displays the job status
  # once. If the job is completed successfully, prints information about the
  # user list. Otherwise, prints the query to use to check the job again later.
  check_job_status(
    client,
    customer_id,
    offline_user_data_job_resource_name,
  )
end

def print_customer_match_user_list(client, customer_id, user_list)
  query = <<~EOQUERY
    SELECT user_list.size_for_display, user_list.size_for_search
    FROM user_list
    WHERE user_list.resource_name = #{user_list}
  EOQUERY

  response = client.service.google_ads.search_stream(
    customer_id: customer_id,
    query: query,
  )
  row = response.first
  puts "The estimated number of users that the user list " \
    "#{row.user_list.resource_name} has is " \
    "#{row.user_list.size_for_display} for Display and " \
    "#{row.user_list.size_for_search} for Search."
  puts "Reminder: It may take several hours for the user list to be " \
    "populated with the users so getting zeros for the estimations is expected."
end

def build_offline_user_data_job_operations(client)
  # Create a list of unhashed user data records that we will format in the
  # following steps to prepare for the API.
  raw_records = [
    # The first user data has an email address and a phone number.
    {
      email: 'dana@example.com',
      # Phone number to be converted to E.164 format, with a leading '+' as
      # required. This includes whitespace that will be removed later.
      phone: '+1 800 5550100',
    },
    # The second user data has an email address, a phone number, and an address.
    {
      # Email address that includes a period (.) before the Gmail domain.
      email: 'alex.2@example.com',
      # Address that includes all four required elements: first name, last
      # name, country code, and postal code.
      first_name: 'Alex',
      last_name: 'Quinn',
      country_code: 'US',
      postal_code: '94045',
      # Phone number to be converted to E.164 format, with a leading '+' as
      # required.
      phone: '+1 800 5550102',
    },
    # The third user data only has an email address.
    {
      email: 'charlie@example.com',
    },
  ]

  # Create a UserData for each entry in the raw records.
  user_data_list = raw_records.map do |record|
    client.resource.user_data do |data|
      if record[:email]
        data.user_identifiers << client.resource.user_identifier do |ui|
          ui.hashed_email = normalize_and_hash(record[:email], true)
        end
      end
      if record[:phone]
        data.user_identifiers << client.resource.user_identifier do |ui|
          ui.hashed_phone_number = normalize_and_hash(record[:phone], true)
        end
      end
      if record[:first_name]
        # Check that we have all the required information.
        missing_keys = [:last_name, :country_code, :postal_code].reject {|key|
          record[key].nil?
        }
        if missing_keys.empty?
          # If nothing is missing, add the address.
          data.user_identifiers << client.resource.user_identifier do |ui|
            ui.address_identifier = client.resource.offline_user_address_info do |address|
              address.hashed_first_name = normalize_and_hash(record[:first_name])
              address.hashed_last_name = normalize_and_hash(record[:last_name])
              address.country_code = record[:country_code]
              address.postal_code = record[:postal_code]
            end
          end
        else
          # If some data is missing, skip this entry.
          puts "Skipping addition of mailing information because the following keys are missing:" \
            "#{missing_keys}"
        end
      end
    end
  end

  operations = user_data_list.map do |user_data|
    client.operation.create_resource.offline_user_data_job(user_data)
  end

  operations
end

def check_job_status(client, customer_id, offline_user_data_job)
  query = <<~QUERY
    SELECT
      offline_user_data_job.id,
      offline_user_data_job.status,
      offline_user_data_job.type,
      offline_user_data_job.failure_reason,
      offline_user_data_job.customer_match_user_list_metadata.user_list
    FROM
      offline_user_data_job
    WHERE
      offline_user_data_job.resource_name = '#{offline_user_data_job}'
  QUERY

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

  job = row.offline_user_data_job
  puts "Offline user data job ID #{job.id} with type '#{job.type}' has status: #{job.status}."

  case job.status
  when :SUCCESS
    print_customer_match_user_list(client, customer_id, job.customer_match_user_list_metadata.user_list)
  when :FAILED
    puts "  Failure reason: #{job.failure_reason}"
  else
    puts "  To check the status of the job periodically, use the following GAQL " \
      "query with GoogleAdsService.search:"
    puts query
  end
end

def normalize_and_hash(str, trim_inner_spaces = false)
  if trim_inner_spaces
    str = str.gsub("\s", '')
  end
  Digest::SHA256.hexdigest(str.strip.downcase)
end

if __FILE__ == $0
  options = {}

  # Running the example with -h will print the command line usage.

  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('-r', '--run-job', 'If true, runs the OfflineUserDataJob after adding operations.' \
        'The default value is false.') do |v|
      options[:run_job] = v
    end

    opts.on('-u', '--user-list-id [USER-LIST-ID]', String,
        'The ID of an existing user list. If not specified, this example will create a new user list.') do |v|
      options[:user_list_id] = v
    end

    opts.on('-j', '--offline-user-data-job-id [OFFLINE-USER-DATA-JOB-ID]', String,
        'The ID of an existing OfflineUserDataJob in the PENDING state. If not specified, this' \
        ' example will create a new job.') do |v|
      options[:job_id] = v
    end

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

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

  begin
    add_customer_match_user_list(
      options.fetch(:customer_id).tr("-", ""),
      options[:run_job],
      options[:user_list_id],
      options[:job_id],
    )
  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 example creates operations to add members to a user list (a.k.a. audience)
# using an OfflineUserDataJob, and if requested, runs the job.
#
# If a job ID is specified, this examples add operations to that job. Otherwise,
# it creates a new job for the operations.
#
# Your application should create a single job containing all of the operations
# for a user list. This will be far more efficient than creating and running
# multiple jobs that each contain a small set of operations.
#
# Notes:
#
# * This feature is only available to accounts that meet the requirements described
# at https://support.google.com/adspolicy/answer/6299717.
# * It may take up to several hours for the list to be populated with users.
# * Email addresses must be associated with a Google account.
# * For privacy purposes, the user list size will show as zero until the list has
# at least 1,000 users. After that, the size will be rounded to the two most
# significant digits.

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::SearchStreamHandler;
use Google::Ads::GoogleAds::V13::Resources::UserList;
use Google::Ads::GoogleAds::V13::Resources::OfflineUserDataJob;
use Google::Ads::GoogleAds::V13::Common::CrmBasedUserListInfo;
use Google::Ads::GoogleAds::V13::Common::CustomerMatchUserListMetadata;
use Google::Ads::GoogleAds::V13::Common::UserData;
use Google::Ads::GoogleAds::V13::Common::UserIdentifier;
use Google::Ads::GoogleAds::V13::Common::OfflineUserAddressInfo;
use Google::Ads::GoogleAds::V13::Enums::CustomerMatchUploadKeyTypeEnum
  qw(CONTACT_INFO);
use Google::Ads::GoogleAds::V13::Enums::OfflineUserDataJobStatusEnum
  qw(SUCCESS FAILED PENDING RUNNING);
use Google::Ads::GoogleAds::V13::Enums::OfflineUserDataJobTypeEnum
  qw(CUSTOMER_MATCH_USER_LIST);
use Google::Ads::GoogleAds::V13::Services::UserListService::UserListOperation;
use
  Google::Ads::GoogleAds::V13::Services::OfflineUserDataJobService::OfflineUserDataJobOperation;
use
  Google::Ads::GoogleAds::V13::Services::GoogleAdsService::SearchGoogleAdsStreamRequest;
use Google::Ads::GoogleAds::V13::Utils::ResourceNames;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd          qw(abs_path);
use Data::Uniqid qw(uniqid);
use Digest::SHA  qw(sha256_hex);

sub add_customer_match_user_list {
  my ($api_client, $customer_id, $run_job, $user_list_id,
    $offline_user_data_job_id)
    = @_;

  my $user_list_resource_name = undef;
  if (!defined $offline_user_data_job_id) {
    if (!defined $user_list_id) {
      # Create a Customer Match user list.
      $user_list_resource_name =
        create_customer_match_user_list($api_client, $customer_id);
    } else {
      # Uses the specified Customer Match user list.
      $user_list_resource_name =
        Google::Ads::GoogleAds::V13::Utils::ResourceNames::user_list(
        $customer_id, $user_list_id);
    }
  }
  add_users_to_customer_match_user_list($api_client, $customer_id, $run_job,
    $user_list_resource_name, $offline_user_data_job_id);
  print_customer_match_user_list_info($api_client, $customer_id,
    $user_list_resource_name);

  return 1;
}

# Creates a Customer Match user list.
sub create_customer_match_user_list {
  my ($api_client, $customer_id) = @_;

  # Create the user list.
  my $user_list = Google::Ads::GoogleAds::V13::Resources::UserList->new({
      name        => "Customer Match list #" . uniqid(),
      description =>
        "A list of customers that originated from email and physical addresses",
      # Customer Match user lists can use a membership life span of 10000 to
      # indicate unlimited; otherwise normal values apply.
      # Set the membership life span to 30 days.
      membershipLifeSpan => 30,
      # Set the upload key type to indicate the type of identifier that will be
      # used to add users to the list. This field is immutable and required for
      # a CREATE operation.
      crmBasedUserList =>
        Google::Ads::GoogleAds::V13::Common::CrmBasedUserListInfo->new({
          uploadKeyType => CONTACT_INFO
        })});

  # Create the user list operation.
  my $user_list_operation =
    Google::Ads::GoogleAds::V13::Services::UserListService::UserListOperation->
    new({
      create => $user_list
    });

  # Issue a mutate request to add the user list and print some information.
  my $user_lists_response = $api_client->UserListService()->mutate({
      customerId => $customer_id,
      operations => [$user_list_operation]});
  my $user_list_resource_name =
    $user_lists_response->{results}[0]{resourceName};
  printf "User list with resource name '%s' was created.\n",
    $user_list_resource_name;

  return $user_list_resource_name;
}

# Creates and executes an asynchronous job to add users to the Customer Match
# user list.
sub add_users_to_customer_match_user_list {
  my ($api_client, $customer_id, $run_job, $user_list_resource_name,
    $offline_user_data_job_id)
    = @_;

  my $offline_user_data_job_service = $api_client->OfflineUserDataJobService();

  my $offline_user_data_job_resource_name = undef;
  if (!defined $offline_user_data_job_id) {
    # Create a new offline user data job.
    my $offline_user_data_job =
      Google::Ads::GoogleAds::V13::Resources::OfflineUserDataJob->new({
        type                          => CUSTOMER_MATCH_USER_LIST,
        customerMatchUserListMetadata =>
          Google::Ads::GoogleAds::V13::Common::CustomerMatchUserListMetadata->
          new({
            userList => $user_list_resource_name
          })});

    # Issue a request to create the offline user data job.
    my $create_offline_user_data_job_response =
      $offline_user_data_job_service->create({
        customerId => $customer_id,
        job        => $offline_user_data_job
      });
    $offline_user_data_job_resource_name =
      $create_offline_user_data_job_response->{resourceName};
    printf
      "Created an offline user data job with resource name: '%s'.\n",
      $offline_user_data_job_resource_name;
  } else {
    # Reuse the specified offline user data job.
    $offline_user_data_job_resource_name =
      Google::Ads::GoogleAds::V13::Utils::ResourceNames::offline_user_data_job(
      $customer_id, $offline_user_data_job_id);
  }

  # Issue a request to add the operations to the offline user data job.
  # This example only adds a few operations, so it only sends one AddOfflineUserDataJobOperations
  # request. If your application is adding a large number of operations, split
  # the operations into batches and send multiple AddOfflineUserDataJobOperations
  # requests for the SAME job. See
  # https://developers.google.com/google-ads/api/docs/remarketing/audience-types/customer-match#customer_match_considerations
  # and https://developers.google.com/google-ads/api/docs/best-practices/quotas#user_data
  # for more information on the per-request limits.
  my $user_data_job_operations = build_offline_user_data_job_operations();
  my $response                 = $offline_user_data_job_service->add_operations(
    {
      resourceName         => $offline_user_data_job_resource_name,
      enablePartialFailure => "true",
      operations           => $user_data_job_operations
    });

  # Print the status message if any partial failure error is returned.
  # Note: The details of each partial failure error are not printed here, you can
  # refer to the example handle_partial_failure.pl to learn more.
  if ($response->{partialFailureError}) {
    # Extract the partial failure from the response status.
    my $partial_failure = $response->{partialFailureError}{details}[0];
    printf "Encountered %d partial failure errors while adding %d operations " .
      "to the offline user data job: '%s'. Only the successfully added " .
      "operations will be executed when the job runs.\n",
      scalar @{$partial_failure->{errors}}, scalar @$user_data_job_operations,
      $response->{partialFailureError}{message};
  } else {
    printf "Successfully added %d operations to the offline user data job.\n",
      scalar @$user_data_job_operations;
  }

  if (!defined $run_job) {
    print
"Not running offline user data job $offline_user_data_job_resource_name, as requested.\n";
    return;
  }

  # Issue an asynchronous request to run the offline user data job for executing
  # all added operations.
  my $operation_response = $offline_user_data_job_service->run({
    resourceName => $offline_user_data_job_resource_name
  });

  # Offline user data jobs may take 6 hours or more to complete, so instead of waiting
  # for the job to complete, this example retrieves and displays the job status once.
  # If the job is completed successfully, it prints information about the user list.
  # Otherwise, it prints, the query to use to check the job status again later.
  check_job_status($api_client, $customer_id,
    $offline_user_data_job_resource_name);
}

# Retrieves, checks, and prints the status of the offline user data job.
sub check_job_status() {
  my ($api_client, $customer_id, $offline_user_data_job_resource_name) = @_;

  my $search_query =
    "SELECT offline_user_data_job.resource_name, " .
    "offline_user_data_job.id, offline_user_data_job.status, " .
    "offline_user_data_job.type, offline_user_data_job.failure_reason, " .
    "offline_user_data_job.customer_match_user_list_metadata.user_list " .
    "FROM offline_user_data_job " .
    "WHERE offline_user_data_job.resource_name = " .
    "$offline_user_data_job_resource_name LIMIT 1";

  my $search_request =
    Google::Ads::GoogleAds::V13::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
  });

  # The results have exactly one row.
  my $google_ads_row        = $iterator->next;
  my $offline_user_data_job = $google_ads_row->{offlineUserDataJob};
  my $status                = $offline_user_data_job->{status};

  printf
    "Offline user data job ID %d with type %s has status: %s.\n",
    $offline_user_data_job->{id},
    $offline_user_data_job->{type},
    $status;

  if ($status eq SUCCESS) {
    print_customer_match_user_list_info($api_client, $customer_id,
      $offline_user_data_job->{customerMatchUserListMetadata}{userList});
  } elsif ($status eq FAILED) {
    print "Failure reason: $offline_user_data_job->{failure_reason}";
  } elsif (grep /$status/, (PENDING, RUNNING)) {
    print
      "To check the status of the job periodically, use the following GAQL " .
      "query with the GoogleAdsService->search() method:\n$search_query\n";
  }

  return 1;
}

# Builds and returns offline user data job operations to add one user identified
# by an email address and one user identified based on a physical address.
sub build_offline_user_data_job_operations() {
  # The first user data has an email address and a phone number.
  my $raw_record_1 = {
    email => 'dana@example.com',
    # Phone number to be converted to E.164 format, with a leading '+' as
    # required. This includes whitespace that will be removed later.
    phone => '+1 800 5550101',
  };

  # The second user data has an email address, a mailing address, and a phone
  # number.
  my $raw_record_2 = {
    # Email address that includes a period (.) before the Gmail domain.
    email => 'alex.2@example.com',
    # Address that includes all four required elements: first name, last
    # name, country code, and postal code.
    firstName   => 'Alex',
    lastName    => 'Quinn',
    countryCode => 'US',
    postalCode  => '94045',
    # Phone number to be converted to E.164 format, with a leading '+' as
    # required.
    phone => '+1 800 5550102',
  };

  # The third user data only has an email address.
  my $raw_record_3 = {email => 'charlie@example.com',};

  my $raw_records = [$raw_record_1, $raw_record_2, $raw_record_3];

  my $operations = [];
  foreach my $record (@$raw_records) {
    # Check if the record has email, phone, or address information, and adds a
    # SEPARATE UserIdentifier object for each one found. For example, a record
    # with an email address and a phone number will result in a UserData with two
    # UserIdentifiers.
    #
    # IMPORTANT: Since the identifier attribute of UserIdentifier
    # (https://developers.google.com/google-ads/api/reference/rpc/latest/UserIdentifier)
    # is a oneof
    # (https://protobuf.dev/programming-guides/proto3/#oneof-features), you must set
    # only ONE of hashed_email, hashed_phone_number, mobile_id, third_party_user_id,
    # or address-info. Setting more than one of these attributes on the same UserIdentifier
    # will clear all the other members of the oneof. For example, the following code is
    # INCORRECT and will result in a UserIdentifier with ONLY a hashed_phone_number:
    #
    # my $incorrect_user_identifier = Google::Ads::GoogleAds::V13::Common::UserIdentifier->new({
    #   hashedEmail => '...',
    #   hashedPhoneNumber => '...',
    # });
    #
    # The separate 'if' statements below demonstrate the correct approach for creating a
    # UserData object for a member with multiple UserIdentifiers.

    my $user_identifiers = [];

    # Check if the record has an email address, and if so, add a UserIdentifier for it.
    if (defined $record->{email}) {
      # Add the hashed email identifier to the list of UserIdentifiers.
      push(
        @$user_identifiers,
        Google::Ads::GoogleAds::V13::Common::UserIdentifier->new({
            hashedEmail => normalize_and_hash($record->{email}, 1)}));
    }

    # Check if the record has a phone number, and if so, add a UserIdentifier for it.
    if (defined $record->{phone}) {
      # Add the hashed phone number identifier to the list of UserIdentifiers.
      push(
        @$user_identifiers,
        Google::Ads::GoogleAds::V13::Common::UserIdentifier->new({
            hashedEmail => normalize_and_hash($record->{phone}, 1)}));
    }

    # Check if the record has all the required mailing address elements, and if so, add
    # a UserIdentifier for the mailing address.
    if (defined $record->{firstName}) {
      my $required_keys = ["lastName", "countryCode", "postalCode"];
      my $missing_keys  = [];

      foreach my $key (@$required_keys) {
        if (!defined $record->{$key}) {
          push(@$missing_keys, $key);
        }
      }

      if (@$missing_keys) {
        print
"Skipping addition of mailing address information because the following"
          . "keys are missing: "
          . join(",", @$missing_keys);
      } else {
        push(
          @$user_identifiers,
          Google::Ads::GoogleAds::V13::Common::UserIdentifier->new({
              addressInfo =>
                Google::Ads::GoogleAds::V13::Common::OfflineUserAddressInfo->
                new({
                  # First and last name must be normalized and hashed.
                  hashedFirstName => normalize_and_hash($record->{firstName}),
                  hashedLastName  => normalize_and_hash($record->{lastName}),
                  # Country code and zip code are sent in plain text.
                  countryCode => $record->{countryCode},
                  postalCode  => $record->{postalCode},
                })}));
      }
    }

    # If the user_identifiers array is not empty, create a new
    # OfflineUserDataJobOperation and add the UserData to it.
    if (@$user_identifiers) {
      my $user_data = Google::Ads::GoogleAds::V13::Common::UserData->new({
          userIdentifiers => [$user_identifiers]});
      push(
        @$operations,
        Google::Ads::GoogleAds::V13::Services::OfflineUserDataJobService::OfflineUserDataJobOperation
          ->new({
            create => $user_data
          }));
    }
  }
  return $operations;
}

# Prints information about the Customer Match user list.
sub print_customer_match_user_list_info {
  my ($api_client, $customer_id, $user_list_resource_name) = @_;

  # Create a query that retrieves the user list.
  my $search_query =
    "SELECT user_list.size_for_display, user_list.size_for_search " .
    "FROM user_list " .
    "WHERE user_list.resource_name = '$user_list_resource_name'";

  # Create a search Google Ads stream request that will retrieve the user list.
  my $search_stream_request =
    Google::Ads::GoogleAds::V13::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query,
    });

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

  my $search_stream_handler =
    Google::Ads::GoogleAds::Utils::SearchStreamHandler->new({
      service => $google_ads_service,
      request => $search_stream_request
    });

  # Issue a search request and process the stream response to print out some
  # information about the user list.
  $search_stream_handler->process_contents(
    sub {
      my $google_ads_row = shift;
      my $user_list      = $google_ads_row->{userList};

      printf "The estimated number of users that the user list '%s' " .
        "has is %d for Display and %d for Search.\n",
        $user_list->{resourceName},
        $user_list->{sizeForDisplay},
        $user_list->{sizeForSearch};
    });

  print
    "Reminder: It may take several hours for the user list to be populated " .
    "with the users so getting zeros for the estimations is expected.\n";
}

# Normalizes and hashes a string value.
sub normalize_and_hash {
  my $value                    = shift;
  my $trim_intermediate_spaces = shift;

  if ($trim_intermediate_spaces) {
    $value =~ s/\s+|\s+$//g;
  } else {
    $value =~ s/^\s+|\s+$//g;
  }
  return sha256_hex(lc $value);
}

# 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);

my $customer_id              = undef;
my $run_job                  = undef;
my $user_list_id             = undef;
my $offline_user_data_job_id = undef;

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s"              => \$customer_id);
GetOptions("run_job=s"                  => \$run_job);
GetOptions("user_list_id=i"             => \$user_list_id);
GetOptions("offline_user_data_job_id=i" => \$offline_user_data_job_id);

# 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);

# Call the example.
add_customer_match_user_list($api_client, $customer_id =~ s/-//gr,
  $run_job, $user_list_id, $offline_user_data_job_id);

=pod

=head1 NAME

add_customer_match_user_list

=head1 DESCRIPTION

This example uses Customer Match to create a new user list (a.k.a. audience) and
adds users to it.

This feature is only available to allowlisted accounts.
See https://support.google.com/adspolicy/answer/6299717 for more details.

Note: It may take up to several hours for the list to be populated with users.
Email addresses must be associated with a Google account. For privacy purposes,
the user list size will show as zero until the list has at least 1,000 users.
After that, the size will be rounded to the two most significant digits.

=head1 SYNOPSIS

add_customer_match_user_list.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -run_job			[optional] Run the OfflineUserDataJob after adding operations. Otherwise, only adds operations to the job.
    -user_list_id		[optional] ID of an existing user list. If undef, creates a new user list.
    -offline_user_data_job_id	[optional] ID of an existing OfflineUserDataJob in the PENDING state. If undef, creates a new job.

=cut