Add Call Ad

Java

// Copyright 2022 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.advancedoperations;

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.common.CallAdInfo;
import com.google.ads.googleads.v16.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v16.enums.CallConversionReportingStateEnum.CallConversionReportingState;
import com.google.ads.googleads.v16.errors.GoogleAdsError;
import com.google.ads.googleads.v16.errors.GoogleAdsException;
import com.google.ads.googleads.v16.resources.Ad;
import com.google.ads.googleads.v16.resources.AdGroupAd;
import com.google.ads.googleads.v16.services.AdGroupAdOperation;
import com.google.ads.googleads.v16.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v16.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v16.utils.ResourceNames;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * This example adds a call ad to a given ad group. More information about call ads can be found at
 * https://support.google.com/google-ads/answer/6341403.
 */
public class AddCallAd {
  private static class AddCallAdParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.AD_GROUP_ID, required = true)
    private Long adGroupId;

    // Specifies the phone country code here or the default specified below will be used.
    // See supported codes at:
    // https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
    @Parameter(names = ArgumentNames.PHONE_COUNTRY, required = true)
    private String phoneCountry = "US";

    @Parameter(names = ArgumentNames.PHONE_NUMBER, required = true)
    private String phoneNumber;

    // Optional: Specifies the conversion action ID to attribute call conversions to. If not set,
    // the default conversion action is used.
    @Parameter(names = ArgumentNames.CONVERSION_ACTION_ID)
    private Integer conversionActionId;
  }

  public static void main(String[] args) throws IOException {
    AddCallAdParams params = new AddCallAdParams();
    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.adGroupId = Long.parseLong("INSERT_AD_GROUP_ID_HERE");
      params.phoneCountry = "US";
      params.phoneNumber = "INSERT_PHONE_NUMBER_HERE";
      // Optional: Specifies the conversion action ID to attribute call conversions to. If not set,
      // the default conversion action is used.
      params.conversionActionId = null;
    }

    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 AddCallAd()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.adGroupId,
              params.phoneCountry,
              params.phoneNumber,
              params.conversionActionId);
    } 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 adGroupId the ad group ID to add a call ad to.
   * @param phoneCountry the phone country (2-letter code).
   * @param phoneNumber the raw phone number, e.g. '(800) 555-0100'.
   * @param conversionActionId the conversion action ID to attribute conversions to.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      long adGroupId,
      String phoneCountry,
      String phoneNumber,
      Integer conversionActionId) {
    // Creates a CallAdInfo Builder.
    CallAdInfo.Builder callAdInfoBuilder =
        CallAdInfo.newBuilder()
            // Sets basic information.
            .setBusinessName("Google")
            .setHeadline1("Travel")
            .setHeadline2("Discover")
            .setDescription1("Travel the World")
            .setDescription2("Travel the Universe")
            // Sets the country code and phone number of the business to call.
            .setCountryCode(phoneCountry)
            .setPhoneNumber(phoneNumber)
            // Sets the verification URL to a webpage that includes the phone number.
            .setPhoneNumberVerificationUrl("https://www.example.com/contact")
            // The fields below are optional.
            // Configures call tracking and reporting.
            .setCallTracked(true)
            .setDisableCallConversion(false)
            // Sets path parts to append for display.
            .setPath1("services")
            .setPath2("travels");

    // Sets the conversion action ID to the one provided if any.
    if (conversionActionId != null) {
      callAdInfoBuilder
          .setConversionAction(ResourceNames.conversionAction(customerId, conversionActionId))
          .setConversionReportingState(
              CallConversionReportingState.USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION);
    }

    // Creates a call ad.
    Ad ad =
        Ad.newBuilder()
            .addFinalUrls("https://www.example.com")
            .setCallAd(callAdInfoBuilder.build())
            .build();

    // Creates an ad group ad for the new ad.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(ResourceNames.adGroup(customerId, adGroupId))
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(ad)
            .build();

    // Creates an ad group ad operation.
    AdGroupAdOperation adGroupAdOperation =
        AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    // Creates an ad group ad service client.
    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      // Issues a mutate request to add the ad group ad.
      MutateAdGroupAdsResponse response =
          adGroupAdServiceClient.mutateAdGroupAds(
              Long.toString(customerId), ImmutableList.of(adGroupAdOperation));
      // Prints information about the newly created ad group ad.
      System.out.printf(
          "Created ad group ad with resource name: '%s'.%n",
          response.getResults(0).getResourceName());
    }
  }
}

      

