Dodaj połączenie

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

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.v11.common.AdScheduleInfo;
import com.google.ads.googleads.v11.common.CallAsset;
import com.google.ads.googleads.v11.enums.AssetFieldTypeEnum.AssetFieldType;
import com.google.ads.googleads.v11.enums.CallConversionReportingStateEnum.CallConversionReportingState;
import com.google.ads.googleads.v11.enums.DayOfWeekEnum.DayOfWeek;
import com.google.ads.googleads.v11.enums.MinuteOfHourEnum.MinuteOfHour;
import com.google.ads.googleads.v11.errors.GoogleAdsError;
import com.google.ads.googleads.v11.errors.GoogleAdsException;
import com.google.ads.googleads.v11.resources.CustomerAsset;
import com.google.ads.googleads.v11.services.AssetServiceClient;
import com.google.ads.googleads.v11.services.CustomerAssetOperation;
import com.google.ads.googleads.v11.services.CustomerAssetServiceClient;
import com.google.ads.googleads.v11.services.MutateAssetsResponse;
import com.google.ads.googleads.v11.services.MutateCustomerAssetsResponse;
import com.google.ads.googleads.v11.utils.ResourceNames;
import com.google.ads.googleads.v11.resources.Asset;
import com.google.ads.googleads.v11.services.AssetOperation;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/** This example adds a call extension to a specific account. */
public class AddCall {
  private static class AddCallParams extends CodeSampleParams {

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

    // 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 {
    AddCallParams params = new AddCallParams();
    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.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 AddCall()
          .runExample(
              googleAdsClient,
              params.customerId,
              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 phoneCountry the phone country (2-letter code).
   * @param phoneNumber the raw phone number, e.g. '(123) 456-7890'.
   * @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,
      String phoneCountry,
      String phoneNumber,
      Integer conversionActionId) {
    // Creates the asset for the call extensions.
    String assetResourceName =
        addExtensionAsset(
            googleAdsClient, customerId, phoneCountry, phoneNumber, conversionActionId);

    // Adds the extensions at the account level, so these will serve in all eligible campaigns.
    linkAssetToAccount(googleAdsClient, customerId, assetResourceName);
  }

  /**
   * Creates a new asset for the call.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param phoneCountry the phone country (2-letter code).
   * @param phoneNumber the raw phone number, e.g. '(123) 456-7890'.
   * @param conversionActionId the conversion action ID to attribute conversions to.
   * @return resource name of the newly created asset.
   */
  private String addExtensionAsset(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String phoneCountry,
      String phoneNumber,
      Integer conversionActionId) {
    CallAsset.Builder callAssetBuilder =
        CallAsset.newBuilder()
            // Sets the country code and phone number of the business to call.
            .setCountryCode(phoneCountry)
            .setPhoneNumber(phoneNumber)
            // Optional: Specifies all day and time intervals for which the asset may serve.
            .addAdScheduleTargets(
                AdScheduleInfo.newBuilder()
                    // Sets the day of this schedule as Monday.
                    .setDayOfWeek(DayOfWeek.MONDAY)
                    // Sets the start hour to 9am.
                    .setStartHour(9)
                    // Sets the end hour to 5pm.
                    .setEndHour(17)
                    // Sets the start and end minute of zero, for example: 9:00 and 5:00.
                    .setStartMinute(MinuteOfHour.ZERO)
                    .setEndMinute(MinuteOfHour.ZERO)
                    .build());

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

    // Creates an asset operation wrapping the call asset in an asset.
    AssetOperation assetOperation =
        AssetOperation.newBuilder()
            .setCreate(Asset.newBuilder().setCallAsset(callAssetBuilder.build()).build())
            .build();

    // Creates an asset service client.
    try (AssetServiceClient assetServiceClient =
        googleAdsClient.getLatestVersion().createAssetServiceClient()) {
      // Issues a mutate request to add the asset and prints its information.
      MutateAssetsResponse response =
          assetServiceClient.mutateAssets(
              Long.toString(customerId), ImmutableList.of(assetOperation));
      String createdAssetResourceName = response.getResults(0).getResourceName();
      System.out.printf(
          "Created a call asset with resource name: '%s'.%n", createdAssetResourceName);
      return createdAssetResourceName;
    }
  }

