Sử dụng chiến lược đặt giá thầu danh mục đầu tư

Java

// Copyright 2018 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 static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

import com.beust.jcommander.Parameter;
import com.google.ads.googleads.examples.utils.ArgumentNames;
import com.google.ads.googleads.examples.utils.CodeSampleParams;
import com.google.ads.googleads.lib.GoogleAdsClient;
import com.google.ads.googleads.v17.common.TargetSpend;
import com.google.ads.googleads.v17.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v17.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod;
import com.google.ads.googleads.v17.enums.CampaignStatusEnum.CampaignStatus;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.BiddingStrategy;
import com.google.ads.googleads.v17.resources.Campaign;
import com.google.ads.googleads.v17.resources.Campaign.NetworkSettings;
import com.google.ads.googleads.v17.resources.CampaignBudget;
import com.google.ads.googleads.v17.services.BiddingStrategyOperation;
import com.google.ads.googleads.v17.services.BiddingStrategyServiceClient;
import com.google.ads.googleads.v17.services.CampaignBudgetOperation;
import com.google.ads.googleads.v17.services.CampaignBudgetServiceClient;
import com.google.ads.googleads.v17.services.CampaignOperation;
import com.google.ads.googleads.v17.services.CampaignServiceClient;
import com.google.ads.googleads.v17.services.MutateBiddingStrategiesResponse;
import com.google.ads.googleads.v17.services.MutateBiddingStrategyResult;
import com.google.ads.googleads.v17.services.MutateCampaignBudgetResult;
import com.google.ads.googleads.v17.services.MutateCampaignBudgetsResponse;
import com.google.ads.googleads.v17.services.MutateCampaignResult;
import com.google.ads.googleads.v17.services.MutateCampaignsResponse;
import com.google.ads.googleads.v17.utils.ResourceNames;
import com.google.common.collect.Lists;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.annotation.Nullable;

/** Adds a portfolio bidding strategy and uses it to construct a campaign. */
public class UsePortfolioBiddingStrategy {

  private static class UsePortfolioBiddingStrategyParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.CAMPAIGN_BUDGET_ID)
    private Long campaignBudgetId;
  }

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

      // Optional: Specify a campaign budget ID here if you'd like to use an existing shared budget.
      params.campaignBudgetId = 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 UsePortfolioBiddingStrategy()
          .runExample(googleAdsClient, params.customerId, params.campaignBudgetId);
    } 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 campaignBudgetId the ID of the shared budget to use. If null, this example will create a
   *     new shared budget.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient, Long customerId, @Nullable Long campaignBudgetId) {
    String biddingStrategyResourceName = createBiddingStrategy(googleAdsClient, customerId);
    String campaignBudgetResourceName = null;
    if (campaignBudgetId == null) {
      campaignBudgetResourceName = createSharedCampaignBudget(googleAdsClient, customerId);
    } else {
      campaignBudgetResourceName = ResourceNames.campaignBudget(customerId, campaignBudgetId);
    }

    createCampaignWithBiddingStrategy(
        googleAdsClient, customerId, biddingStrategyResourceName, campaignBudgetResourceName);
  }

  /**
   * Creates the bidding strategy object.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String createBiddingStrategy(GoogleAdsClient googleAdsClient, long customerId) {
    try (BiddingStrategyServiceClient biddingStrategyServiceClient =
        googleAdsClient.getLatestVersion().createBiddingStrategyServiceClient()) {
      // Creates a portfolio bidding strategy.
      TargetSpend targetSpend = TargetSpend.newBuilder().setCpcBidCeilingMicros(2_000_000L).build();
      BiddingStrategy portfolioBiddingStrategy =
          BiddingStrategy.newBuilder()
              .setName("Maximize Clicks #" + getPrintableDateTime())
              .setTargetSpend(targetSpend)
              .build();
      // Constructs an operation that will create a portfolio bidding strategy.
      BiddingStrategyOperation operation =
          BiddingStrategyOperation.newBuilder().setCreate(portfolioBiddingStrategy).build();
      // Sends the operation in a mutate request.
      MutateBiddingStrategiesResponse response =
          biddingStrategyServiceClient.mutateBiddingStrategies(
              Long.toString(customerId), Lists.newArrayList(operation));

      MutateBiddingStrategyResult mutateBiddingStrategyResult = response.getResults(0);
      // Prints the resource name of the created object.
      System.out.printf(
          "Created portfolio bidding strategy with resource name: '%s'.%n",
          mutateBiddingStrategyResult.getResourceName());

      return mutateBiddingStrategyResult.getResourceName();
    }
  }

  /**
   * Creates an explicit budget to be used only to create the campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String createSharedCampaignBudget(GoogleAdsClient googleAdsClient, long customerId) {
    try (CampaignBudgetServiceClient campaignBudgetServiceClient =
        googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) {
      // Creates a shared budget.
      CampaignBudget budget =
          CampaignBudget.newBuilder()
              .setName("Shared Interplanetary Budget #" + getPrintableDateTime())
              .setAmountMicros(50_000_000L)
              .setDeliveryMethod(BudgetDeliveryMethod.STANDARD)
              .setExplicitlyShared(true)
              .build();
      // Constructs an operation that will create a shared budget.
      CampaignBudgetOperation operation =
          CampaignBudgetOperation.newBuilder().setCreate(budget).build();
      // Sends the operation in a mutate request.
      MutateCampaignBudgetsResponse response =
          campaignBudgetServiceClient.mutateCampaignBudgets(
              Long.toString(customerId), Lists.newArrayList(operation));

      MutateCampaignBudgetResult mutateCampaignBudgetResult = response.getResults(0);
      // Prints the resource name of the created object.
      System.out.printf(
          "Created shared budget with resource name: '%s'.%n",
          mutateCampaignBudgetResult.getResourceName());

      return mutateCampaignBudgetResult.getResourceName();
    }
  }

  /**
   * Create a Campaign with a portfolio bidding strategy.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param biddingStrategyResourceName the bidding strategy resource name to use
   * @param campaignBudgetResourceName the shared budget resource name to use
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private String createCampaignWithBiddingStrategy(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String biddingStrategyResourceName,
      String campaignBudgetResourceName) {
    try (CampaignServiceClient campaignServiceClient =
        googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
      // Creates the campaign.
      NetworkSettings networkSettings =
          NetworkSettings.newBuilder()
              .setTargetGoogleSearch(true)
              .setTargetSearchNetwork(true)
              .setTargetContentNetwork(true)
              .build();
      Campaign campaign =
          Campaign.newBuilder()
              .setName("Interplanetary Cruise #" + getPrintableDateTime())
              .setStatus(CampaignStatus.PAUSED)
              .setCampaignBudget(campaignBudgetResourceName)
              .setBiddingStrategy(biddingStrategyResourceName)
              .setAdvertisingChannelType(AdvertisingChannelType.SEARCH)
              .setNetworkSettings(networkSettings)
              .build();
      // Constructs an operation that will create a campaign.
      CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
      // Sends the operation in a mutate request.
      MutateCampaignsResponse response =
          campaignServiceClient.mutateCampaigns(
              Long.toString(customerId), Lists.newArrayList(operation));

      MutateCampaignResult mutateCampaignResult = response.getResults(0);
      // Prints the resource name of the created object.
      System.out.printf(
          "Created campaign with resource name: '%s'.%n", mutateCampaignResult.getResourceName());

      return mutateCampaignResult.getResourceName();
    }
  }
}

      

C#

// Copyright 2019 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.V17.Common;
using Google.Ads.GoogleAds.V17.Enums;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V17.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Resources.Campaign.Types;

namespace Google.Ads.GoogleAds.Examples.V17
{
    /// <summary>
    /// This code example adds a portfolio bidding strategy and uses it to construct a campaign.
    /// </summary>
    public class UsePortfolioBiddingStrategy : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="UsePortfolioBiddingStrategy"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the call is made.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the call is made.")]
            public long CustomerId { get; set; }
        }

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

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds a portfolio bidding strategy and uses it to construct a " +
            "campaign.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            try
            {
                // Create the portfolio bidding strategy.
                string BIDDINGSTRATEGY_NAME = "Maximize Clicks " +
                    ExampleUtilities.GetRandomString();
                const long BID_CEILING = 2000000;

                string portfolioBiddingStrategy = CreatePortfolioBiddingStrategy(
                    client, customerId, BIDDINGSTRATEGY_NAME, BID_CEILING);

                Console.WriteLine("Portfolio bidding strategy with resource name '{0}' " +
                    "was created.", portfolioBiddingStrategy);

                // Create the shared budget.
                string BUDGET_NAME = "Shared Interplanetary Budget #" +
                    ExampleUtilities.GetRandomString();
                const long BUDGET_AMOUNT = 30000000;

                string sharedBudget = CreateSharedBudget(client, customerId, BUDGET_NAME,
                    BUDGET_AMOUNT);

                Console.WriteLine("Shared budget with resource name '{0}' was created.",
                    sharedBudget);

                // Create the campaign.
                string CAMPAIGN_NAME = "Interplanetary Cruise #" +
                    ExampleUtilities.GetRandomString();

                string newCampaign = CreateCampaignWithBiddingStrategy(client, customerId,
                    CAMPAIGN_NAME, portfolioBiddingStrategy, sharedBudget);

                Console.WriteLine("Campaign with resource name '{0}' was created.", newCampaign);
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates the portfolio bidding strategy.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="name">The bidding strategy name.</param>
        /// <param name="bidCeiling">The bid ceiling amount in micros.</param>
        /// <returns>The bidding strategy resource name.</returns>
        private string CreatePortfolioBiddingStrategy(GoogleAdsClient client,
            long customerId, string name, long bidCeiling)
        {
            // Get the BiddingStrategyService.
            BiddingStrategyServiceClient biddingStrategyService = client.GetService(
                Services.V17.BiddingStrategyService);

            // Create a portfolio bidding strategy.
            BiddingStrategy biddingStrategy = new BiddingStrategy()
            {
                Name = name,

                TargetSpend = new TargetSpend()
                {
                    CpcBidCeilingMicros = bidCeiling,
                }
            };

            // Create operation.
            BiddingStrategyOperation biddingOperation = new BiddingStrategyOperation()
            {
                Create = biddingStrategy
            };

            // Create the portfolio bidding strategy.
            MutateBiddingStrategiesResponse biddingResponse =
                biddingStrategyService.MutateBiddingStrategies(
                    customerId.ToString(), new BiddingStrategyOperation[] { biddingOperation });

            return biddingResponse.Results[0].ResourceName;
        }

        /// <summary>
        /// Creates a shared campaign budget to be used to create the campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="name">The budget name.</param>
        /// <param name="amount">The budget amount in micros.</param>
        /// <returns>The budget resource name.</returns>
        private string CreateSharedBudget(GoogleAdsClient client, long customerId, string name,
            long amount)
        {
            // Get the CampaignBudgetService.
            CampaignBudgetServiceClient campaignBudgetService =
                client.GetService(Services.V17.CampaignBudgetService);

            // Create a shared budget.
            CampaignBudget budget = new CampaignBudget()
            {
                Name = name,
                AmountMicros = amount,
                DeliveryMethod = BudgetDeliveryMethodEnum.Types.BudgetDeliveryMethod.Standard,
                ExplicitlyShared = true
            };

            // Create the operation.
            CampaignBudgetOperation campaignBudgetOperation = new CampaignBudgetOperation()
            {
                Create = budget
            };

            // Make the mutate request.
            MutateCampaignBudgetsResponse retVal = campaignBudgetService.MutateCampaignBudgets(
                customerId.ToString(), new CampaignBudgetOperation[] { campaignBudgetOperation });
            return retVal.Results[0].ResourceName;
        }

        /// <summary>
        /// Creates the campaign with a portfolio bidding strategy.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="name">The campaign name.</param>
        /// <param name="biddingStrategyResourceName">The bidding strategy id.</param>
        /// <param name="campaignBudgetResourceName">The campaign budget resource name.</param>
        /// <returns>The campaign resource name.</returns>
        private string CreateCampaignWithBiddingStrategy(GoogleAdsClient client,
            long customerId, string name, string biddingStrategyResourceName,
            string campaignBudgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);

            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                Name = name,
                AdvertisingChannelType = AdvertisingChannelType.Search,

                // Recommendation: Set the campaign to PAUSED when creating it to prevent
                // the ads from immediately serving. Set to ENABLED once you've added
                // targeting and the ads are ready to serve.
                Status = CampaignStatus.Paused,

                // Set the campaign budget.
                CampaignBudget = campaignBudgetResourceName,

                // Set bidding strategy (required).
                BiddingStrategy = biddingStrategyResourceName,

                // Set the campaign network options.
                NetworkSettings = new NetworkSettings()
                {
                    TargetGoogleSearch = true,
                    TargetSearchNetwork = true,
                    TargetContentNetwork = true,
                    TargetPartnerSearchNetwork = false
                }
            };

            // Create the operation.
            CampaignOperation operation = new CampaignOperation()
            {
                Create = campaign
            };

            // Create the campaign.
            MutateCampaignsResponse retVal = campaignService.MutateCampaigns(
                customerId.ToString(), new CampaignOperation[] { operation });

            return retVal.Results[0].ResourceName;
        }
    }
}

      

PHP

<?php

/**
 * Copyright 2018 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\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\V17\ResourceNames;
use Google\Ads\GoogleAds\V17\Common\TargetSpend;
use Google\Ads\GoogleAds\V17\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V17\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V17\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\BiddingStrategy;
use Google\Ads\GoogleAds\V17\Resources\Campaign;
use Google\Ads\GoogleAds\V17\Resources\Campaign\NetworkSettings;
use Google\Ads\GoogleAds\V17\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V17\Services\BiddingStrategyOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignOperation;
use Google\Ads\GoogleAds\V17\Services\MutateBiddingStrategiesRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignBudgetsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignsRequest;
use Google\ApiCore\ApiException;

/**
 * This example adds a portfolio bidding strategy and uses it to construct a campaign.
 */
