Orçamentos de campanha

Os orçamentos são usados para gerenciar a quantia de dinheiro gasta nas suas campanhas do Google AdWords. Este guia explica tudo o que você precisa saber para lidar com os orçamentos na AdWords API, incluindo o compartilhamento, a atribuição, a remoção e o acompanhamento deles.

Como compartilhar orçamentos

Um orçamento pode se aplicar a uma única campanha ou ser compartilhado entre muitas campanhas.

Todo novo Budget criado com o uso da Google AdWords API é compartilhável por padrão. Para verificar isso, confira o valor de isExplicitlyShared por meio de uma chamada da API para o BudgetService:

  • isExplicitlyShared = true significa que o orçamento pode ser compartilhado entre várias campanhas.
  • isExplicitlyShared = false significa que o orçamento pode ser usado por apenas uma campanha.

Os orçamentos explicitamente compartilhados são exibidos na Biblioteca compartilhada de uma conta na interface do usuário do Google AdWords, ao passo que um orçamento não compartilhado é exibido somente nas Configurações da campanha associada a ele.

No exemplo a seguir, que cria um novo orçamento, ele é compartilhado porque isExplicitlyShared é deixado com o valor padrão de true.

Java

// Get the BudgetService.
BudgetServiceInterface budgetService =
    adWordsServices.get(session, BudgetServiceInterface.class);

// Create a budget, which can be shared by multiple campaigns.
Budget sharedBudget = new Budget();
sharedBudget.setName("Interplanetary Cruise #" + System.currentTimeMillis());
Money budgetAmount = new Money();
budgetAmount.setMicroAmount(50_000_000L);
sharedBudget.setAmount(budgetAmount);
sharedBudget.setDeliveryMethod(BudgetBudgetDeliveryMethod.STANDARD);

BudgetOperation budgetOperation = new BudgetOperation();
budgetOperation.setOperand(sharedBudget);
budgetOperation.setOperator(Operator.ADD);

// Add the budget
Long budgetId =
    budgetService.mutate(new BudgetOperation[] {budgetOperation}).getValue(0).getBudgetId();

CSharp

using (BudgetService budgetService =
    (BudgetService) user.GetService(AdWordsService.v201802.BudgetService)) {

  // Create the campaign budget.
  Budget budget = new Budget();
  budget.name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString();
  budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD;
  budget.amount = new Money();
  budget.amount.microAmount = 500000;

  BudgetOperation budgetOperation = new BudgetOperation();
  budgetOperation.@operator = Operator.ADD;
  budgetOperation.operand = budget;

  try {
    BudgetReturnValue budgetRetval = budgetService.mutate(
        new BudgetOperation[] { budgetOperation });
    return budgetRetval.value[0];
  } catch (Exception e) {
    throw new System.ApplicationException("Failed to add shared budget.", e);
  }
}

Python

budget_service = client.GetService('BudgetService', version='v201802')

# Create a budget, which can be shared by multiple campaigns.
budget = {
    'name': 'Interplanetary budget #%s' % uuid.uuid4(),
    'amount': {
        'microAmount': '50000000'
    },
    'deliveryMethod': 'STANDARD'
}

budget_operations = [{
    'operator': 'ADD',
    'operand': budget
}]

# Add the budget.
budget_id = budget_service.mutate(budget_operations)['value'][0][
    'budgetId']

PHP

$budgetService = $adWordsServices->get($session, BudgetService::class);

// Create the shared budget (required).
$budget = new Budget();
$budget->setName('Interplanetary Cruise Budget #' . uniqid());
$money = new Money();
$money->setMicroAmount(50000000);
$budget->setAmount($money);
$budget->setDeliveryMethod(BudgetBudgetDeliveryMethod::STANDARD);

$operations = [];

// Create a budget operation.
$operation = new BudgetOperation();
$operation->setOperand($budget);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

// Create the budget on the server.
$result = $budgetService->mutate($operations);
$budget = $result->getValue()[0];

Perl

# Create a budget, which can be shared by multiple campaigns.
my $budget = Google::Ads::AdWords::v201802::Budget->new({
    # Required attributes.
    name => "Interplanetary budget #" . uniqid(),
    amount =>
      Google::Ads::AdWords::v201802::Money->new({microAmount => 5000000}),
    deliveryMethod => "STANDARD"
});

