Valider l'identité de l'annonceur

Java

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

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

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v16.enums.IdentityVerificationProgramEnum.IdentityVerificationProgram;
import com.google.ads.googleads.v16.enums.IdentityVerificationProgramStatusEnum.IdentityVerificationProgramStatus;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.services.GetIdentityVerificationResponse;
import com.google.ads.googleads.v16.services.IdentityVerification;
import com.google.ads.googleads.v16.services.IdentityVerificationProgress;
import com.google.ads.googleads.v16.services.IdentityVerificationServiceClient;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This code example illustrates how to retrieve the status of the advertiser identity verification
 * program and, if required and not already started, how to start the verification process.
 */
public class VerifyAdvertiserIdentity {

  private static class VerifyAdvertiserIdentityParams extends CodeSampleParams {

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

  public static void main(String[] args) {
    VerifyAdvertiserIdentityParams params = new VerifyAdvertiserIdentityParams();
    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");
    }

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

  /**
   * Runs the example.
   *
   * @param googleAdsClient the API client to use.
   * @param customerId the customer ID to update.
   */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    try (IdentityVerificationServiceClient identityVerificationServiceClient =
        googleAdsClient.getLatestVersion().createIdentityVerificationServiceClient()) {
      // Retrieves the current Advertiser Identity Verification status.
      IdentityVerification identityVerification =
          getIdentityVerification(customerId, identityVerificationServiceClient);

      if (identityVerification == null) {
        // If getIdentityVerification returned an empty response, the account is not enrolled in
        // mandatory identity verification.
        System.out.printf(
            "Account %d is not required to perform advertiser identity verification.%n",
            customerId);
        System.out.println(
            "See https://support.google.com/adspolicy/answer/9703665 for details on how and when an"
                + " account is required to undergo the advertiser identity verification program.");
        return;
      }

      IdentityVerificationProgramStatus programStatus =
          identityVerification.getVerificationProgress().getProgramStatus();
      switch (programStatus) {
        case UNSPECIFIED:
          // Starts an identity verification session.
          startIdentityVerification(customerId, identityVerificationServiceClient);

          // Calls getIdentityVerification again to retrieve the verification progress after
          // starting an identity verification session.
          getIdentityVerification(customerId, identityVerificationServiceClient);
          break;
        case PENDING_USER_ACTION:
          // If there is an identity verification session in progress, there is no need to start
          // another one by calling startIdentityVerification.
          System.out.println("There is an advertiser identify verification session in progress.");
          System.out.printf(
              "The URL for the verification process is '%s' and it will expire at '%s'%n",
              identityVerification.getVerificationProgress().getActionUrl(),
              identityVerification.getVerificationProgress().getInvitationLinkExpirationTime());
          break;
        case PENDING_REVIEW:
          System.out.println("The verification is under review.");
          break;
        case SUCCESS:
          System.out.println("The verification already completed.");
          break;
        default:
          throw new IllegalStateException(
              "The identity verification has an unexpected status: " + programStatus);
      }
    }
  }

  /** Retrieves the status of the advertiser identity verification process. */
  private IdentityVerification getIdentityVerification(
      long customerId, IdentityVerificationServiceClient identityVerificationServiceClient) {
    GetIdentityVerificationResponse response =
        identityVerificationServiceClient.getIdentityVerification(Long.toString(customerId));
    if (response.getIdentityVerificationCount() == 0) {
      return null;
    }
    IdentityVerification identityVerification = response.getIdentityVerification(0);
    String deadline =
        identityVerification
            .getIdentityVerificationRequirement()
            .getVerificationCompletionDeadlineTime();
    IdentityVerificationProgress progress = identityVerification.getVerificationProgress();
    System.out.printf(
        "Account %d has a verification completion deadline of '%s' and status '%s' for advertiser"
            + " identity verification.%n",
        customerId, deadline, progress.getProgramStatus());
    return identityVerification;
  }


  /** Starts the identity verification process. */
  private void startIdentityVerification(
      long customerId, IdentityVerificationServiceClient identityVerificationServiceClient) {
    // Sends a request to start the identity verification process.
    identityVerificationServiceClient.startIdentityVerification(
        Long.toString(customerId), IdentityVerificationProgram.ADVERTISER_IDENTITY_VERIFICATION);
  }
}

      

C#