class UsePortfolioBiddingStrategy
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // Optional: Specify a campaign budget ID below to be used to create a campaign. If none is
    // specified, this example will create a new campaign budget.
    private const CAMPAIGN_BUDGET_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::CAMPAIGN_BUDGET_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::CAMPAIGN_BUDGET_ID] ?: self::CAMPAIGN_BUDGET_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|null $campaignBudgetId the ID of the campaign budget to use if any
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        ?int $campaignBudgetId
    ) {
        $biddingStrategyResourceName = self::createBiddingStrategy($googleAdsClient, $customerId);
        if (is_null($campaignBudgetId)) {
            $campaignBudgetResourceName =
                self::createSharedCampaignBudget($googleAdsClient, $customerId);
        } else {
            $campaignBudgetResourceName =
                ResourceNames::forCampaignBudget($customerId, $campaignBudgetId);
        }
        self::createCampaignWithBiddingStrategy(
            $googleAdsClient,
            $customerId,
            $biddingStrategyResourceName,
            $campaignBudgetResourceName
        );
    }

    /**
     * Creates the portfolio bidding strategy.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the resource name of created bidding strategy
     */
    private static function createBiddingStrategy(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a portfolio bidding strategy.
        $portfolioBiddingStrategy = new BiddingStrategy([
            'name' => 'Maximize Clicks #' . Helper::getPrintableDatetime(),
            'target_spend' => new TargetSpend([
                'cpc_bid_ceiling_micros' => 2000000
            ])
        ]);

        // Constructs an operation that will create a portfolio bidding strategy.
        $biddingStrategyOperation = new BiddingStrategyOperation();
        $biddingStrategyOperation->setCreate($portfolioBiddingStrategy);

        // Issues a mutate request to create the bidding strategy.
        $biddingStrategyServiceClient = $googleAdsClient->getBiddingStrategyServiceClient();
        $response = $biddingStrategyServiceClient->mutateBiddingStrategies(
            MutateBiddingStrategiesRequest::build($customerId, [$biddingStrategyOperation])
        );
        /** @var BiddingStrategy $addedBiddingStrategy */
        $addedBiddingStrategy = $response->getResults()[0];

        // Prints out the resource name of the created bidding strategy.
        printf(
            "Created portfolio bidding strategy with resource name: '%s'.%s",
            $addedBiddingStrategy->getResourceName(),
            PHP_EOL
        );

        return $addedBiddingStrategy->getResourceName();
    }

    /**
     * Creates an explicitly shared budget to be used to create the campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the resource name of created shared budget
     */
    private static function createSharedCampaignBudget(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        // Creates a shared budget.
        $budget = new CampaignBudget([
            'name' => 'Shared Interplanetary Budget #' . Helper::getPrintableDatetime(),
            'delivery_method' => BudgetDeliveryMethod::STANDARD,
            // Sets the amount of budget.
            'amount_micros' => 50000000,
            // Makes the budget explicitly shared.
            'explicitly_shared' => true
        ]);

        // Constructs a campaign budget operation.
        $campaignBudgetOperation = new CampaignBudgetOperation();
        $campaignBudgetOperation->setCreate($budget);

        // Issues a mutate request to create the budget.
        $campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
        $response = $campaignBudgetServiceClient->mutateCampaignBudgets(
            MutateCampaignBudgetsRequest::build($customerId, [$campaignBudgetOperation])
        );

        /** @var CampaignBudget $addedBudget */
        $addedBudget = $response->getResults()[0];
        printf(
            "Created a shared budget with resource name '%s'.%s",
            $addedBudget->getResourceName(),
            PHP_EOL
        );

        return $addedBudget->getResourceName();
    }

    /**
     * Creates a campaign with the created portfolio bidding strategy.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $biddingStrategyResourceName the bidding strategy resource name to use
     * @param string $campaignBudgetResourceName the shared budget resource name to use
     */
    private static function createCampaignWithBiddingStrategy(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $biddingStrategyResourceName,
        string $campaignBudgetResourceName
    ) {
        // Creates a Search campaign.
        $campaign = new Campaign([
            'name' => 'Interplanetary Cruise #' . Helper::getPrintableDatetime(),
            'advertising_channel_type' => AdvertisingChannelType::SEARCH,
            // Recommendation: Set the campaign to PAUSED when creating it to prevent
            // the ads from immediately serving. Set to ENABLED once you've added
            // targeting and the ads are ready to serve.
            'status' => CampaignStatus::PAUSED,
            // Configures the campaign network options.
            'network_settings' => new NetworkSettings([
                'target_google_search' => true,
                'target_search_network' => true,
                'target_content_network' => true,
            ]),
            // Sets the bidding strategy and budget.
            'bidding_strategy' => $biddingStrategyResourceName,
            'campaign_budget' => $campaignBudgetResourceName
        ]);

        // Constructs a campaign operation.
        $campaignOperation = new CampaignOperation();
        $campaignOperation->setCreate($campaign);

        // Issues a mutate request to add the campaign.
        $campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
        $response = $campaignServiceClient->mutateCampaigns(
            MutateCampaignsRequest::build($customerId, [$campaignOperation])
        );

        /** @var Campaign $addedCampaign */
        $addedCampaign = $response->getResults()[0];
        printf(
            "Created a campaign with resource name: '%s'.%s",
            $addedCampaign->getResourceName(),
            PHP_EOL
        );
    }
}