my $budget_operation = Google::Ads::AdWords::v201802::BudgetOperation->new({
    operator => "ADD",
    operand  => $budget
});

# Add budget.
my $budgetId =
  $client->BudgetService()->mutate({operations => ($budget_operation)})
  ->get_value()->get_budgetId()->get_value();

Ruby

# Create a budget, which can be shared by multiple campaigns.
budget_srv = adwords.service(:BudgetService, API_VERSION)
budget = {
  :name => 'Interplanetary budget #%d' % (Time.new.to_f * 1000).to_i,
  :amount => {:micro_amount => 50000000},
  :delivery_method => 'STANDARD'
}
budget_operation = {:operator => 'ADD', :operand => budget}

# Add budget.
return_budget = budget_srv.mutate([budget_operation])
budget_id = return_budget[:value].first[:budget_id]

VB.NET

Using budgetService As BudgetService = CType(user.GetService(
    AdWordsService.v201802.BudgetService), BudgetService)

  ' Create the campaign budget.
  Dim budget As New Budget
  budget.name = "Interplanetary Cruise Budget #" & ExampleUtilities.GetRandomString
  budget.deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD
  budget.amount = New Money
  budget.amount.microAmount = 50000000

  Dim budgetOperation As New BudgetOperation
  budgetOperation.operator = [Operator].ADD
  budgetOperation.operand = budget

  Try
    Dim budgetRetval As BudgetReturnValue = budgetService.mutate(
        New BudgetOperation() {budgetOperation})
    Return budgetRetval.value(0)
  Catch e As Exception
    Throw New System.ApplicationException("Failed to add shared budget.", e)
  End Try
End Using

Como atribuir um orçamento a uma campanha

Depois de criar ou identificar um Budget com BudgetService, use o código do orçamento resultante em uma chamada subsequente para CampaignService. Se a operação do orçamento for bem-sucedida, um orçamento órfão (orçamento sem associação a nenhuma campanha) será criado, mesmo se houver falha na operação de campanha. Recomendamos que você reutilize ou remova esses orçamentos.

Nova campanha

Para uma nova campanha, na operação CampaignService.mutate() do ADD, defina o atributo budget da campanha como um objeto Budget com o budgetId definido como o código de um orçamento, conforme demonstrado no exemplo de código abaixo.

Java

// Get the CampaignService.
CampaignServiceInterface campaignService =
    adWordsServices.get(session, CampaignServiceInterface.class);

// Create campaign.
Campaign campaign = new Campaign();
campaign.setName("Interplanetary Cruise #" + System.currentTimeMillis());

// 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.setStatus(CampaignStatus.PAUSED);

BiddingStrategyConfiguration biddingStrategyConfiguration = new BiddingStrategyConfiguration();
biddingStrategyConfiguration.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);

// You can optionally provide a bidding scheme in place of the type.
ManualCpcBiddingScheme cpcBiddingScheme = new ManualCpcBiddingScheme();
biddingStrategyConfiguration.setBiddingScheme(cpcBiddingScheme);

campaign.setBiddingStrategyConfiguration(biddingStrategyConfiguration);

// You can optionally provide these field(s).
campaign.setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"));
campaign.setEndDate(new DateTime().plusDays(30).toString("yyyyMMdd"));
campaign.setFrequencyCap(new FrequencyCap(5L, TimeUnit.DAY, Level.ADGROUP));

// Only the budgetId should be sent, all other fields will be ignored by CampaignService.
Budget budget = new Budget();
budget.setBudgetId(budgetId);
campaign.setBudget(budget);

campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);

// Set the campaign network options to Search and Search Network.
NetworkSetting networkSetting = new NetworkSetting();
networkSetting.setTargetGoogleSearch(true);
networkSetting.setTargetSearchNetwork(true);
networkSetting.setTargetContentNetwork(false);
networkSetting.setTargetPartnerSearchNetwork(false);
campaign.setNetworkSetting(networkSetting);

