// 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 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.v2.errors.GoogleAdsException; import com.google.ads.googleads.v2.common.TargetSpend; import com.google.ads.googleads.v2.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType; import com.google.ads.googleads.v2.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod; import com.google.ads.googleads.v2.enums.CampaignStatusEnum.CampaignStatus; import com.google.ads.googleads.v2.errors.GoogleAdsError; import com.google.ads.googleads.v2.resources.BiddingStrategy; import com.google.ads.googleads.v2.resources.Campaign; import com.google.ads.googleads.v2.resources.Campaign.NetworkSettings; import com.google.ads.googleads.v2.resources.CampaignBudget; import com.google.ads.googleads.v2.resources.CampaignBudgetName; import com.google.ads.googleads.v2.services.BiddingStrategyOperation; import com.google.ads.googleads.v2.services.BiddingStrategyServiceClient; import com.google.ads.googleads.v2.services.CampaignBudgetOperation; import com.google.ads.googleads.v2.services.CampaignBudgetServiceClient; import com.google.ads.googleads.v2.services.CampaignOperation; import com.google.ads.googleads.v2.services.CampaignServiceClient; import com.google.ads.googleads.v2.services.MutateBiddingStrategiesResponse; import com.google.ads.googleads.v2.services.MutateBiddingStrategyResult; import com.google.ads.googleads.v2.services.MutateCampaignBudgetResult; import com.google.ads.googleads.v2.services.MutateCampaignBudgetsResponse; import com.google.ads.googleads.v2.services.MutateCampaignResult; import com.google.ads.googleads.v2.services.MutateCampaignsResponse; import com.google.common.collect.Lists; import com.google.protobuf.BoolValue; import com.google.protobuf.Int64Value; import com.google.protobuf.StringValue; 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; try { googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build(); } catch (FileNotFoundException fnfe) { System.err.printf( "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe); return; } catch (IOException ioe) { System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe); return; } 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); } } } /** * 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 = CampaignBudgetName.format(customerId.toString(), campaignBudgetId.toString()); } 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(Int64Value.of(2_000_000L)) .setTargetSpendMicros(Int64Value.of(20_000_000L)) .build(); BiddingStrategy portfolioBiddingStrategy = BiddingStrategy.newBuilder() .setName(StringValue.of("Maximize Clicks #" + System.currentTimeMillis())) .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( StringValue.of("Shared Interplanetary Budget #" + System.currentTimeMillis())) .setAmountMicros(Int64Value.of(50_000_000L)) .setDeliveryMethod(BudgetDeliveryMethod.STANDARD) .setExplicitlyShared(BoolValue.of(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(BoolValue.of(true)) .setTargetSearchNetwork(BoolValue.of(true)) .setTargetContentNetwork(BoolValue.of(true)) .build(); Campaign campaign = Campaign.newBuilder() .setName(StringValue.of("Interplanetary Cruise #" + System.currentTimeMillis())) .setStatus(CampaignStatus.PAUSED) .setCampaignBudget(StringValue.of(campaignBudgetResourceName)) .setBiddingStrategy(StringValue.of(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(); } } }
// 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 Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V2.Common; using Google.Ads.GoogleAds.V2.Enums; using Google.Ads.GoogleAds.V2.Errors; using Google.Ads.GoogleAds.V2.Resources; using Google.Ads.GoogleAds.V2.Services; using System; using static Google.Ads.GoogleAds.V2.Enums.AdvertisingChannelTypeEnum.Types; using static Google.Ads.GoogleAds.V2.Enums.CampaignStatusEnum.Types; using static Google.Ads.GoogleAds.V2.Resources.Campaign.Types; namespace Google.Ads.GoogleAds.Examples.V2 { /// <summary> /// This code example adds a portfolio bidding strategy and uses it to construct a campaign. /// </summary> public class UsePortfolioBiddingStrategy : ExampleBase { /// <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) { UsePortfolioBiddingStrategy codeExample = new UsePortfolioBiddingStrategy(); Console.WriteLine(codeExample.Description); // The Google Ads customer ID for which the call is made. long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); codeExample.Run(new GoogleAdsClient(), customerId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description { get { return "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; const long SPEND_TARGET = 20000000; string portfolioBiddingStrategy = CreatePortfolioBiddingStrategy( client, customerId, BIDDINGSTRATEGY_NAME, BID_CEILING, SPEND_TARGET); 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}"); } } /// <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> /// <param name="spendTarget">The spend target in micros.</param> /// <returns>The bidding strategy resource name.</returns> private string CreatePortfolioBiddingStrategy(GoogleAdsClient client, long customerId, string name, long bidCeiling, long spendTarget) { // Get the BiddingStrategyService. BiddingStrategyServiceClient biddingStrategyService = client.GetService( Services.V2.BiddingStrategyService); // Create a portfolio bidding strategy. BiddingStrategy biddingStrategy = new BiddingStrategy() { Name = name, TargetSpend = new TargetSpend() { // Optionally set additional bidding scheme parameters. CpcBidCeilingMicros = bidCeiling, TargetSpendMicros = spendTarget } }; // 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.V2.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.V2.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 /** * 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\Lib\V2\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V2\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V2\GoogleAdsException; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Util\V2\ResourceNames; use Google\Ads\GoogleAds\V2\Common\TargetSpend; use Google\Ads\GoogleAds\V2\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType; use Google\Ads\GoogleAds\V2\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod; use Google\Ads\GoogleAds\V2\Enums\CampaignStatusEnum\CampaignStatus; use Google\Ads\GoogleAds\V2\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V2\Resources\BiddingStrategy; use Google\Ads\GoogleAds\V2\Resources\Campaign; use Google\Ads\GoogleAds\V2\Resources\Campaign\NetworkSettings; use Google\Ads\GoogleAds\V2\Resources\CampaignBudget; use Google\Ads\GoogleAds\V2\Services\BiddingStrategyOperation; use Google\Ads\GoogleAds\V2\Services\CampaignBudgetOperation; use Google\Ads\GoogleAds\V2\Services\CampaignOperation; use Google\ApiCore\ApiException; use Google\Protobuf\BoolValue; use Google\Protobuf\Int64Value; use Google\Protobuf\StringValue; /** * This example adds a portfolio bidding strategy and uses it to construct a campaign. */ class UsePortfolioBiddingStrategy { 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. 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) ->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 ); } } catch (ApiException $apiException) { printf( "ApiException was thrown with message '%s'.%s", $apiException->getMessage(), PHP_EOL ); } } /** * Runs the example. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the customer ID * @param int $campaignBudgetId the campaign budget ID */ 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' => new StringValue(['value' => 'Maximize Clicks #' . uniqid()]), 'target_spend' => new TargetSpend([ 'cpc_bid_ceiling_micros' => new Int64Value(['value' => 2000000]), 'target_spend_micros' => new Int64Value(['value' => 20000000]) ]) ]); // 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( $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' => new StringValue(['value' => 'Shared Interplanetary Budget #' . uniqid()]), 'delivery_method' => BudgetDeliveryMethod::STANDARD, // Sets the amount of budget. 'amount_micros' => new Int64Value(['value' => 50000000]), // Makes the budget explicitly shared. 'explicitly_shared' => new BoolValue(['value' => 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( $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' => new StringValue(['value' => 'Interplanetary Cruise #' . uniqid()]), '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' => new BoolValue(['value' => true]), 'target_search_network' => new BoolValue(['value' => true]), 'target_content_network' => new BoolValue(['value' => true]), ]), // Sets the bidding strategy and budget. 'bidding_strategy' => new StringValue(['value' => $biddingStrategyResourceName]), 'campaign_budget' => new StringValue(['value' => $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($customerId, [$campaignOperation]); /** @var Campaign $addedCampaign */ $addedCampaign = $response->getResults()[0]; printf( "Created a campaign with resource name: '%s'.%s", $addedCampaign->getResourceName(), PHP_EOL ); } } UsePortfolioBiddingStrategy::main();
#!/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 import google.ads.google_ads.client def main(client, customer_id): campaign_budget_service = client.get_service('CampaignBudgetService', version='v2') bidding_strategy_service = client.get_service('BiddingStrategyService', version='v2') campaign_service = client.get_service('CampaignService', version='v2') # Create a budget, which can be shared by multiple campaigns. campaign_budget_operation = client.get_type('CampaignBudgetOperation', version='v2') campaign_budget = campaign_budget_operation.create campaign_budget.name.value = 'Interplanetary Budget %s' % uuid.uuid4() campaign_budget.delivery_method = client.get_type( 'BudgetDeliveryMethodEnum').STANDARD campaign_budget.amount_micros.value = 500000 campaign_budget.explicitly_shared.value = True # Add budget. try: campaign_budget_response = ( campaign_budget_service.mutate_campaign_budgets( customer_id, [campaign_budget_operation])) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) campaign_budget_id = campaign_budget_response.results[0].resource_name print('Budget "%s" was created.' % campaign_budget_id) # Create a portfolio bidding strategy. bidding_strategy_operation = client.get_type('BiddingStrategyOperation', version='v2') bidding_strategy = bidding_strategy_operation.create bidding_strategy.name.value = 'Enhanced CPC %s' % uuid.uuid4() target_spend = bidding_strategy.target_spend target_spend.cpc_bid_ceiling_micros.value = 2000000 target_spend.target_spend_micros.value = 20000000 # Add portfolio bidding strategy. try: bidding_strategy_response = ( bidding_strategy_service.mutate_bidding_strategies( customer_id, [bidding_strategy_operation])) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) bidding_strategy_id = bidding_strategy_response.results[0].resource_name print('Portfolio bidding strategy "%s" was created.' % bidding_strategy_id) # Create campaign. campaign_operation = client.get_type('CampaignOperation', version='v2') campaign = campaign_operation.create campaign.name.value = 'Interplanetary Cruise %s' % uuid.uuid4() campaign.advertising_channel_type = client.get_type( '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.get_type('CampaignStatusEnum', version='v2').PAUSED # Set the bidding strategy and budget. campaign.bidding_strategy.value = bidding_strategy_id campaign.manual_cpc.enhanced_cpc_enabled.value = True campaign.campaign_budget.value = campaign_budget_id # Set the campaign network options. campaign.network_settings.target_google_search.value = True campaign.network_settings.target_search_network.value = True campaign.network_settings.target_content_network.value = False campaign.network_settings.target_partner_search_network.value = False # Add the campaign. try: campaign_response = campaign_service.mutate_campaigns( customer_id, [campaign_operation]) except google.ads.google_ads.errors.GoogleAdsException as ex: print('Request with ID "%s" failed with status "%s" and includes the ' 'following errors:' % (ex.request_id, ex.error.code().name)) for error in ex.failure.errors: print('\tError with message "%s".' % error.message) if error.location: for field_path_element in error.location.field_path_elements: print('\t\tOn field: %s' % field_path_element.field_name) sys.exit(1) print('Created campaign %s.' % campaign_response.results[0].resource_name) if __name__ == '__main__': # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. google_ads_client = (google.ads.google_ads.client.GoogleAdsClient .load_from_storage()) 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() main(google_ads_client, args.customer_id)
#!/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, [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.enhanced_cpc = client.resource.enhanced_cpc end operation = client.operation.create_resource.bidding_strategy(bidding_strategy) response = client.service.bidding_strategy.mutate_bidding_strategies( customer_id, [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, 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 rescue Google::Gax::RetryError => e STDERR.printf("Error: '%s'\n\tCause: '%s'\n\tCode: %d\n\tDetails: '%s'\n" \ "\tRequest-Id: '%s'\n", e.message, e.cause.message, e.cause.code, e.cause.details, e.cause.metadata['request-id']) end end