UsePortfolioBiddingStrategy::main();

      

Python

#!/usr/bin/env python
# Copyright 2018 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 constructs a campaign with a Portfolio Bidding Strategy."""


import argparse
import sys
import uuid

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


def main(client, customer_id):
    campaign_budget_service = client.get_service("CampaignBudgetService")
    bidding_strategy_service = client.get_service("BiddingStrategyService")
    campaign_service = client.get_service("CampaignService")

    # Create a budget, which can be shared by multiple campaigns.
    campaign_budget_operation = client.get_type("CampaignBudgetOperation")
    campaign_budget = campaign_budget_operation.create
    campaign_budget.name = f"Interplanetary Budget {uuid.uuid4()}"
    campaign_budget.delivery_method = (
        client.enums.BudgetDeliveryMethodEnum.STANDARD
    )
    campaign_budget.amount_micros = 500000
    campaign_budget.explicitly_shared = True

    # Add budget.
    try:
        campaign_budget_response = (
            campaign_budget_service.mutate_campaign_budgets(
                customer_id=customer_id, operations=[campaign_budget_operation]
            )
        )
        campaign_budget_id = campaign_budget_response.results[0].resource_name
        print(f'Budget "{campaign_budget_id}" was created.')
    except GoogleAdsException as ex:
        handle_googleads_exception(ex)

    # Create a portfolio bidding strategy.
    bidding_strategy_operation = client.get_type("BiddingStrategyOperation")
    bidding_strategy = bidding_strategy_operation.create
    bidding_strategy.name = f"Enhanced CPC {uuid.uuid4()}"
    target_spend = bidding_strategy.target_spend
    target_spend.cpc_bid_ceiling_micros = 2000000

    # Add portfolio bidding strategy.
    try:
        bidding_strategy_response = (
            bidding_strategy_service.mutate_bidding_strategies(
                customer_id=customer_id, operations=[bidding_strategy_operation]
            )
        )
        bidding_strategy_id = bidding_strategy_response.results[0].resource_name
        print(f'Created portfolio bidding strategy "{bidding_strategy_id}".')
    except GoogleAdsException as ex:
        handle_googleads_exception(ex)

    # Create campaign.
    campaign_operation = client.get_type("CampaignOperation")
    campaign = campaign_operation.create
    campaign.name = f"Interplanetary Cruise {uuid.uuid4()}"
    campaign.advertising_channel_type = (
        client.enums.AdvertisingChannelTypeEnum.SEARCH
    )

    # Recommendation: Set the campaign to PAUSED when creating it to prevent the
    # ads from immediately serving. Set to ENABLED once you've added targeting
    # and the ads are ready to serve.
    campaign.status = client.enums.CampaignStatusEnum.PAUSED

    # Set the bidding strategy and budget.
    campaign.bidding_strategy = bidding_strategy_id
    campaign.manual_cpc.enhanced_cpc_enabled = True
    campaign.campaign_budget = campaign_budget_id

    # Set the campaign network options.
    campaign.network_settings.target_google_search = True
    campaign.network_settings.target_search_network = True
    campaign.network_settings.target_content_network = False
    campaign.network_settings.target_partner_search_network = False

    # Add the campaign.
    try:
        campaign_response = campaign_service.mutate_campaigns(
            customer_id=customer_id, operations=[campaign_operation]
        )
        print(f"Created campaign {campaign_response.results[0].resource_name}.")
    except GoogleAdsException as ex:
        handle_googleads_exception(ex)