// Set options that are not required.
GeoTargetTypeSetting geoTarget = new GeoTargetTypeSetting();
geoTarget.setPositiveGeoTargetType(GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE);
campaign.setSettings(new Setting[] {geoTarget});

// You can create multiple campaigns in a single request.
Campaign campaign2 = new Campaign();
campaign2.setName("Interplanetary Cruise banner #" + System.currentTimeMillis());
campaign2.setStatus(CampaignStatus.PAUSED);
BiddingStrategyConfiguration biddingStrategyConfiguration2 = new BiddingStrategyConfiguration();
biddingStrategyConfiguration2.setBiddingStrategyType(BiddingStrategyType.MANUAL_CPC);
campaign2.setBiddingStrategyConfiguration(biddingStrategyConfiguration2);

Budget budget2 = new Budget();
budget2.setBudgetId(budgetId);
campaign2.setBudget(budget2);

campaign2.setAdvertisingChannelType(AdvertisingChannelType.DISPLAY);

// Create operations.
CampaignOperation operation = new CampaignOperation();
operation.setOperand(campaign);
operation.setOperator(Operator.ADD);
CampaignOperation operation2 = new CampaignOperation();
operation2.setOperand(campaign2);
operation2.setOperator(Operator.ADD);

CampaignOperation[] operations = new CampaignOperation[] {operation, operation2};

// Add campaigns.
CampaignReturnValue result = campaignService.mutate(operations);

// Display campaigns.
for (Campaign campaignResult : result.getValue()) {
  System.out.printf("Campaign with name '%s' and ID %d was added.%n", campaignResult.getName(),
      campaignResult.getId());
}

CSharp

List<CampaignOperation> operations = new List<CampaignOperation>();

for (int i = 0; i < NUM_ITEMS; i++) {
  // Create the campaign.
  Campaign campaign = new Campaign();
  campaign.name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString();
  campaign.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.
  campaign.status = CampaignStatus.PAUSED;

  BiddingStrategyConfiguration biddingConfig = new BiddingStrategyConfiguration();
  biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC;
  campaign.biddingStrategyConfiguration = biddingConfig;

  campaign.budget = new Budget();
  campaign.budget.budgetId = budget.budgetId;

  // Set the campaign network options.
  campaign.networkSetting = new NetworkSetting();
  campaign.networkSetting.targetGoogleSearch = true;
  campaign.networkSetting.targetSearchNetwork = true;
  campaign.networkSetting.targetContentNetwork = false;
  campaign.networkSetting.targetPartnerSearchNetwork = false;

  // Set the campaign settings for Advanced location options.
  GeoTargetTypeSetting geoSetting = new GeoTargetTypeSetting();
  geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE;
  geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE;

  campaign.settings = new Setting[] { geoSetting };

  // Optional: Set the start date.
  campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd");

  // Optional: Set the end date.
  campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd");

  // Optional: Set the frequency cap.
  FrequencyCap frequencyCap = new FrequencyCap();
  frequencyCap.impressions = 5;
  frequencyCap.level = Level.ADGROUP;
  frequencyCap.timeUnit = TimeUnit.DAY;
  campaign.frequencyCap = frequencyCap;

  // Create the operation.
  CampaignOperation operation = new CampaignOperation();
  operation.@operator = Operator.ADD;
  operation.operand = campaign;

  operations.Add(operation);
}

try {
  // Add the campaign.
  CampaignReturnValue retVal = campaignService.mutate(operations.ToArray());

  // Display the results.
  if (retVal != null && retVal.value != null && retVal.value.Length > 0) {
    foreach (Campaign newCampaign in retVal.value) {
      Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
          newCampaign.name, newCampaign.id);
    }
  } else {
    Console.WriteLine("No campaigns were added.");
  }
} catch (Exception e) {
  throw new System.ApplicationException("Failed to add campaigns.", e);
}

Python