  /**
   * Links the call asset at the account level to serve in all eligible campaigns.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param assetResourceName the resource name of the call asset.
   */
  private void linkAssetToAccount(
      GoogleAdsClient googleAdsClient, long customerId, String assetResourceName) {
    // Creates a customer asset operation wrapping the call asset in a customer asset.
    CustomerAssetOperation customerAssetOperation =
        CustomerAssetOperation.newBuilder()
            .setCreate(
                CustomerAsset.newBuilder()
                    .setAsset(assetResourceName)
                    .setFieldType(AssetFieldType.CALL)
                    .build())
            .build();

    // Creates a CustomerAssetServiceClient.
    try (CustomerAssetServiceClient customerAssetServiceClient =
        googleAdsClient.getLatestVersion().createCustomerAssetServiceClient()) {
      // Issues a mutate request to add the customer asset and prints its information.
      MutateCustomerAssetsResponse response =
          customerAssetServiceClient.mutateCustomerAssets(
              Long.toString(customerId), ImmutableList.of(customerAssetOperation));
      System.out.printf(
          "Created a customer asset 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.Util;
using Google.Ads.GoogleAds.V11.Common;
using Google.Ads.GoogleAds.V11.Enums;
using Google.Ads.GoogleAds.V11.Errors;
using Google.Ads.GoogleAds.V11.Resources;
using Google.Ads.GoogleAds.V11.Services;
using Google.Protobuf;
using System.Collections.Generic;
using System.Linq;
using System;
using System.Threading;
using static Google.Ads.GoogleAds.V11.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.AssetFieldTypeEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.CallConversionReportingStateEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.DayOfWeekEnum.Types;
using static Google.Ads.GoogleAds.V11.Enums.MinuteOfHourEnum.Types;

using SystemDayOfWeek = System.DayOfWeek;
using DayOfWeek = Google.Ads.GoogleAds.V11.Enums.DayOfWeekEnum.Types.DayOfWeek;

namespace Google.Ads.GoogleAds.Examples.V11
{
    /// <summary>
    /// This example adds a call extension to a specific account.
    /// </summary>
    public class AddCall : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddCall"/> 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>
            /// 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);

            AddCall codeExample = new AddCall();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(
                new GoogleAdsClient(),
                options.CustomerId,
                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="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,
            string phoneCountry,
            string phoneNumber,
            long? conversionActionId)
        {
            try
            {
                // Creates the asset for the call extensions.
                string assetResourceName = AddExtensionAsset(
                    client,
                    customerId,
                    phoneCountry,
                    phoneNumber,
                    conversionActionId
                );

                // Adds the extensions at the account level, so these will serve in all eligible
                // campaigns.
                LinkAssetToAccount(client, customerId, assetResourceName);
            }
            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 a new asset for the call.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer 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>
        /// <returns>The resource name of the created call asset</returns>
        private string AddExtensionAsset(
            GoogleAdsClient client,
            long customerId,
            string phoneCountry,
            string phoneNumber,
            long? conversionActionId)
        {
            // Creates the call asset.
            CallAsset callAsset = new CallAsset()
            {
                // Sets the country code and phone number of the business to call.
                CountryCode = phoneCountry,
                PhoneNumber = phoneNumber,

                // Optional: Specifies all day and time intervals for which the asset may serve.
                AdScheduleTargets = {
                    new AdScheduleInfo()
                    {
                        // Sets the day of this schedule as Monday.
                        DayOfWeek = DayOfWeek.Monday,

                        // Sets the start hour to 9am.
                        StartHour = 9,

                        // Sets the end hour to 5pm.
                        EndHour = 17,

                        // Sets the start and end minute of zero, for example: 9:00 and 5:00.
                        StartMinute = MinuteOfHour.Zero,
                        EndMinute = MinuteOfHour.Zero
                    }
                }
            };

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

                callAsset.CallConversionReportingState =
                    CallConversionReportingState.UseResourceLevelCallConversionAction;
            }

            // Creates an asset operation wrapping the call asset in an asset.
            AssetOperation assetOperation = new AssetOperation()
            {
                Create = new Asset()
                {
                    CallAsset = callAsset
                }
            };

            AssetServiceClient assetServiceClient =
                client.GetService(Services.V11.AssetService);

            // Issues a mutate request to add the asset and prints its information.
            MutateAssetsResponse response = assetServiceClient.MutateAssets(
                customerId.ToString(),
                new[] { assetOperation }
            );

            string createdAssetResourceName = response.Results.First().ResourceName;

            Console.WriteLine(
                $"Created a call asset with resource name: '{createdAssetResourceName}'."
            );

            return createdAssetResourceName;
        }

        /// <summary>
        /// Links the call asset at the account level to serve in all eligible campaigns.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID.</param>
        /// <param name="assetResourceName">The resource name of the call asset.</param>
        private void LinkAssetToAccount(
            GoogleAdsClient client,
            long customerId,
            string assetResourceName)
        {
            // Creates a customer asset operation wrapping the call asset in a customer asset.
            CustomerAssetOperation customerAssetOperation = new CustomerAssetOperation()
            {
                Create = new CustomerAsset()
                {
                    Asset = assetResourceName,
                    FieldType = AssetFieldType.Call
                }
            };

            CustomerAssetServiceClient customerAssetServiceClient =
                client.GetService(Services.V11.CustomerAssetService);

            // Issues a mutate request to add the customer asset and prints its information.
            MutateCustomerAssetsResponse response = customerAssetServiceClient.MutateCustomerAssets(
                customerId.ToString(),
                new[] { customerAssetOperation }
            );

            string resourceName = response.Results.First().ResourceName;

            Console.WriteLine(
                $"Created a customer asset with resource name: '{resourceName}'."
            );
        }
    }
}

      

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

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\V11\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V11\GoogleAdsException;
use Google\Ads\GoogleAds\Util\V11\ResourceNames;
use Google\Ads\GoogleAds\V11\Common\AdScheduleInfo;
use Google\Ads\GoogleAds\V11\Common\CallAsset;
use Google\Ads\GoogleAds\V11\Enums\AssetFieldTypeEnum\AssetFieldType;
use Google\Ads\GoogleAds\V11\Enums\CallConversionReportingStateEnum\CallConversionReportingState;
use Google\Ads\GoogleAds\V11\Enums\DayOfWeekEnum\DayOfWeek;
use Google\Ads\GoogleAds\V11\Enums\MinuteOfHourEnum\MinuteOfHour;
use Google\Ads\GoogleAds\V11\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V11\Resources\Asset;
use Google\Ads\GoogleAds\V11\Resources\CustomerAsset;
use Google\Ads\GoogleAds\V11\Services\AssetOperation;
use Google\Ads\GoogleAds\V11\Services\CustomerAssetOperation;
use Google\ApiCore\ApiException;

/**
 * This example adds a call extension to a specific account.
 */
class AddCall
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_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::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)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_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 client customer ID
     * @param string $phoneCountry the phone country (2-letter code)
     * @param string $phoneNumber the raw phone number, e.g. '(123) 456-7890'
     * @param int|null $conversionActionId the conversion action ID to attribute conversions to
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $phoneCountry,
        string $phoneNumber,
        ?int $conversionActionId
    ) {
        // Creates the asset for the call extensions.
        $assetResourceName = self::addExtensionAsset(
            $googleAdsClient,
            $customerId,
            $phoneCountry,
            $phoneNumber,
            $conversionActionId
        );

        // Adds the extensions at the account level, so these will serve in all eligible campaigns.
        self::linkAssetToAccount($googleAdsClient, $customerId, $assetResourceName);
    }