// Copyright 2024 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.V16.Errors;
using Google.Ads.GoogleAds.V16.Services;
using static Google.Ads.GoogleAds.V16.Enums.IdentityVerificationProgramEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.IdentityVerificationProgramStatusEnum.Types;
using System;
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Extensions.Config;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// This code example illustrates how to retrieve the status of the advertiser identity
    /// verification program and, if required and not already started, how to start the verification
    /// process.
    /// </summary>
    public class VerifyAdvertiserIdentity : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="VerifyAdvertiserIdentity"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }
        }

        /// <summary>
        /// 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);

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example retrieves the status of the advertiser identity verification " +
             "program and, if required and not already started, starts the verification process.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Retrieve the current Advertiser Identity Verification status.
            IdentityVerification identityVerification =
                GetIdentityVerification(client, customerId);

            if (identityVerification == null)
            {

                // If GetIdentityVerification returned an empty response, the account is not
                // enrolled in mandatory identity verification.
                Console.WriteLine($"Account {customerId} is not required to perform advertiser " +
                    "identity verification.\n" +
                    "See https://support.google.com/adspolicy/answer/9703665 for details on how " +
                    "and when an account is required to undergo the advertiser identity " +
                    "verification program.");
                    return;
            }

            switch(identityVerification.VerificationProgress.ProgramStatus)
            {
                case IdentityVerificationProgramStatus.Unspecified:
                    // Starts an identity verification session.
                    StartIdentityVerification(client, customerId);
                    // Calls GetIdentityVerification again to retrieve the verification progress
                    // after starting an identity verification session.
                    GetIdentityVerification(client, customerId);
                    break;
                case IdentityVerificationProgramStatus.PendingUserAction:
                    // If there is an identity verification session in progress, there is no
                    // need to start another one by calling StartIdentityVerification.
                    Console.WriteLine("There is an advertiser identity verification session " +
                        "in progress.\n" +
                        "The URL for the verification process is: " +
                        identityVerification.VerificationProgress.ActionUrl +
                        " and it will expire at " +
                        identityVerification.VerificationProgress.InvitationLinkExpirationTime);
                    break;
                case IdentityVerificationProgramStatus.PendingReview:
                    Console.WriteLine("The verification is under review.");
                    break;
                case IdentityVerificationProgramStatus.Success:
                    Console.WriteLine("The verification completed successfully.");
                    break;
                default:
                    Console.WriteLine("The verification has an unknown state.");
                    break;
            }
        }

        /// <summary>
        /// Retrieves the status of the advertiser identity verification process.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        private static IdentityVerification GetIdentityVerification(
                GoogleAdsClient client, long customerId)
        {
            IdentityVerificationServiceClient identityVerificationService =
                client.GetService(Services.V16.IdentityVerificationService);

            try {
                GetIdentityVerificationResponse response =
                    identityVerificationService.GetIdentityVerification(
                        new GetIdentityVerificationRequest()
                        {
                            CustomerId = customerId.ToString()
                        }
                    );

                    if (response.IdentityVerification.Count == 0)
                    {
                        return null;
                    }

                    IdentityVerification identityVerification = response.IdentityVerification[0];
                    string deadline =
                        identityVerification.IdentityVerificationRequirement.VerificationCompletionDeadlineTime;
                     IdentityVerificationProgress identityVerificationProgress =
                        identityVerification.VerificationProgress;
                    Console.WriteLine($"Account {customerId} has a verification completion " +
                        $"deadline of {deadline} and status " +
                        $"{identityVerificationProgress.ProgramStatus} for advertiser identity " +
                        "verification.");

                    return identityVerification;
            } catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }


        }

        /// <summary>
        /// Starts the identity verification process.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        private static void StartIdentityVerification(GoogleAdsClient client, long customerId)
        {
            IdentityVerificationServiceClient identityVerificationService =
                client.GetService(Services.V16.IdentityVerificationService);

            StartIdentityVerificationRequest request = new StartIdentityVerificationRequest()
            {
                CustomerId = customerId.ToString(),
                VerificationProgram = IdentityVerificationProgram.AdvertiserIdentityVerification
            };

            try {
                identityVerificationService.StartIdentityVerification(request);
            } catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }
    }
}

      

PHP

<?php

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

namespace Google\Ads\GoogleAds\Examples\AccountManagement;

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