operations = [{
    'operator': 'ADD',
    'operand': {
        'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
        # 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',
        'advertisingChannelType': 'SEARCH',
        'biddingStrategyConfiguration': {
            'biddingStrategyType': 'MANUAL_CPC',
        },
        'endDate': (datetime.datetime.now() +
                    datetime.timedelta(365)).strftime('%Y%m%d'),
        # Note that only the budgetId is required
        'budget': {
            'budgetId': budget_id
        },
        'networkSetting': {
            'targetGoogleSearch': 'true',
            'targetSearchNetwork': 'true',
            'targetContentNetwork': 'false',
            'targetPartnerSearchNetwork': 'false'
        },
        # Optional fields
        'startDate': (datetime.datetime.now() +
                      datetime.timedelta(1)).strftime('%Y%m%d'),
        'frequencyCap': {
            'impressions': '5',
            'timeUnit': 'DAY',
            'level': 'ADGROUP'
        },
        'settings': [
            {
                'xsi_type': 'GeoTargetTypeSetting',
                'positiveGeoTargetType': 'DONT_CARE',
                'negativeGeoTargetType': 'DONT_CARE'
            }
        ]
    }
}, {
    'operator': 'ADD',
    'operand': {
        'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
        'status': 'PAUSED',
        'biddingStrategyConfiguration': {
            'biddingStrategyType': 'MANUAL_CPC'
        },
        'endDate': (datetime.datetime.now() +
                    datetime.timedelta(365)).strftime('%Y%m%d'),
        # Note that only the budgetId is required
        'budget': {
            'budgetId': budget_id
        },
        'advertisingChannelType': 'DISPLAY'
    }
}]
campaigns = campaign_service.mutate(operations)

# Display results.
for campaign in campaigns['value']:
  print ('Campaign with name "%s" and id "%s" was added.'
         % (campaign['name'], campaign['id']))

PHP

$campaignService = $adWordsServices->get($session, CampaignService::class);

$operations = [];

// Create a campaign with required and optional settings.
$campaign = new Campaign();
$campaign->setName('Interplanetary Cruise #' . uniqid());
$campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);

// Set shared budget (required).
$campaign->setBudget(new Budget());
$campaign->getBudget()->setBudgetId($budget->getBudgetId());

// Set bidding strategy (required).
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBiddingStrategyType(
    BiddingStrategyType::MANUAL_CPC
);

// You can optionally provide a bidding scheme in place of the type.
$biddingScheme = new ManualCpcBiddingScheme();
$biddingStrategyConfiguration->setBiddingScheme($biddingScheme);

$campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

// Set network targeting (optional).
$networkSetting = new NetworkSetting();
$networkSetting->setTargetGoogleSearch(true);
$networkSetting->setTargetSearchNetwork(true);
$networkSetting->setTargetContentNetwork(true);
$campaign->setNetworkSetting($networkSetting);

// Set additional settings (optional).
// 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.
$campaign->setStatus(CampaignStatus::PAUSED);
$campaign->setStartDate(date('Ymd', strtotime('+1 day')));
$campaign->setEndDate(date('Ymd', strtotime('+1 month')));

// Set frequency cap (optional).
$frequencyCap = new FrequencyCap();
$frequencyCap->setImpressions(5);
$frequencyCap->setTimeUnit(TimeUnit::DAY);
$frequencyCap->setLevel(Level::ADGROUP);
$campaign->setFrequencyCap($frequencyCap);

// Set advanced location targeting settings (optional).
$geoTargetTypeSetting = new GeoTargetTypeSetting();
$geoTargetTypeSetting->setPositiveGeoTargetType(
    GeoTargetTypeSettingPositiveGeoTargetType::DONT_CARE
);
$geoTargetTypeSetting->setNegativeGeoTargetType(
    GeoTargetTypeSettingNegativeGeoTargetType::DONT_CARE
);
$campaign->setSettings([$geoTargetTypeSetting]);

// Create a campaign operation and add it to the operations list.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

// Create a campaign with only required settings.
$campaign = new Campaign();
$campaign->setName('Interplanetary Cruise #' . uniqid());
$campaign->setAdvertisingChannelType(AdvertisingChannelType::DISPLAY);

// Set shared budget (required).
$campaign->setBudget(new Budget());
$campaign->getBudget()->setBudgetId($budget->getBudgetId());