def handle_googleads_exception(exception):
    print(
        f'Request with ID "{exception.request_id}" failed with status '
        f'"{exception.error.code().name}" and includes the following errors:'
    )
    for error in exception.failure.errors:
        print(f'\tError with message "{error.message}".')
        if error.location:
            for field_path_element in error.location.field_path_elements:
                print(f"\t\tOn field: {field_path_element.field_name}")
    sys.exit(1)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Adds a campaign for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    args = parser.parse_args()

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

    main(googleads_client, args.customer_id)

      

Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2018 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 Portfolio Bidding Strategy and uses it to construct a
# campaign.

require "optparse"
require "google/ads/google_ads"

def use_portfolio_bidding_strategy(customer_id)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters

  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  # Create a budget, which can be shared by multiple campaigns.
  budget = client.resource.campaign_budget do |cb|
    cb.name = "Interplanetary budget ##{(Time.new.to_f * 1000).to_i}"
    cb.amount_micros = 50_000_000
    cb.delivery_method = :STANDARD
    cb.explicitly_shared = true
  end

  operation = client.operation.create_resource.campaign_budget(budget)

  response = client.service.campaign_budget.mutate_campaign_budgets(
    customer_id: customer_id,
    operations: [operation],
  )
  budget_id = response.results.first.resource_name

  puts "Budget #{budget_id} was created"

  # Create a portfolio bidding strategy.
  bidding_strategy = client.resource.bidding_strategy do |bs|
    bs.name = "Enhanced CPC ##{(Time.new.to_f * 1000).to_i}"
    bs.target_spend = client.resource.target_spend do |ts|
      ts.cpc_bid_ceiling_micros = 2_000_000
    end
  end

  operation = client.operation.create_resource.bidding_strategy(bidding_strategy)

  response = client.service.bidding_strategy.mutate_bidding_strategies(
    customer_id: customer_id,
    operations: [operation],
  )
  bidding_id = response.results.first.resource_name

  puts "Portfolio bidding strategy #{bidding_id} was created"

  # Create campaigns.
  campaigns = 2.times.map do |i|
    client.resource.campaign do |c|
      c.name = "Interplanetary Cruise ##{(Time.new.to_f * 1000).to_i + i}"
      c.status = :PAUSED
      c.bidding_strategy = bidding_id
      c.campaign_budget = budget_id
      c.advertising_channel_type = :SEARCH
      c.network_settings = client.resource.network_settings do |ns|
        ns.target_google_search = true
        ns.target_search_network = true
        ns.target_content_network = false
        ns.target_partner_search_network = false
      end
    end
  end

  campaign_operations = campaigns.map {|c|
    client.operation.create_resource.campaign(c)
  }
  response = client.service.campaign.mutate_campaigns(
    customer_id: customer_id,
    operations: campaign_operations,
  )
  response.results.each do |c|
    puts "Campaign #{c.resource_name} was created"
  end
end

if __FILE__ == $PROGRAM_NAME
  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'

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

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

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

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

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

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

      

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, 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 portfolio bidding strategy and uses it to construct a
# campaign.

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::V17::Resources::BiddingStrategy;
use Google::Ads::GoogleAds::V17::Resources::CampaignBudget;
use Google::Ads::GoogleAds::V17::Resources::Campaign;
use Google::Ads::GoogleAds::V17::Resources::NetworkSettings;
use Google::Ads::GoogleAds::V17::Common::TargetSpend;
use Google::Ads::GoogleAds::V17::Enums::BudgetDeliveryMethodEnum   qw(STANDARD);
use Google::Ads::GoogleAds::V17::Enums::AdvertisingChannelTypeEnum qw(SEARCH);
use Google::Ads::GoogleAds::V17::Enums::CampaignStatusEnum         qw(PAUSED);
use
  Google::Ads::GoogleAds::V17::Services::BiddingStrategyService::BiddingStrategyOperation;
use
  Google::Ads::GoogleAds::V17::Services::CampaignBudgetService::CampaignBudgetOperation;
use Google::Ads::GoogleAds::V17::Services::CampaignService::CampaignOperation;
use Google::Ads::GoogleAds::V17::Utils::ResourceNames;

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

# 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";
# Optional: Specify a campaign budget ID below to be used to create a campaign.
# If none is specified, this example will create a new campaign budget.
my $campaign_budget_id = undef;

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

  my $bidding_strategy_resource_name =
    create_bidding_strategy($api_client, $customer_id);

  my $campaign_budget_resource_name =
    $campaign_budget_id
    ? Google::Ads::GoogleAds::V17::Utils::ResourceNames::campaign_budget(
    $customer_id, $campaign_budget_id)
    : create_shared_campaign_buget($api_client, $customer_id);

  create_campaign_with_bidding_strategy(
    $api_client, $customer_id,
    $bidding_strategy_resource_name,
    $campaign_budget_resource_name
  );

  return 1;
}