use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V16\GoogleAdsException;
use Google\Ads\GoogleAds\V16\Enums\IdentityVerificationProgramEnum\IdentityVerificationProgram;
use Google\Ads\GoogleAds\V16\Enums\IdentityVerificationProgramStatusEnum\IdentityVerificationProgramStatus;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Services\Client\IdentityVerificationServiceClient;
use Google\Ads\GoogleAds\V16\Services\GetIdentityVerificationRequest;
use Google\Ads\GoogleAds\V16\Services\IdentityVerification;
use Google\Ads\GoogleAds\V16\Services\StartIdentityVerificationRequest;
use Google\ApiCore\ApiException;

/**
 * This code example illustrates how to retrieve the status of the advertiser identity verification
 * program and, if required and not already started, how to start the verification process.
 */
class VerifyAdvertiserIdentity
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

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

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

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

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } 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
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        // Retrieves the current Advertiser Identity Verification status.
        $identityVerificationServiceClient = $googleAdsClient->getIdentityVerificationServiceClient();
        $identityVerification =
            self::getIdentityVerification($customerId, $identityVerificationServiceClient);
        if (is_null($identityVerification)) {
            // If getIdentityVerification returned an empty response, the account is not enrolled in
            // mandatory identity verification.
            printf(
                "Account %d is not required to perform advertiser identity verification.%s",
                $customerId,
                PHP_EOL
            );
            print 'See https://support.google.com/adspolicy/answer/9703665 for details on how and'
                . ' when an account is required to undergo the advertiser identity verification'
                . ' program.' . PHP_EOL;
            return;
        }

        switch ($identityVerification->getVerificationProgress()->getProgramStatus()) {
            case IdentityVerificationProgramStatus::UNSPECIFIED:
                // Starts an identity verification session.
                self::startIdentityVerification($customerId, $identityVerificationServiceClient);
                // Calls getIdentityVerification again to retrieve the verification progress after
                // starting an identity verification session.
                self::getIdentityVerification($customerId, $identityVerificationServiceClient);
                break;
            case IdentityVerificationProgramStatus::PENDING_USER_ACTION:
                // If there is an identity verification session in progress, there is no need to
                // start another one by calling startIdentityVerification.
                print 'There is an advertiser identify verification session in progress.';
                printf(
                    "The URL for the verification process is '%s' and it will expire at '%s'.%s",
                    $identityVerification->getVerificationProgress()->getActionUrl(),
                    $identityVerification->getVerificationProgress()
                        ->getInvitationLinkExpirationTime(),
                    PHP_EOL
                );
                break;
            case IdentityVerificationProgramStatus::PENDING_REVIEW:
                print 'The verification is under review' . PHP_EOL;
                break;
            case IdentityVerificationProgramStatus::SUCCESS:
                print 'The verification already completed' . PHP_EOL;
                break;
            case IdentityVerificationProgramStatus::UNKNOWN:
            default:
                throw new \UnexpectedValueException(
                    'The identity verification has an unknown state.'
                );
        }
    }

    /**
     * Retrieves the status of the advertiser identity verification process.
     *
     * @param int $customerId the customer ID
     * @param IdentityVerificationServiceClient $identityVerificationServiceClient the identity
     *     verification service client
     * @return IdentityVerification|null the retrieved identity verification
     */
    private static function getIdentityVerification(
        int $customerId,
        IdentityVerificationServiceClient $identityVerificationServiceClient
    ) {
        // Gets an identity verification response.
        $response = $identityVerificationServiceClient->getIdentityVerification(
            GetIdentityVerificationRequest::build($customerId)
        );
        if (empty($response->getIdentityVerification())) {
            return null;
        }

        // Prints some details about the retrieved identity verification.
        /** @var IdentityVerification $identityVerification */
        $identityVerification = $response->getIdentityVerification()->getIterator()->current();
        $deadline = $identityVerification->getIdentityVerificationRequirement()
            ->getVerificationCompletionDeadlineTime();
        $progress = $identityVerification->getVerificationProgress();
        printf(
            "Account %d has a verification completion deadline of '%s' and status '%s' for"
            . " advertiser identity verification.%s",
            $customerId,
            $deadline,
            IdentityVerificationProgramStatus::name($progress->getProgramStatus()),
            PHP_EOL
        );

        return $identityVerification;
    }

    /**
     * Starts the identity verification process.
     *
     * @param int $customerId the customer ID
     * @param IdentityVerificationServiceClient $identityVerificationServiceClient the identity
     *     verification service client
     */
    private static function startIdentityVerification(
        int $customerId,
        IdentityVerificationServiceClient $identityVerificationServiceClient
    ): void {
        // Sends a request to start the identity verification process.
        $identityVerificationServiceClient->startIdentityVerification(
            StartIdentityVerificationRequest::build(
                $customerId,
                IdentityVerificationProgram::ADVERTISER_IDENTITY_VERIFICATION
            )
        );
    }
}