// Set bidding strategy (required).
$biddingStrategyConfiguration = new BiddingStrategyConfiguration();
$biddingStrategyConfiguration->setBiddingStrategyType(
    BiddingStrategyType::MANUAL_CPC
);
$campaign->setBiddingStrategyConfiguration($biddingStrategyConfiguration);

$campaign->setStatus(CampaignStatus::PAUSED);

// Create a campaign operation and add it to the operations list.
$operation = new CampaignOperation();
$operation->setOperand($campaign);
$operation->setOperator(Operator::ADD);
$operations[] = $operation;

// Create the campaigns on the server and print out some information for
// each created campaign.
$result = $campaignService->mutate($operations);
foreach ($result->getValue() as $campaign) {
    printf(
        "Campaign with name '%s' and ID %d was added.\n",
        $campaign->getName(),
        $campaign->getId()
    );
}

Perl

# Create campaigns.
my $num_campaigns = 2;
my @operations    = ();
for (my $i = 0 ; $i < $num_campaigns ; $i++) {
  my (undef, undef, undef, $mday, $mon, $year) = localtime(time);
  my $today = sprintf("%d%02d%02d", ($year + 1900), ($mon + 1), $mday);
  (undef, undef, undef, $mday, $mon, $year) = localtime(time + 60 * 60 * 24);
  my $tomorrow = sprintf("%d%02d%02d", ($year + 1900), ($mon + 1), $mday);
  my $campaign = Google::Ads::AdWords::v201802::Campaign->new({
      name => "Interplanetary Cruise #" . uniqid(),
      # Bidding strategy (required).
      biddingStrategyConfiguration =>
        Google::Ads::AdWords::v201802::BiddingStrategyConfiguration->new({
          biddingStrategyType => "MANUAL_CPC",
          # You can optionally provide a bidding scheme in place of the type.
        }
        ),
      # Budget (required) - note only the budgetId is required.
      budget =>
        Google::Ads::AdWords::v201802::Budget->new({budgetId => $budgetId}),
      # Create a Search Network with Display Select campaign.
      # To create a Display Only campaign, omit networkSetting and use the
      # DISPLAY advertisingChannelType.
      # NetworkSetting (optional).
      networkSetting => Google::Ads::AdWords::v201802::NetworkSetting->new({
          targetGoogleSearch         => 1,
          targetSearchNetwork        => 1,
          targetContentNetwork       => 1,
          targetPartnerSearchNetwork => 0
        }
      ),
      # Advertising channel type (required).
      advertisingChannelType => "SEARCH",
      # Frequency cap (non-required).
      frequencyCap => Google::Ads::AdWords::v201802::FrequencyCap->new({
          impressions => 5,
          timeUnit    => "DAY",
          level       => "ADGROUP"
        }
      ),
      settings => [
        # Advanced location targeting settings (non-required).
        Google::Ads::AdWords::v201802::GeoTargetTypeSetting->new({
            positiveGeoTargetType => "DONT_CARE",
            negativeGeoTargetType => "DONT_CARE"
          }
        ),
      ],
      # Additional properties (non-required).
      startDate                   => $today,
      endDate                     => $tomorrow,
      # 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"
    });

  # Create operation.
  my $campaign_operation =
    Google::Ads::AdWords::v201802::CampaignOperation->new({
      operator => "ADD",
      operand  => $campaign
    });
  push @operations, $campaign_operation;
}

# Add campaigns.
my $result = $client->CampaignService()->mutate({operations => \@operations});

# Display campaigns.
foreach my $campaign (@{$result->get_value()}) {
  printf "Campaign with name \"%s\" and id \"%s\" was added.\n",
    $campaign->get_name(), $campaign->get_id();
}

Ruby

campaign_srv = adwords.service(:CampaignService, API_VERSION)

# Create campaigns.
campaigns = [
  {
    :name => "Interplanetary Cruise #%d" % (Time.new.to_f * 1000).to_i,
    # 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',
    :bidding_strategy_configuration => {
      :bidding_strategy_type => 'MANUAL_CPC'
    },
    # Budget (required) - note only the budget ID is required.
    :budget => {:budget_id => budget_id},
    :advertising_channel_type => 'SEARCH',
    # Optional fields:
    :start_date =>
        DateTime.parse((Date.today + 1).to_s).strftime('%Y%m%d'),
    :network_setting => {
      :target_google_search => true,
      :target_search_network => true,
      :target_content_network => true
    },
    :settings => [
      {
        :xsi_type => 'GeoTargetTypeSetting',
        :positive_geo_target_type => 'DONT_CARE',
        :negative_geo_target_type => 'DONT_CARE'
      }
    ],
    :frequency_cap => {
      :impressions => '5',
      :time_unit => 'DAY',
      :level => 'ADGROUP'
    }
  },
  {
    :name => "Interplanetary Cruise banner #%d" % (Time.new.to_f * 1000).to_i,
    :status => 'PAUSED',
    :bidding_strategy_configuration => {
      :bidding_strategy_type => 'MANUAL_CPC'
    },
    :budget => {:budget_id => budget_id},
    :advertising_channel_type => 'DISPLAY'
  }
]

# Prepare for adding campaign.
operations = campaigns.map do |campaign|
  {:operator => 'ADD', :operand => campaign}
end

# Add campaign.
response = campaign_srv.mutate(operations)
if response and response[:value]
  response[:value].each do |campaign|
    puts "Campaign with name '%s' and ID %d was added." %
        [campaign[:name], campaign[:id]]
  end
else
  raise new StandardError, 'No campaigns were added.'
end

VB.NET

  Dim operations As New List(Of CampaignOperation)

  For i As Integer = 1 To NUM_ITEMS
    ' Create the campaign.
    Dim campaign As New Campaign
    campaign.name = "Interplanetary Cruise #" & ExampleUtilities.GetRandomString
    campaign.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.
    campaign.status = CampaignStatus.PAUSED

    Dim biddingConfig As New BiddingStrategyConfiguration()
    biddingConfig.biddingStrategyType = BiddingStrategyType.MANUAL_CPC
    campaign.biddingStrategyConfiguration = biddingConfig

    ' Set the campaign budget.
    campaign.budget = New Budget
    campaign.budget.budgetId = budget.budgetId

    ' Set the campaign network options.
    campaign.networkSetting = New NetworkSetting
    campaign.networkSetting.targetGoogleSearch = True
    campaign.networkSetting.targetSearchNetwork = True
    campaign.networkSetting.targetContentNetwork = False
    campaign.networkSetting.targetPartnerSearchNetwork = False

    ' Set the campaign geo target and keyword match settings.
    Dim geoSetting As New GeoTargetTypeSetting
    geoSetting.positiveGeoTargetType = GeoTargetTypeSettingPositiveGeoTargetType.DONT_CARE
    geoSetting.negativeGeoTargetType = GeoTargetTypeSettingNegativeGeoTargetType.DONT_CARE

    campaign.settings = New Setting() {geoSetting}

    ' Optional: Set the start date.
    campaign.startDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd")

    ' Optional: Set the end date.
    campaign.endDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd")

    ' Optional: Set the frequency cap.
    Dim frequencyCap As New FrequencyCap
    frequencyCap.impressions = 5
    frequencyCap.level = Level.ADGROUP
    frequencyCap.timeUnit = TimeUnit.DAY
    campaign.frequencyCap = frequencyCap

    ' Create the operation.
    Dim operation As New CampaignOperation
    operation.operator = [Operator].ADD
    operation.operand = campaign
    operations.Add(operation)
  Next

  Try
    ' Add the campaign.
    Dim retVal As CampaignReturnValue = campaignService.mutate(operations.ToArray())

    ' Display the results.
    If ((Not retVal Is Nothing) AndAlso (Not retVal.value Is Nothing) AndAlso
      (retVal.value.Length > 0)) Then
      For Each newCampaign As Campaign In retVal.value
        Console.WriteLine("Campaign with name = '{0}' and id = '{1}' was added.",
            newCampaign.name, newCampaign.id)
      Next
    Else
      Console.WriteLine("No campaigns were added.")
    End If
  Catch e As Exception
    Throw New System.ApplicationException("Failed to add campaigns.", e)
  End Try
End Using

Como substituir o orçamento de uma campanha

Para substituir o orçamento de uma campanha existente, use uma operação SET no CampaignService.mutate() e defina o atributo budget de uma campanha como um objeto Budget com o budgetId definido como o ID do orçamento existente (juntamente com outros campos da campanha que você queira configurar). Isso substitui o orçamento existente associado à campanha por aquele especificado pelo budgetId, pois uma campanha pode estar associada a mais de um orçamento por vez.

Como dissociar um orçamento de uma campanha

A campanha sempre precisa estar associada a um orçamento. Para remover um orçamento de uma campanha, altere o código do orçamento associado à campanha e substitua-o por outro. Para identificar as campanhas que usam um orçamento específico, consulte Como recuperar a lista de campanhas de um determinado orçamento.

Como remover um orçamento

Assim como as campanhas, um orçamento não pode ser completamente excluído. Só é possível definir o status como REMOVED.

Antes de remover um orçamento, garanta que ele não está sendo usado por nenhuma campanha ENABLED ou PAUSED. Para isso, verifique sua referenceCount. Se esse campo for maior que 0, significa que ainda há campanhas ENABLED ou PAUSED usando o orçamento. Você pode recuperar o referenceCount do orçamento por meio de uma operação BudgetService.get() ou o campo referenceCount a partir de uma operação CampaignService.get().

Depois de determinar que um Budget não é mais usado, envie uma BudgetOperation para BudgetService.mutate() com:

  • operator = SET
  • operand definido como um Budget com:
    • budgetId definido como o código do orçamento
    • status definido como REMOVED

Além disso, é possível remover um orçamento não compartilhado que é usado por uma única campanha. Para fazer isso, remova essa campanha. Quando você define o status de uma dessas campanhas como REMOVED, o status do orçamento não compartilhado usado por ela também é automaticamente definido como REMOVED.

Como recuperar a lista de campanhas para determinado orçamento

Receber uma lista de campanhas que usam o mesmo orçamento pode ser útil para equilibrar o uso dos orçamentos. A seguinte consulta AWQL ao CampaignService retornará todas as campanhas referentes ao código de orçamento especificado:

SELECT Id WHERE BudgetId = <YOUR_BUDGET_ID>

Se preferir, você pode usar essa declaração de AWQL para receber as mesmas informações do Relatório de desempenho de campanhas:

SELECT CampaignId, BudgetId, IsBudgetExplicitlyShared, Impressions
FROM CAMPAIGN_PERFORMANCE_REPORT
WHERE BudgetId = <YOUR_BUDGET_ID>

Acompanhamento de desempenho

Para recuperar as estatísticas de desempenho do orçamento, use um Relatório de desempenho do orçamento, que inclui todas as estatísticas reunidas, por padrão, no nível do orçamento, uma linha por orçamento. Se os campos de segmento forem utilizados, você poderá ter mais de uma linha por orçamento. Consulte segmentação para ver mais detalhes.

Restrições

As campanhas que tiverem experimentos de campanha ativos precisam ter um orçamento não compartilhado e exclusivo.

Erros comuns

Erro Descrição
BudgetError.CANNOT_UPDATE_BUDGET_TO_IMPLICITLY_SHARED Indica que você tentou definir o valor isExplicitlyShared de um orçamento de true para false em uma operação SET. Quando um orçamento é compartilhado explicitamente (isExplicitlyShared = true), não é possível alterar o isExplicitlyShared de volta para false.
EntityCountLimitExceeded.ACCOUNT_LIMIT Indica que você atingiu o número máximo de orçamentos em uma conta.
CampaignError.CAMPAIGN_CANNOT_USE_SHARED_BUDGET A campanha à qual você está tentando adicionar o orçamento usa experimentos de campanha. Além disso, o orçamento já está sendo usado por outra campanha.
BudgetError.CANNOT_EDIT_SHARED_BUDGET Você está tentando modificar o orçamento associado a uma campanha usando o CampaignService. No entanto, essa operação só pode ser feita por meio do BudgetService.
BudgetError.BUDGET_IN_USE Você está tentando remover um orçamento associado a uma ou mais campanhas ativas ou pausadas.

Enviar comentários sobre…

Precisa de ajuda? Acesse nossa página de suporte.