    /**
     * Creates a new asset for the call.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $phoneCountry the phone country (2-letter code)
     * @param string $phoneNumber the raw phone number, e.g. '(123) 456-7890'
     * @param int|null $conversionActionId the conversion action ID to attribute conversions to
     * @return string the resource name of the created call asset
     */
    private static function addExtensionAsset(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $phoneCountry,
        string $phoneNumber,
        ?int $conversionActionId
    ): string {
        // Creates the call asset.
        $callAsset = new CallAsset([
            // Sets the country code and phone number of the business to call.
            'country_code' => $phoneCountry,
            'phone_number' => $phoneNumber,
            // Optional: Specifies all day and time intervals for which the asset may serve.
            'ad_schedule_targets' => [new AdScheduleInfo([
                // Sets the day of this schedule as Monday.
                'day_of_week' => DayOfWeek::MONDAY,
                // Sets the start hour to 9am.
                'start_hour' => 9,
                // Sets the end hour to 5pm.
                'end_hour' => 17,
                // Sets the start and end minute of zero, for example: 9:00 and 5:00.
                'start_minute' => MinuteOfHour::ZERO,
                'end_minute' => MinuteOfHour::ZERO
            ])]
        ]);

        // Sets the conversion action ID to the one provided if any.
        if (!is_null($conversionActionId)) {
            $callAsset->setCallConversionAction(
                ResourceNames::forConversionAction($customerId, $conversionActionId)
            );
            $callAsset->setCallConversionReportingState(
                CallConversionReportingState::USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
            );
        }

        // Creates an asset operation wrapping the call asset in an asset.
        $assetOperation = new AssetOperation();
        $assetOperation->setCreate(new Asset(['call_asset' => $callAsset]));

        // Issues a mutate request to add the asset and prints its information.
        $assetServiceClient = $googleAdsClient->getAssetServiceClient();
        $response = $assetServiceClient->mutateAssets($customerId, [$assetOperation]);
        $createdAssetResourceName = $response->getResults()[0]->getResourceName();
        printf(
            "Created a call asset with resource name: '%s'.%s",
            $createdAssetResourceName,
            PHP_EOL
        );

        return $createdAssetResourceName;
    }