VerifyAdvertiserIdentity::main();

      

Python

#!/usr/bin/env python
# Copyright 2024 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.
"""Retrieves the status of the advertiser identity verification program.

If required and not already started, it also starts the verification process.
"""


import argparse
import sys

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


def main(client, customer_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: The client customer ID str.
    """
    # Retrieve the current advertiser identity verification status.
    identity_verification = get_identity_verification(client, customer_id)

    if identity_verification:
        status = identity_verification.verification_progress.program_status
        status_enum = client.enums.IdentityVerificationProgramStatusEnum

        if status == status_enum.UNSPECIFIED:
            # Starts an identity verification session.
            start_identity_verification(client, customer_id)
            # Call get_identity_verification again to retrieve the verification
            # progress after starting an identity verification session.
            get_identity_verification(client, customer_id)
        elif status == status_enum.PENDING_USER_ACTION:
            # If there is an identity verification session in progress, there
            # is no need to start another one by calling
            # StartIdentityVerification.
            verification_progress = identity_verification.verification_progress
            print(
                "There is an advertiser identity verification session in "
                "progress. The URL for the verification process is: "
                f"{verification_progress.action_url} and it will expire at "
                f"{verification_progress.invitation_link_expiration_time}."
            )
        elif status == status == status_enum.PENDING_REVIEW:
            print("The verification is under review.")
        elif status == status == status_enum.SUCCESS:
            print("The verification completed successfully.")
        else:
            print("The verification has an unknown state.")
    else:
        # If get_identity_verification returned None, the account is not
        # enrolled in mandatory identity verification.
        print(
            f"Account {customer_id} is not required to perform advertiser "
            "identity verification. See "
            "https://support.google.com/adspolicy/answer/9703665 for details "
            "on how and when an account is required to undergo the advertiser "
            "identity verification program."
        )


def get_identity_verification(client, customer_id):
    """Retrieves the status of the advertiser identity verification process.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: The client customer ID str.

    Returns:
        either an IdentityVerification instance, or None
    """
    service = client.get_service("IdentityVerificationService")
    response = service.get_identity_verification(customer_id=customer_id)

    # Check if the response contains any indentity verifications. If not, then
    # None will be returned.
    if response.identity_verification:
        identity_verification = response.identity_verification[0]
        deadline = (
            identity_verification.identity_verification_requirement.verification_completion_deadline_time
        )
        progress = identity_verification.verification_progress.program_status

        print(
            f"Account {customer_id} has a verification completion deadline "
            f"of {deadline} and status {progress} for advertiser identity "
            "verification."
        )

        return identity_verification


def start_identity_verification(client, customer_id):
    """Starts the identity verification process.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: The client customer ID str.
    """
    service = client.get_service("IdentityVerificationService")
    # Sends a request to start the identity verification process.
    service.start_identity_verification(
        customer_id=customer_id,
        verification_program=client.enums.IdentityVerificationProgramEnum.ADVERTISER_IDENTITY_VERIFICATION,
    )


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=(
            "Retrieves the status of the advertiser identity verification "
            "program. If required and not already started, it also starts the "
            "verification process."
        )
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

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

    try:
        main(googleads_client, args.customer_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 2024 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 code example illustrates how to retrieve the status of the advertiser
# identity verification program and, if required and not already started, how
# to start the verification process.

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

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

  client.configure do |config|
    config.login_customer_id = customer_id
  end

  identity_verification = get_identity_verification(client, customer_id)

  if identity_verification.nil?
    puts "Account #{customer_id} is not required to perform mandatory identity verification."
    puts "See https://support.google.com/adspolicy/answer/9703665 for details on how " \
      "and when an account is required to undergo the advertiser identity " \
      "verification program."
  else
    if identity_verification.verification_progress.action_url.nil?
      start_identity_verification(client, customer_id)

      # Call GetIdentityVerification again to retrieve the verification
      # progress after starting an identity verification session.
      get_identity_verification(client, customer_id)
    else
      # If there is an identity verification session in progress, there is no
      # need to start another one by calling start_identity_verification.
      puts "There is an advertiser identity verification session in progress."

      progress = identity_verification.verification_progress
      puts "The URL for the verification process is #{progress.action_url} and " \
        "it will expire at #{progress.invitation_link_expiration_time}."
    end
  end
end

def get_identity_verification(client, customer_id)
  response = client.service.identity_verification.get_identity_verification(
    customer_id: customer_id
  )

  return nil if response.nil? || response.identity_verification.empty?

  identity_verification = response.identity_verification.first
  deadline = identity_verification.
    identity_verification_requirement.
    verification_completion_deadline_time
  progress = identity_verification.verification_progress
  puts "Account #{customer_id} has a verification completion deadline " \
    "of #{deadline} and status #{progress.program_status} for advertiser " \
    "identity verification."

  identity_verification
end

def start_identity_verification(client, customer_id)
  client.service.identity_verification.start_identity_verification(
    customer_id: customer_id,
    verification_program: :ADVERTISER_IDENTITY_VERIFICATION,
  )
end

if __FILE__ == $PROGRAM_NAME
  # Running the example with -h will print the command line usage.
  options = {}

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: ruby %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.separator ''
    opts.separator 'Help:'

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

  begin
    verify_advertiser_identity(options.fetch(:customer_id).tr("-", ""))
  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 2024, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This code example illustrates how to retrieve the status of the advertiser
# identity verification program and, if required and not already started, how
# to start the verification process.

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::V16::Enums::IdentityVerificationProgramEnum
  qw (ADVERTISER_IDENTITY_VERIFICATION);
use
  Google::Ads::GoogleAds::V16::Services::IdentityVerificationService::StartIdentityVerificationRequest;

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

sub verify_advertiser_identity {
  my ($api_client, $customer_id) = @_;

  # Retrieve the current advertiser identity verification status.
  my $identity_verification =
    get_identity_verification($api_client, $customer_id);

  if (defined $identity_verification) {
    if (!defined $identity_verification->{verificationProgress}{actionUrl}) {
      start_identity_verification($api_client, $customer_id);

      # Call get_identity_verification again to retrieve the verification progress
      # after starting an identity verification session.
      get_identity_verification($api_client, $customer_id);
    } else {
      # If there is an identity verification session in progress, there is no need
      # to start another one by calling StartIdentityVerification.
      printf "There is an advertiser identity verification session in " .
        "progress.\n The URL for the verification process is: %s and it " .
        "will expire at %s",
        $identity_verification->{verificationProgress}{actionUrl},
        $identity_verification->{verificationProgress}
        {invitationLinkExpirationTime};
    }
  } else {
    # If get_identity_verification returned an empty response, the account is not
    # enrolled in mandatory identity verification.
    printf "Account $customer_id is not required to perform identity " .
      "verification.\n See https://support.google.com/adspolicy/answer/9703665 "
      . "for details on how and when an account is required to undergo the "
      . "advertiser identity verification program.";
  }
  return 1;
}

# Retrieves the status of the advertiser identity verification process.
sub get_identity_verification {
  my ($api_client, $customer_id) = @_;

  my $response = $api_client->IdentityVerificationService()->get({
    customerId => $customer_id
  });

  if (!defined $response->{identityVerification}) {
    printf "Account %s does not require advertiser identity verification.",
      $customer_id;
    return;
  }

  my $identity_verification = $response->{identityVerification}[0];
  my $deadline = $identity_verification->{identityVerificationRequirement}
    {verificationCompletionDeadlineTime};
  my $identity_verification_progress =
    $identity_verification->{verificationProgress};

  printf "Account %s has a verification completion deadline of %s and status " .
    "%s for advertiser identity verification.", $customer_id, $deadline,
    $identity_verification_progress->{programStatus};
  return $identity_verification;
}

# Starts the identity verification process.
sub start_identity_verification {
  my ($api_client, $customer_id) = @_;

  my $request =
    Google::Ads::GoogleAds::V16::Services::IdentityVerificationService::StartIdentityVerificationRequest
    ->new({
      customerId          => $customer_id,
      verificationProgram => ADVERTISER_IDENTITY_VERIFICATION
    });

  $api_client->AdvertiserIdentityVerificationService()
    ->start_identity_verification($request);
}

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

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_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.
verify_advertiser_identity($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

verify_advertiser_identity

=head1 DESCRIPTION

This code example retrieves the status of the advertiser identity verification
program and, if required and not already started, starts the verification process.

=head1 SYNOPSIS

verify_advertiser_identity.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut