AI-generated Key Takeaways
-
The code demonstrates how to add a portfolio bidding strategy to a Google Ads account.
-
It shows how to create an explicitly shared campaign budget that can be used for multiple campaigns.
-
The example illustrates how to create a new campaign and associate it with the newly created portfolio bidding strategy and shared budget.
-
The code utilizes the Google Ads API client libraries for Java, C#, PHP, Python, and Ruby to interact with the Google Ads API.
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 static com.google.ads.googleads.v22.enums.EuPoliticalAdvertisingStatusEnum.EuPoliticalAdvertisingStatus.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING; 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.v22.common.TargetSpend; import com.google.ads.googleads.v22.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType; import com.google.ads.googleads.v22.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod; import com.google.ads.googleads.v22.enums.CampaignStatusEnum.CampaignStatus; import com.google.ads.googleads.v22.errors.GoogleAdsError; import com.google.ads.googleads.v22.errors.GoogleAdsException; import com.google.ads.googleads.v22.resources.BiddingStrategy; import com.google.ads.googleads.v22.resources.Campaign; import com.google.ads.googleads.v22.resources.Campaign.NetworkSettings; import com.google.ads.googleads.v22.resources.CampaignBudget; import com.google.ads.googleads.v22.services.BiddingStrategyOperation; import com.google.ads.googleads.v22.services.BiddingStrategyServiceClient; import com.google.ads.googleads.v22.services.CampaignBudgetOperation; import com.google.ads.googleads.v22.services.CampaignBudgetServiceClient; import com.google.ads.googleads.v22.services.CampaignOperation; import com.google.ads.googleads.v22.services.CampaignServiceClient; import com.google.ads.googleads.v22.services.MutateBiddingStrategiesResponse; import com.google.ads.googleads.v22.services.MutateBiddingStrategyResult; import com.google.ads.googleads.v22.services.MutateCampaignBudgetResult; import com.google.ads.googleads.v22.services.MutateCampaignBudgetsResponse; import com.google.ads.googleads.v22.services.MutateCampaignResult; import com.google.ads.googleads.v22.services.MutateCampaignsResponse; import com.google.ads.googleads.v22.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) // Declares whether this campaign serves political ads targeting the EU. .setContainsEuPoliticalAdvertising(DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING) .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 c;%s'.%n", mutateCampaignResult.getResourceName()); return mutateCampaignResult.getResourceName(); } } } UsePortfolioBiddingStrategy.java
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.V22.Common; using Google.Ads.GoogleAds.V22.Enums; using Google.Ads.GoogleAds.V22.Errors; using Google.Ads.GoogleAds.V22.Resources; using Google.Ads.GoogleAds.V22.Services; using System; using static Google.Ads.GoogleAds.V22.Enums.AdvertisingChannelTypeEnum.Types; using static Google.Ads.GoogleAds.V22.Enums.CampaignStatusEnum.Types; using static Google.Ads.GoogleAds.V22.Enums.EuPoliticalAdvertisingStatusEnum.Types; using static Google.Ads.GoogleAds.V22.Resources.Campaign.Types; namespace Google.Ads.GoogleAds.Exa<mples.V>22 { /// summary /// This code example adds a portfolio bidding strategy and uses it to construct <a campai>gn. /// /summary public class UsePortfolioBiddingStrategy : ExampleBas<e {> /// summary /// Command line opti<ons for running the see cref="UseP>ortfolioBiddingStrateg<y"/> example. /// /summary public class Options : OptionsB<ase > { /// 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 lon<g Custo>merId { get; set; } } /// summary /// Main method, to run this code< example> as a standal<one application.<>/span> /// /summary < /// >param name="args"The command line arguments./param public static void Main(string[] args) { < > Options options = ExampleUtilities.ParseCommandLineOptions(args); UsePortfolioBiddingStrategy codeExample = new UsePortfolioBiddingStrategy(); Console.WriteLine(codeExample.Description); codeExample.Run(new Goo<gleAdsC>lient(), options.CustomerId); } /// summary //</ Return>s 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 " + "campa<ign.&quo>t;; </// summary > /// Runs the code exa<mple.<>/span> /// /<summary /// par>am 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($"Fa<ilure: {>e.Failure}&qu<ot;); > Console.WriteLine($<">Request ID: {<e.RequestId}"); > throw; } } </// su>mmary < /// Creates the >portfolio bidding strategy<. > /// /summ<ary /// param n>ame="client"The Google <Ads cl>ient./param < >/// param name="customerId&quo<t;The Go>ogle 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 /// returnsThe bidding strategy resource name./returns private string CreatePortfolioBiddingStrategy(GoogleAdsClient client, long customerId, string name, long bidCeiling) { // Get the BiddingStrategyService. BiddingStrategyServiceClient biddingStrategyService = client.GetService( Services.V22.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. MutateBiddingStrategi<esRespo>nse biddingResponse = biddingStrategyService.MutateBiddingStrategies( < > customer<Id.ToString(), new >BiddingStrategyOperati<on[] {> biddingOpera<tion }); r>eturn biddingResponse.Results[0].ResourceName; < } > /// sum<mary /// >Creates a shared< campa>ign budget to< be used to create >the campaign. /// /s<ummary> /// <param n>ame="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 /// returnsThe budget resource name./returns private string CreateSharedBudget(GoogleAdsClient client, long customerId, string name, long amount) { // Get the CampaignBudgetService. CampaignBudgetServiceClient campaignBudgetService = client.GetService(Services.V22.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 r<etVal = >campaignBudge<tService.MutateCamp>aignBudgets( < > customerId.T<oString(), new Campaign>BudgetOperation[] { campaignBudgetOperation }); < >return retVal<.Results[0].Resou>rceName; }< > /// summa<ry /// Creates the campaign with> a portfolio bidding str<ategy.> /// </summary /// param name="c>lient"The Google Ads client./<param<>/span> /// p<aram na>me="customerId"Th<e 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 /// returnsThe 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.V22.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 }, // Declare whether or not this campaign contains political ads targeting the EU. ContainsEuPoliticalAdvertising = EuPoliticalAdvertisingStatus.DoesNotContainEuPoliticalAdvertising, }; // Create the operation. CampaignOperaperation() { Create = campaign }; // Create the campaign. MutateCampaignsResponse retVal = campaignService.MutateCampaigns( customerId.ToString(), new CampaignOperation[] { operation }); return retVal.Results[0].ResourceName; } } } UsePortfolioBiddingStrategy.cs
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\V22\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V22\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V22\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Util\V22\ResourceNames; use Google\Ads\GoogleAds\V22\Common\TargetSpend; use Google\Ads\GoogleAds\V22\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType; use Google\Ads\GoogleAds\V22\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod; use Google\Ads\GoogleAds\V22\Enums\CampaignStatusEnum\CampaignStatus; use Google\Ads\GoogleAds\V22\Enums\EuPoliticalAdvertisingStatusEnum\EuPoliticalAdvertisingStatus; use Google\Ads\GoogleAds\V22\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V22\Resources\BiddingStrategy; use Google\Ads\GoogleAds\V22\Resources\Campaign; use Google\Ads\GoogleAds\V22\Resources\Campaign\NetworkSettings; use Google\Ads\GoogleAds\V22\Resources\CampaignBudget; use Google\Ads\GoogleAds\V22\Services\BiddingStrategyOperation; use Google\Ads\GoogleAds\V22\Services\CampaignBudgetOperation; use Google\Ads\GoogleAds\V22\Services\CampaignOperation; use Google\Ads\GoogleAds\V22\Services\MutateBiddingStrategiesRequest; use Google\Ads\GoogleAds\V22\Services\MutateCampaignBudgetsRequest; use Google\Ads\GoogleAds\V22\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. $oAuth2Cred>ential = (n>ew OAuth2TokenBuilder())-fromFile()-build(); // Construct a Google Ads client configured from a properties file and the // OAuth2 credentials above. $googleAdsClie>nt = (new GoogleAdsClien>tBuilder())-fromFile() -withOAuth2Credent>ial($oAuth2Credential) -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( > &q>uot;\t%s: %s%s", $>error-getErrorCode()-getErrorCode(), $error-getMessage(), PHP_EOL ); } exit(1); } catch (ApiException $apiException) { printf( "ApiExcep>tion 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 strate>gy. $portfolioBiddingStrategy = new BiddingStrategy([ 'name>' = 'Maximize Clicks #' . Helper::getPrintableDat>etime(), 'target_spend' = new TargetSpend([ 'cpc_bid_ceiling_micros' = 2000000 ]) ]); // Constructs an operation that will create a portfolio biddin>g strategy. $biddingStrategyOperation = new BiddingStrategyOperation(); $biddingStrategyOperation-setCreate($portfolioBiddingStrategy); //> Issues a mutate request to create the bidding strategy. $biddingStrategyServ>iceClient = $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 $googleAdsCli>ent, int $customerId ) { // Creates a shared budget. $budget = new Camp>aignBudget([ 'name' = 'Shared Interplanetary Budget #' . Helper::getPrintabl>eDatetime(), '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 CampaignBudgetOperatio>n(); $campaignBudgetOperation-setCreate($budget); // Issues a muta>te 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: Se>t the campaign to PAUSED when creating it to prevent // the ads from immediately serving. Set to ENAB>LED once you've added // targeting and the ads >are ready to serve. 'status'> = CampaignStatus::PAUSED, // Configu>res the campaign network options. 'network_settings' = new NetworkSettings([ > 'target_google_search' = true, >39;target_search_network' = true, 'target_content_network' = true, ]), // Sets the bidding strategy and budget. > 'bidding_strategy' = $biddingStrategyResourceName, 'campaign_budget' = $campaignBudgetResourceName, // Declare whether or not this campaign serves political ads targeting the EU. > 'contains_eu_political_advertising' = EuPoliticalAdvertisingStatus::DOES_NOT_CONTAIN_EU_POLITIC>AL_ADVERTISING ]); // Constructs a campaign operation.> $campaignOperation = new CampaignOperation(); $campaignOperation-setCreate($campaign); // Issues a mutate request to add the campaign. $campaignService>Client = $googleAdsClient-getCampaignServiceClient(); $response = $campaignServiceClient-mutateCampaigns( > MutateCampaignsRequest::build($customerId, [$campaignOperation]) ); /** @va $addedCampaign = $response-getResults()[0]; printf( "Created a campaign with resource name: '%s'.%s", $addedCampaign-getResourceName(), PHP_EOL ); } } UsePortfolioBiddingStrategy::main(); UsePortfolioBiddingStrategy.php
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 from google.ads.googleads.v22.common.types.bidding import TargetSpend from google.ads.googleads.v22.resources.types.bidding_strategy import ( BiddingStrategy, ) from google.ads.googleads.v22.resources.types.campaign import Campaign from google.ads.googleads.v22.resources.types.campaign_budget import ( CampaignBudget, ) from google.ads.googleads.v22.services.services.bidding_strategy_service import ( BiddingStrategyServiceClient, ) from google.ads.googleads.v22.services.services.campaign_budget_service import ( CampaignBudgetServiceClient, ) from google.ads.googleads.v22.services.services.campaign_service import ( CampaignServiceClient, ) from google.ads.googleads.v22.services.types.bidding_strategy_service import ( BiddingStrategyOperation, MutateBiddingStrategiesResponse, ) from google.ads.googleads.v22.services.types.campaign_budget_service import ( CampaignBudgetOperation, MutateCampaignBudgetsResponse, ) from google.ads.googleads.v22.services.types.campaign_service import ( CampaignOperation, MutateCampaignsResponse, ) def> main(client: GoogleAdsClient, customer_id: str) - None: campaign_budget_service: CampaignBudgetServiceClient = client.get_service( "CampaignBudgetService" ) bidding_strategy_service: BiddingStrategyServiceClient = client.get_service( "BiddingStrategyService" ) campaign_service: CampaignServiceClient = client.get_service( "CampaignService" ) # Create a budget, which can be shared by multiple campaigns. campaign_budget_operation: CampaignBudgetOperation = client.get_type( "CampaignBudgetOperation" ) campaign_budget: CampaignBudget = 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: MutateCampaignBudgetsResponse = ( campaign_budget_service.mutate_campaign_budgets( customer_id=customer_id, operations=[campaign_budget_operation] ) ) campaign_budget_id: str = 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: BiddingStrategyOperation = client.get_type( "BiddingStrategyOperation" ) bidding_strategy: BiddingStrategy = bidding_strategy_operation.create bidding_strategy.name = f"Enhanced CPC {uuid.uuid4()}" target_spend: TargetSpend = bidding_strategy.target_spend target_spend.cpc_bid_ceiling_micros = 2000000 # Add portfolio bidding strategy. try: bidding_strategy_response: MutateBiddingStrategiesResponse = ( bidding_strategy_service.mutate_bidding_strategies( customer_id=customer_id, operations=[bidding_strategy_operation] ) ) bidding_strategy_id: str = 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: CampaignOperation = client.get_type("CampaignOperation") campaign: 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 campaign.contains_eu_political_advertising = ( client.enums.EuPoliticalAdvertisingStatusEnum.DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING ) # Add the campaign. try: campaign_response: MutateCampaignsResponse = ( campaign_service.mutate_campaigns( customer_id=customer_id, operations=[campaign_operation] ) ) print(f"Created campaign {cam>paign_response.results[0].resource_name}.") except GoogleAdsException as ex: handle_googleads_exception(ex) def handle_googleads_exception(exception: GoogleAdsException) - None: 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 = 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: argparse # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client: GoogleAdsClient = GoogleAdsClient.load_from_storage( version="v22" ) main(googleads_client, args.customer_id) use_portfolio_bidding_strategy.py
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 c.contains_eu_political_advertising = :DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING 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 mes>sage') 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("\tOnement.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 use_portfolio_bidding_strategy.rb
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::V22::Resources::BiddingStrategy; use Google::Ads::GoogleAds::V22::Resources::CampaignBudget; use Google::Ads::GoogleAds::V22::Resources::Campaign; use Google::Ads::GoogleAds::V22::Resources::NetworkSettings; use Google::Ads::GoogleAds::V22::Common::TargetSpend; use Google::Ads::GoogleAds::V22::Enums::BudgetDeliveryMethodEnum qw(STANDARD); use Google::Ads::GoogleAds::V22::Enums::AdvertisingChannelTypeEnum qw(SEARCH); use Google::Ads::GoogleAds::V22::Enums::CampaignStatusEnum qw(PAUSED); use Google::Ads::GoogleAds::V22::Enums::EuPoliticalAdvertisingStatusEnum qw(DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING); use Google::Ads::GoogleAds::V22::Services::BiddingStrategyService::BiddingStrategyOperation; use Google::Ads::GoogleAds::V22::Services::CampaignBudgetService::CampaignBudgetOperation; use Google::Ads::GoogleAds::V22::Services::CampaignService::CampaignOperation; use Google::Ads::GoogleAds::V22::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::V22::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::Goo>gleAds::V22::Resources::B>iddingStrategy-new({ name = "Maxim>ize Clicks #" . uniqid(), targetSpend => Google::Ads::GoogleAds::V22::Common:>:TargetSpend-new({ cpcBidCeilingMicros = 2000000 } ), }); # Create a bidding strategy operation. my $bidding_strategy_operation = Google::Ads::GoogleAds::V22::Services::Bidd>ingStrategyService::>BiddingStrategyOperation -new({ create = $portfolio_bidding_strategy }); # Add the bidding strategy. >my $bidding_strategies_re>sponse = $api_client-Bi>ddingStrategyService()-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::Go>ogleAds::V22::Resources::CampaignBudget-new({ name => "Shared Interplanetary Budget #" . uniqid(), del>iveryMethod = STANDARD, # Set the amount of budget. amountMicros = >50000000, # Makes the budget explicitly shared. explicitlyShared = 'true' }); # Create a campaign budget operation. my $campaign_budget_operation = Googl>e::Ads::Googl>eAds::V22::Services::CampaignBudgetService::CampaignBudgetOperation -new({create = $campaign_>budget}); # Add the c>ampaign budget. my $campa>ign_budgets_response = $api_clien>t-CampaignBudgetService()-mutate({ customerId = $customer_id, operations = [$campaign_budge>t_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::V22::Resources::Campaign-n>ew({ name = "Interplanetary Cruise #" . uniqid(), advertisingChannelType = SEARCH, # Recommendation: Set the campaign to PAUSED when creating it to stop # the ads from imme>diately serving. Set to ENABLED once you've added # targeting and the a>ds are ready to serve. status = PAUSED, # Configures >the campaign network options. ne>tworkSettings = Google::Ads::Goog>leAds::V22::Resources::NetworkSettings-ne>w({ targetGoogleSearch = "true", targetSearchNetwork = "tru>e", targetContentNetwork = "true">; } ), # Set the bidding strategy and budget. biddingStrategy = $bidding_strategy_resource_name, campaignBudget = $campaign_budget_resource_name, # Declare whether or not this campaign serves political ads targeting the EU. > # Valid values are CONTAINS_EU_POLITICAL_ADVERTISING and # DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING. containsEuPoliticalAdvertising = DOES_NOT_CONTAIN_EU_POLITICAL_ADVERTISING> }); # Crea>te a campaign operation. my $campaign_operation = Google::Ads::GoogleA>ds::V22::Services:>:CampaignService::CampaignO>peration- new({create = $camp>aign}); # Add the campaign. my $campaigns_response = $api_client-Campaign>Service()-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 r>eturned fault. $api_client-set_die_on_faul>ts(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 e. -customer_id The Google Ads customer ID. -campaign_budget_id [optional] The ID of the shared campaign budget to use. =cut use_portfolio_bidding_strategy.pl