# Creates the portfolio bidding strategy.
sub create_bidding_strategy {
  my ($api_client, $customer_id) = @_;

  # Create a portfolio bidding strategy.
  my $portfolio_bidding_strategy =
    Google::Ads::GoogleAds::V17::Resources::BiddingStrategy->new({
      name        => "Maximize Clicks #" . uniqid(),
      targetSpend => Google::Ads::GoogleAds::V17::Common::TargetSpend->new({
          cpcBidCeilingMicros => 2000000
        }
      ),
    });

  # Create a bidding strategy operation.
  my $bidding_strategy_operation =
    Google::Ads::GoogleAds::V17::Services::BiddingStrategyService::BiddingStrategyOperation
    ->new({
      create => $portfolio_bidding_strategy
    });

  # Add the bidding strategy.
  my $bidding_strategies_response =
    $api_client->BiddingStrategyService()->mutate({
      customerId => $customer_id,
      operations => [$bidding_strategy_operation]});

  my $bidding_strategy_resource_name =
    $bidding_strategies_response->{results}[0]{resourceName};

  printf "Created portfolio bidding strategy with resource name: '%s'.\n",
    $bidding_strategy_resource_name;

  return $bidding_strategy_resource_name;
}

# Creates an explicitly shared budget to be used to create the campaign.
sub create_shared_campaign_buget {
  my ($api_client, $customer_id) = @_;

  # Create a shared budget.
  my $campaign_budget =
    Google::Ads::GoogleAds::V17::Resources::CampaignBudget->new({
      name           => "Shared Interplanetary Budget #" . uniqid(),
      deliveryMethod => STANDARD,
      # Set the amount of budget.
      amountMicros => 50000000,
      # Makes the budget explicitly shared.
      explicitlyShared => 'true'
    });

  # Create a campaign budget operation.
  my $campaign_budget_operation =
    Google::Ads::GoogleAds::V17::Services::CampaignBudgetService::CampaignBudgetOperation
    ->new({create => $campaign_budget});

  # Add the campaign budget.
  my $campaign_budgets_response = $api_client->CampaignBudgetService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_budget_operation]});

  my $campaign_budget_resource_name =
    $campaign_budgets_response->{results}[0]{resourceName};

  printf "Created a shared budget with resource name: '%s'.\n",
    $campaign_budget_resource_name;

  return $campaign_budget_resource_name;
}