    /**
     * Links the call asset at the account level to serve in all eligible campaigns.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the client customer ID
     * @param string $assetResourceName the resource name of the call asset
     */
    private static function linkAssetToAccount(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $assetResourceName
    ): void {
        // Creates a customer asset operation wrapping the call asset in a customer asset.
        $customerAssetOperation = new CustomerAssetOperation();
        $customerAssetOperation->setCreate(new CustomerAsset([
            'asset' => $assetResourceName,
            'field_type' => AssetFieldType::CALL
        ]));

        // Issues a mutate request to add the customer asset and prints its information.
        $customerAssetServiceClient = $googleAdsClient->getCustomerAssetServiceClient();
        $response = $customerAssetServiceClient->mutateCustomerAssets(
            $customerId,
            [$customerAssetOperation]
        );
        printf(
            "Created a customer asset with resource name: '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }
}

AddCall::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 extension to a specific account."""


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, 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.
        phone_number: a phone number for your business, e.g. '(123) 456-7890'.
        phone_country: a two-letter ISO-3166 code.
        conversion_action_id: an ID for a conversion action.
    """
    asset_resource_name = add_extension_asset(
        client, customer_id, phone_number, phone_country, conversion_action_id
    )
    link_asset_to_account(client, customer_id, asset_resource_name)


def add_extension_asset(
    client, customer_id, phone_number, phone_country, conversion_action_id
):
    """Creates a new asset for the call.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        phone_number: a phone number for your business, e.g. '(123) 456-7890'.
        phone_country: a two-letter ISO-3166 code.
        conversion_action_id: an ID for a conversion action.

    Returns:
        a resource name for a new call asset.
    """
    operation = client.get_type("AssetOperation")
    # Creates the call asset.
    asset = operation.create.call_asset
    asset.country_code = phone_country
    asset.phone_number = phone_number
    # Optional: Specifies day and time intervals for which the asset may serve.
    ad_schedule = client.get_type("AdScheduleInfo")
    # Sets the day of this schedule as Monday.
    ad_schedule.day_of_week = client.enums.DayOfWeekEnum.MONDAY
    # Sets the start hour to 9am.
    ad_schedule.start_hour = 9
    # Sets the end hour to 5pm.
    ad_schedule.end_hour = 17
    # Sets the start and end minute of zero, for example: 9:00 and 5:00.
    ad_schedule.start_minute = client.enums.MinuteOfHourEnum.ZERO
    ad_schedule.end_minute = client.enums.MinuteOfHourEnum.ZERO
    # Appends the ad schedule to the list of ad schedule targets on the asset.
    asset.ad_schedule_targets.append(ad_schedule)

    # Sets the conversion action ID if provided.
    if conversion_action_id:
        googleads_service = client.get_service("GoogleAdsService")
        asset.call_conversion_action = googleads_service.conversion_action_path(
            customer_id, conversion_action_id
        )
        asset.call_conversion_reporting_state = (
            client.enums.CallConversionReportingStateEnum.USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
        )

    # Issues a mutate request to add the asset.
    asset_service = client.get_service("AssetService")
    response = asset_service.mutate_assets(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created a call asset with resource name: '{resource_name}'")

    return resource_name


def link_asset_to_account(client, customer_id, asset_resource_name):
    """Links the call asset at the account level to serve in eligible campaigns.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
        asset_resource_name: a resource name for the call asset.
    """
    operation = client.get_type("CustomerAssetOperation")
    customer_asset = operation.create
    customer_asset.asset = asset_resource_name
    customer_asset.field_type = client.enums.AssetFieldTypeEnum.CALL

    customer_asset_service = client.get_service("CustomerAssetService")
    response = customer_asset_service.mutate_customer_assets(
        customer_id=customer_id, operations=[operation]
    )
    resource_name = response.results[0].resource_name
    print(f"Created a customer asset 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="v11")

    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(
        "-n",
        "--phone_number",
        type=str,
        required=True,
        help=("A phone number for your business, e.g. '(123) 456-7890'"),
    )
    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.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 extension to a specific account.

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

def add_call(customer_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

  asset_resource_name = add_extension_asset(client,
    customer_id,
    phone_number,
    phone_country,
    conversion_action_id)
  link_asset_to_account(client, customer_id, asset_resource_name)
end

def add_extension_asset(client,
    customer_id,
    phone_number,
    phone_country,
    conversion_action_id)
  # Creates the call asset.
  operation = client.operation.create_resource.asset do |asset|
    asset.type = :CALL
    asset.call_asset = client.resource.call_asset do |ca|
      ca.country_code = phone_country
      ca.phone_number = phone_number
      # Optional: Specifies day and time intervals for which the asset may serve.
      ad_schedule = client.resource.ad_schedule_info do |as|
        # Sets the day of this schedule as Monday.
        as.day_of_week = :MONDAY
        # Sets the start hour to 9am.
        as.start_hour = 9
        # Sets the end hour to 5pm.
        as.end_hour = 17
        # Sets the start and end minute of zero, for example: 9:00 and 5:00.
        as.start_minute = :ZERO
        as.end_minute = :ZERO
      end
      # Appends the ad schedule to the list of ad schedule targets on the asset.
      ca.ad_schedule_targets << ad_schedule

      # Sets the conversion action ID if provided.
      if conversion_action_id
        ca.call_conversion_action = client.path.
          conversion_action(customer_id, conversion_action_id)
        ca.call_conversion_reporting_state = :USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION
      end
    end
  end

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

  resource_name
end


def link_asset_to_account(client, customer_id, asset_resource_name)
  operation = client.operation.create_resource.customer_asset do |ca|
    ca.asset = asset_resource_name
    ca.field_type = :CALL
  end

  response = client.service.customer_asset.mutate_customer_assets(
    customer_id: customer_id,
    operations: [operation],
  )
  resource_name = response.results.first.resource_name
  puts "Created a customer asset 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[: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('-N', '--phone-number PHONE-NUMBER', String,
        "A phone number for your business, e.g. '(123) 456-7890'") 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(
      options.fetch(:customer_id).tr("-", ""),
      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 extension to a specific account.

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::V11::Resources::Asset;
use Google::Ads::GoogleAds::V11::Resources::CustomerAsset;
use Google::Ads::GoogleAds::V11::Common::CallAsset;
use Google::Ads::GoogleAds::V11::Common::AdScheduleInfo;
use Google::Ads::GoogleAds::V11::Enums::DayOfWeekEnum qw(MONDAY);
use Google::Ads::GoogleAds::V11::Enums::MinuteOfHourEnum qw(ZERO);
use Google::Ads::GoogleAds::V11::Enums::CallConversionReportingStateEnum
  qw(USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION);
use Google::Ads::GoogleAds::V11::Enums::AssetFieldTypeEnum qw(CALL);
use Google::Ads::GoogleAds::V11::Services::AssetService::AssetOperation;
use
  Google::Ads::GoogleAds::V11::Services::CustomerAssetService::CustomerAssetOperation;
use Google::Ads::GoogleAds::V11::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";
# 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 {
  my ($api_client, $customer_id, $phone_country, $phone_number,
    $conversion_action_id)
    = @_;

  # Create the asset for the call extensions.
  my $asset_resource_name =
    add_extension_asset($api_client, $customer_id, $phone_country,
    $phone_number, $conversion_action_id);

  # Add the extensions at the account level, so these will serve in all eligible campaigns.
  link_asset_to_account($api_client, $customer_id, $asset_resource_name);

  return 1;
}

# Creates a new asset for the call.
sub add_extension_asset {
  my ($api_client, $customer_id, $phone_country,
    $phone_number, $conversion_action_id)
    = @_;

  # Create the call asset.
  my $call_asset = Google::Ads::GoogleAds::V11::Common::CallAsset->new({
      # Set the country code and phone number of the business to call.
      countryCode => $phone_country,
      phoneNumber => $phone_number,
      # Optional: Specify all day and time intervals for which the asset may serve.
      adScheduleTargets => [
        Google::Ads::GoogleAds::V11::Common::AdScheduleInfo->new({
            # Set the day of this schedule as Monday.
            dayOfWeek => MONDAY,
            # Set the start hour to 9am.
            startHour => 9,
            # Set the end hour to 5pm.
            endHour => 17,
            # Set the start and end minute of zero, for example: 9:00 and 5:00.
            startMinute => ZERO,
            endMinute   => ZERO
          })]});

  # Set the conversion action ID to the one provided if any.
  if (defined $conversion_action_id) {
    $call_asset->{callConversionAction} =
      Google::Ads::GoogleAds::V11::Utils::ResourceNames::conversion_action(
      $customer_id, $conversion_action_id);
    $call_asset->{callConversionReportingState} =
      USE_RESOURCE_LEVEL_CALL_CONVERSION_ACTION;
  }

  # Create an asset operation wrapping the call asset in an asset.
  my $asset_operation =
    Google::Ads::GoogleAds::V11::Services::AssetService::AssetOperation->new({
      create => Google::Ads::GoogleAds::V11::Resources::Asset->new({
          callAsset => $call_asset
        })});

  # Issue a mutate request to add the asset and print its information.
  my $response = $api_client->AssetService()->mutate({
      customerId => $customer_id,
      operations => [$asset_operation]});
  my $resource_name = $response->{results}[0]{resourceName};
  printf "Created a call asset with resource name: '%s'.\n", $resource_name;
  return $resource_name;
}

# Links the call asset at the account level to serve in all eligible campaigns.
sub link_asset_to_account {
  my ($api_client, $customer_id, $asset_resource_name) = @_;

  # Create a customer asset operation wrapping the call asset in a customer asset.
  my $customer_asset_operation =
    Google::Ads::GoogleAds::V11::Services::CustomerAssetService::CustomerAssetOperation
    ->new({
      create => Google::Ads::GoogleAds::V11::Resources::CustomerAsset->new({
          asset     => $asset_resource_name,
          fieldType => CALL
        })});

  # Issue a mutate request to add the customer asset and print its information.
  my $response = $api_client->CustomerAssetService()->mutate({
      customerId => $customer_id,
      operations => [$customer_asset_operation]});
  printf "Created a customer asset with resource name: '%s'.\n",
    $response->{results}[0]{resourceName};
}

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

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

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

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

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

=pod

=head1 NAME

add_call

=head1 DESCRIPTION

This example adds a call extension to a specific account.

=head1 SYNOPSIS

add_call.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -phone_country              [optional] The phone country (2-letter code).
    -phone_number               The raw phone number, e.g. "(123) 456-7890".
    -conversion_action_id       [optional] The conversion action ID to attribute conversions to.

=cut