C#

// Copyright 2022 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.Common;
using Google.Ads.GoogleAds.V16.Errors;
using Google.Ads.GoogleAds.V16.Resources;
using Google.Ads.GoogleAds.V16.Services;
using System.Linq;
using System;
using static Google.Ads.GoogleAds.V16.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V16.Enums.CallConversionReportingStateEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V16
{
    /// <summary>
    /// This example adds a call ad to a given ad group. More information about call ads can be
    /// found at https://support.google.com/google-ads/answer/6341403.
    /// To get ad groups, run GetAdGroups.cs.
    /// </summary>
    public class AddCallAd : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddCallAd"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID.")]
            public long CustomerId { get; set; }

            /// <summary>
            /// The ad group ID.
            /// </summary>
            [Option("adGroupId", Required = true, HelpText =
                "The ad group ID.")]
            public long AdGroupId { get; set; }

            /// <summary>
            /// Optional: The phone number country.
            ///
            /// Specifies the phone country code here or the default specified in <see cref="Main"/>
            /// will be used. See supported codes at:
            /// https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
            /// </summary>
            [Option("phoneCountry", Required = false, HelpText =
                "The phone number country.")]
            public string PhoneCountry { get; set; }

            /// <summary>
            /// The phone number itself.
            /// </summary>
            [Option("phoneNumber", Required = true, HelpText =
                "The phone number itself.")]
            public string PhoneNumber { get; set; }

            /// <summary>
            /// Optional: Specifies the conversion action ID to attribute call conversions
            /// to. If not set, the default conversion action is used.
            /// </summary>
            [Option("conversionActionId", Required = false, HelpText =
                "The conversion action ID.")]
            public long? ConversionActionId { 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);

            AddCallAd codeExample = new AddCallAd();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(
                new GoogleAdsClient(),
                options.CustomerId,
                options.AdGroupId,
                options.PhoneCountry,
                options.PhoneNumber,
                options.ConversionActionId
            );
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This example adds a call ad to a given ad group.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <param name="phoneCountry">The phone number country.</param>
        /// <param name="phoneNumber">The phone number itself.</param>
        /// <param name="conversionActionId">The conversion action ID or null.</param>
        public void Run(
            GoogleAdsClient client,
            long customerId,
            long adGroupId,
            string phoneCountry,
            string phoneNumber,
            long? conversionActionId)
        {
            try
            {
                // Creates an ad group ad for the new ad.
                AdGroupAd adGroupAd = new AdGroupAd()
                {
                    AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
                    Status = AdGroupAdStatus.Paused,
                    Ad = new Ad()
                    {
                        // The URL of the webpage to refer to.
                        FinalUrls = { "https://www.example.com" },
                        CallAd = new CallAdInfo()
                        {
                            BusinessName = "Google",
                            Headline1 = "Travel",
                            Headline2 = "Discover",
                            Description1 = "Travel the World",
                            Description2 = "Travel the Universe",

                            // Sets the country code and phone number of the business to call.
                            CountryCode = phoneCountry,
                            PhoneNumber = phoneNumber,

                            // Sets the verification URL to a webpage that includes the phone
                            // number.
                            PhoneNumberVerificationUrl = "https://www.example.com/contact",

                            // The fields below are optional.

                            // Configures call tracking and reporting.
                            CallTracked = true,
                            DisableCallConversion = false,

                            // Sets path parts to append for display.
                            Path1 = "services",
                            Path2 = "travels",
                        }
                    }
                };

                // Sets the conversion action ID to the one provided if any.
                if (conversionActionId.HasValue)
                {
                    adGroupAd.Ad.CallAd.ConversionAction =
                        ResourceNames.ConversionAction(customerId, conversionActionId.Value);

                    adGroupAd.Ad.CallAd.ConversionReportingState =
                        CallConversionReportingState.UseResourceLevelCallConversionAction;
                }

                // Creates an ad group ad operation.
                AdGroupAdOperation adGroupAdOperation = new AdGroupAdOperation()
                {
                    Create = adGroupAd
                };

                // Issues a mutate request to add the ad group ad.
                AdGroupAdServiceClient adGroupAdServiceClient =
                    client.GetService(Services.V16.AdGroupAdService);

                MutateAdGroupAdsResponse adGroupAdResponse =
                    adGroupAdServiceClient.MutateAdGroupAds(
                        customerId.ToString(),
                        new[] { adGroupAdOperation }
                    );

                string adGroupAdResourceName = adGroupAdResponse.Results.First().ResourceName;

                Console.WriteLine(
                    $"Created ad group ad with resource name: '{adGroupAdResourceName}'."
                );
            }
            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 2022 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\AdvancedOperations;

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\Util\V16\ResourceNames;
use Google\Ads\GoogleAds\V16\Common\CallAdInfo;
use Google\Ads\GoogleAds\V16\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V16\Enums\CallConversionReportingStateEnum\CallConversionReportingState;
use Google\Ads\GoogleAds\V16\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V16\Resources\Ad;
use Google\Ads\GoogleAds\V16\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V16\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V16\Services\MutateAdGroupAdsRequest;
use Google\ApiCore\ApiException;

/**
 * This example adds a call ad to a given ad group. More information about call ads can be
 * found at https://support.google.com/google-ads/answer/6341403.
 * To get ad groups, run GetAdGroups.php.
 */
class AddCallAd
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    private const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
    // Specifies the phone country code here or the default specified below will be used.
    // See supported codes at:
    // https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
    private const PHONE_COUNTRY = 'US';
    private const PHONE_NUMBER = 'INSERT_PHONE_NUMBER_HERE';
    // Optional: Specifies the conversion action ID to attribute call conversions to. If not set,
    // the default conversion action is used.
    private const CONVERSION_ACTION_ID = null;

    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::AD_GROUP_ID => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::PHONE_COUNTRY => GetOpt::OPTIONAL_ARGUMENT,
            ArgumentNames::PHONE_NUMBER => GetOpt::REQUIRED_ARGUMENT,
            ArgumentNames::CONVERSION_ACTION_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)
            // We set this value to true to show how to use GAPIC v2 source code. You can remove the
            // below line if you wish to use the old-style source code. Note that in that case, you
            // probably need to modify some parts of the code below to make it work.
            // For more information, see
            // https://developers.devsite.corp.google.com/google-ads/api/docs/client-libs/php/gapic.
            ->usingGapicV2Source(true)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID,
                $options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_ID,
                $options[ArgumentNames::PHONE_COUNTRY] ?: self::PHONE_COUNTRY,
                $options[ArgumentNames::PHONE_NUMBER] ?: self::PHONE_NUMBER,
                $options[ArgumentNames::CONVERSION_ACTION_ID] ?: self::CONVERSION_ACTION_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 int $adGroupId the ad group ID to add a call ad to
     * @param string $phoneCountry the phone country (2-letter code)
     * @param string $phoneNumber the raw phone number, e.g. '(800) 555-0100'
     * @param int|null $conversionActionId the conversion action ID to attribute conversions to
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        int $adGroupId,
        string $phoneCountry,
        string $phoneNumber,
        ?int $conversionActionId
    ) {
        // Creates an ad group ad for the new ad.
        $adGroupAd = new AdGroupAd([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            'status' => AdGroupAdStatus::PAUSED,
            'ad' => new Ad([
                // The URL of the webpage to refer to.
                'final_urls' => ['https://www.example.com'],
                'call_ad' => new CallAdInfo([
                    // Sets basic information.
                    'business_name' => 'Google',
                    'headline1' => 'Travel',
                    'headline2' => 'Discover',
                    'description1' => 'Travel the World',
                    'description2' => 'Travel the Universe',
                    // Sets the country code and phone number of the business to call.
                    'country_code' => $phoneCountry,
                    'phone_number' => $phoneNumber,
                    // Sets the verification URL to a webpage that includes the phone number.
                    'phone_number_verification_url' => 'https://www.example.com/contact',

                    // The fields below are optional.
                    // Configures call tracking and reporting.
                    'call_tracked' => true,
                    'disable_call_conversion' => false,
                    // Sets path parts to append for display.
                    'path1' => 'services',
                    'path2' => 'travels'
                ])
            ])
        ]);

        // Sets the conversion action ID to the one provided if any.
        if (!is_null($conversionActionId)) {
            $adGroupAd->getAd()->getCallAd()->setConversionAction(
                ResourceNames::forConversionAction($customerId, $conversionActionId)
            );
            $adGroupAd->getAd()->getCallAd()->setConversionReportingState(
                CallConversionReportingState::USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
            );
        }

        // Creates an ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);

        // Issues a mutate request to add the ad group ad.
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
        $adGroupAdResponse = $adGroupAdServiceClient->mutateAdGroupAds(
            MutateAdGroupAdsRequest::build($customerId, [$adGroupAdOperation])
        );

        // Prints information about the newly created ad group ad.
        printf(
            "Created ad group ad with resource name: '%s'.%s",
            $adGroupAdResponse->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

AddCallAd::main();

      

Python

#!/usr/bin/env python
# Copyright 2022 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 adds a call ad to a given ad group.

More information about call ads can be found at:
https://support.google.com/google-ads/answer/6341403.

To get ad group IDs, run basic_operations/get_ad_groups.py.
"""


import argparse
import sys

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

# Country code is a two-letter ISO-3166 code, for a list of all codes see:
# https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
_DEFAULT_PHONE_COUNTRY = "US"


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

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        ad_group_id: an ad group ID.
        phone_number: a phone number for your business, e.g. '(800) 555-0100'.
        phone_country: a two-letter ISO-3166 code.
        conversion_action_id: an ID for a conversion action.
    """
    googleads_service = client.get_service("GoogleAdsService")
    operation = client.get_type("AdGroupAdOperation")
    ad_group_ad = operation.create
    ad_group_ad.ad_group = googleads_service.ad_group_path(
        customer_id, ad_group_id
    )
    ad_group_ad.status = client.enums.AdGroupAdStatusEnum.PAUSED
    ad = ad_group_ad.ad
    # The URL of the webpage to refer to.
    ad.final_urls.append("https://www.example.com")
    # Sets basic information.
    ad.call_ad.business_name = "Google"
    ad.call_ad.headline1 = "Travel"
    ad.call_ad.headline2 = "Discover"
    ad.call_ad.description1 = "Travel the World"
    ad.call_ad.description2 = "Travel the Universe"
    # Sets the country code and phone number of the business to call.
    ad.call_ad.country_code = phone_country
    ad.call_ad.phone_number = phone_number
    # Sets the verification URL to a webpage that includes the phone number.
    ad.call_ad.phone_number_verification_url = "https://www.example.com/contact"

    # The fields below are optional.
    # Configures call tracking and reporting.
    ad.call_ad.call_tracked = True
    ad.call_ad.disable_call_conversion = False
    # Sets path parts to append for display.
    ad.call_ad.path1 = "services"
    ad.call_ad.path2 = "travels"

    # Sets the conversion action ID if provided.
    if conversion_action_id:
        ad.call_ad.conversion_action = googleads_service.conversion_action_path(
            customer_id, conversion_action_id
        )
        ad.call_ad.conversion_reporting_state = (
            client.enums.CallConversionReportingStateEnum.USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
        )

    # Issues a mutate request to add the ad group ad.
    ad_group_ad_service = client.get_service("AdGroupAdService")
    response = ad_group_ad_service.mutate_ad_group_ads(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created ad group ad with resource name: '{resource_name}'")


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="v16")

    parser = argparse.ArgumentParser(
        description=("Adds a call extension to a specific account.")
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-a",
        "--ad_group_id",
        type=str,
        required=True,
        help="An ad group ID.",
    )
    parser.add_argument(
        "-n",
        "--phone_number",
        type=str,
        required=True,
        help=("A phone number for your business, e.g. '(800) 555-0100'"),
    )
    parser.add_argument(
        "-p",
        "--phone_country",
        type=str,
        default=_DEFAULT_PHONE_COUNTRY,
        help=(
            "A two-letter ISO-3166 code representing a country code, for a "
            "list of all codes see: "
            "https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17"
        ),
    )
    parser.add_argument(
        "-v",
        "--conversion_action_id",
        type=str,
        help=("An optional conversion action ID to attribute conversions to."),
    )

    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.ad_group_id,
            args.phone_number,
            args.phone_country,
            args.conversion_action_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'Error 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 2022 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 adds a call ad to a given ad group.
#
# More information about call ads can be found at:
# https://support.google.com/google-ads/answer/6341403.
#
# To get ad group IDs, run basic_operations/get_ad_groups.rb.

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

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

  operation = client.operation.create_resource.ad_group_ad do |aga|
    aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
    aga.status = :PAUSED
    aga.ad = client.resource.ad do |ad|
      # The URL of the webpage to refer to.
      ad.final_urls << "https://www.example.com"
      ad.call_ad = client.resource.call_ad_info do |ca|
        # Sets basic information.
        ca.business_name = "Google"
        ca.headline1 = "Travel"
        ca.headline2 = "Discover"
        ca.description1 = "Travel the World"
        ca.description2 = "Travel the Universe"
        # Sets the country code and phone number of the business to call.
        ca.country_code = phone_country
        ca.phone_number = phone_number
        # Sets the verification URL to a webpage that includes the phone number.
        ca.phone_number_verification_url = "https://www.example.com/contact"
        # The fields below are optional.
        # Configures call tracking and reporting.
        ca.call_tracked = true
        ca.disable_call_conversion = false
        # Sets path parts to append for display.
        ca.path1 = "services"
        ca.path2 = "travels"
        if conversion_action_id
          ca.conversion_action = client.path.
            conversion_action(customer_id, conversion_action_id)
          ca.conversion_reporting_state = :USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
        end
      end
    end
  end

  # Issues a mutate request to add the ad group ad.
  response = client.service.ad_group_ad.mutate_ad_group_ads(
    customer_id: customer_id,
    operations: [operation],
  )
  resource_name = response.results.first.resource_name
  puts "Created ad group ad with resource name: '#{resource_name}'"
end


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

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

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

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

    opts.on('-A', '--ad-group-id AD-GROUP-ID', String, 'An ad group ID.') do |v|
      options[:ad_group_id] = v
    end

    opts.on('-N', '--phone-number PHONE-NUMBER', String,
        "A phone number for your business, e.g. '(800) 555-0100'") do |v|
      options[:phone_number] = v
    end

    opts.on('-P', '--phone-country PHONE-COUNTRY', String,
        'A two-letter ISO-3166 code representing a country code, for a ' \
        'list of all codes see: ' \
        'https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17') do |v|
      options[:phone_country] = v
    end

    opts.on('-V', '--conversion-action-id CONVERSION-ACTION-ID', String,
        'Specifies the conversion action ID to attribute call conversions to. ' \
        'If not set, the default conversion action is used.') do |v|
      options[:conversion_action_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_call_ad(
      options.fetch(:customer_id).tr("-", ""),
      options[:ad_group_id],
      options[:phone_number],
      options.fetch(:phone_country, 'US'),
      options[:conversion_action_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 2022, 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 adds a call ad to a given ad group. More information about call ads
# can be found at https://support.google.com/google-ads/answer/6341403.
# To get ad groups, run get_ad_groups.pl.

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::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V16::Resources::Ad;
use Google::Ads::GoogleAds::V16::Common::CallAdInfo;
use Google::Ads::GoogleAds::V16::Enums::AdGroupAdStatusEnum qw(PAUSED);
use Google::Ads::GoogleAds::V16::Enums::CallConversionReportingStateEnum
  qw(USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION);
use Google::Ads::GoogleAds::V16::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V16::Utils::ResourceNames;

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

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";
my $ad_group_id = "INSERT_AD_GROUP_ID_HERE";
# Specify the phone country code here or the default specified below will be used.
# See supported codes at:
# https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-17
my $phone_country = "US";
my $phone_number  = "INSERT_PHONE_NUMBER_HERE";
# Optional: Specify the conversion action ID to attribute call conversions to.
# If not set, the default conversion action is used.
my $conversion_action_id = undef;

sub add_call_ad {
  my ($api_client, $customer_id, $ad_group_id, $phone_country, $phone_number,
    $conversion_action_id)
    = @_;

  # Create an ad group ad for the new ad.
  my $ad_group_ad = Google::Ads::GoogleAds::V16::Resources::AdGroupAd->new({
      adGroup => Google::Ads::GoogleAds::V16::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      status => PAUSED,
      ad     => Google::Ads::GoogleAds::V16::Resources::Ad->new({
          # The URL of the webpage to refer to.
          finalUrls => ["https://www.example.com"],
          callAd    => Google::Ads::GoogleAds::V16::Common::CallAdInfo->new({
              # Set basic information.
              businessName => "Google",
              headline1    => "Travel",
              headline2    => "Discover",
              description1 => "Travel the World",
              description2 => "Travel the Universe",
              # Set the country code and phone number of the business to call.
              countryCode => $phone_country,
              phoneNumber => $phone_number,
              # Set the verification URL to a webpage that includes the phone number.
              phoneNumberVerificationUrl => "https://www.example.com/contact",

              # The fields below are optional.
              # Configure call tracking and reporting.
              callTracked           => "true",
              disableCallConversion => "false",
              # Set path parts to append for display.
              path1 => "services",
              path2 => "travels"
            })})});

  # Set the conversion action ID to the one provided if any.
  if (defined $conversion_action_id) {
    $ad_group_ad->{ad}{callAd}{conversionAction} =
      Google::Ads::GoogleAds::V16::Utils::ResourceNames::conversion_action(
      $customer_id, $conversion_action_id);
    $ad_group_ad->{ad}{callAd}{conversionReportingState} =
      USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION;
  }

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V16::Services::AdGroupAdService::AdGroupAdOperation
    ->new({
      create => $ad_group_ad
    });

  # Issue a mutate request to add the ad group ad.
  my $ad_group_ad_response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_ad_operation]});

  # Print information about the newly created ad group ad.
  printf "Created ad group ad with resource name: '%s'.\n",
    $ad_group_ad_response->{results}[0]{resourceName};

  return 1;
}

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

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

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

# Parameters passed on the command line will override any parameters set in code.
GetOptions(
  "customer_id=s"          => \$customer_id,
  "ad_group_id=i"          => \$ad_group_id,
  "phone_country=s"        => \$phone_country,
  "phone_number=s"         => \$phone_number,
  "conversion_action_id=i" => \$conversion_action_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, $ad_group_id, $phone_country, $phone_number);

# Call the example.
add_call_ad(
  $api_client,    $customer_id =~ s/-//gr, $ad_group_id,
  $phone_country, $phone_number,           $conversion_action_id
);

=pod

=head1 NAME

add_call_ad

=head1 DESCRIPTION

This example adds a call ad to a given ad group. More information about call ads
can be found at https://support.google.com/google-ads/answer/6341403.
To get ad groups, run get_ad_groups.pl.

=head1 SYNOPSIS

add_call_ad.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -ad_group_id                The ad group ID to add a call ad to.
    -phone_country              [optional] The phone country (2-letter code).
    -phone_number               The raw phone number, e.g. "(800) 555-0100".
    -conversion_action_id       [optional] The conversion action ID to attribute conversions to.

=cut