# Creates a campaign with the created portfolio bidding strategy.
sub create_campaign_with_bidding_strategy {
  my (
    $api_client, $customer_id,
    $bidding_strategy_resource_name,
    $campaign_budget_resource_name
  ) = @_;

  # Create a search campaign.
  my $campaign = Google::Ads::GoogleAds::V17::Resources::Campaign->new({
      name                   => "Interplanetary Cruise #" . uniqid(),
      advertisingChannelType => SEARCH,
      # Recommendation: Set the campaign to PAUSED when creating it to stop
      # the ads from immediately serving. Set to ENABLED once you've added
      # targeting and the ads are ready to serve.
      status => PAUSED,
      # Configures the campaign network options.
      networkSettings =>
        Google::Ads::GoogleAds::V17::Resources::NetworkSettings->new({
          targetGoogleSearch   => "true",
          targetSearchNetwork  => "true",
          targetContentNetwork => "true"
        }
        ),
      # Set the bidding strategy and budget.
      biddingStrategy => $bidding_strategy_resource_name,
      campaignBudget  => $campaign_budget_resource_name
    });

  # Create a campaign operation.
  my $campaign_operation =
    Google::Ads::GoogleAds::V17::Services::CampaignService::CampaignOperation->
    new({create => $campaign});

  # Add the campaign.
  my $campaigns_response = $api_client->CampaignService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_operation]});

  my $campaign_resource_name = $campaigns_response->{results}[0]{resourceName};

  printf "Created a campaign with resource name: '%s'.\n",
    $campaign_resource_name;
}

# 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,
  "campaign_budget_id=i" => \$campaign_budget_id
);

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

# Call the example.
use_portfolio_bidding_strategy($api_client, $customer_id =~ s/-//gr,
  $campaign_budget_id);

=pod

=head1 NAME

use_portfolio_bidding_strategy

=head1 DESCRIPTION

This example adds a portfolio bidding strategy and uses it to construct a campaign.

=head1 SYNOPSIS

use_portfolio_bidding_strategy.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.
    -campaign_budget_id         [optional] The ID of the shared campaign budget to use.

=cut