Бюджеты кампаний

С помощью бюджетов можно контролировать затраты на рекламные кампании AdWords. Из этого руководства вы узнаете, как работать с бюджетами в AdWords API: назначать их, удалять, использовать в нескольких кампаниях и отслеживать их эффективность.

Использование бюджетов в нескольких кампаниях

Бюджет может относиться к одной кампании или же быть общим, то есть использоваться сразу в нескольких кампаниях.

Новый объект Budget, созданный через AdWords API, по умолчанию доступен для использования сразу в нескольких кампаниях. Чтобы в этом убедиться, проверьте значение поля isExplicitlyShared, отправив вызов службе BudgetService:

  • isExplicitlyShared = true означает, что бюджет можно использовать в нескольких кампаниях.
  • isExplicitlyShared = false означает, что бюджет можно использовать только в одной кампании.

Общие бюджеты отображаются в Общей библиотеке веб-интерфейса AdWords, а частные – только на вкладке Настройки той кампании, где они используются.

В примере ниже описано создание общего бюджета (для поля isExplicitlyShared указано значение по умолчанию – 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();

C#

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

Назначение бюджета кампании

Создав или идентифицировав объект Budget с помощью BudgetService, используйте полученный идентификатор бюджета в последующих вызовах CampaignService. Обратите внимание, что в случае сбоя операции в кампании будет создан "неназначенный" бюджет (то есть бюджет, который не связан ни с одной кампанией). Мы рекомендуем повторно использовать такие бюджеты или удалить их.

Как назначить бюджет для новой кампании

В методе CampaignService.mutate() с помощью операции ADD назначьте атрибуту кампании budget объект Budget с идентификатором бюджета в поле budgetId (см. пример кода ниже).

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());
}

C#

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

Как изменить бюджет кампании

Чтобы изменить бюджет кампании, используйте операцию CampaignService.mutate() SET и укажите для атрибута budget кампании объект Budget, задав в поле budgetId идентификатор существующего бюджета (а также установив другие нужные вам поля). Учтите, что в результате существующий бюджет, назначенный этой кампании, будет заменен на указанный в поле budgetId.

Отмена связи между бюджетом и кампанией

Кампания всегда должна быть связана с бюджетом. Однако вы можете выбрать другой бюджет, изменив идентификатор связанного с кампанией бюджета. О том, как найти кампании, в которых используется тот или иной бюджет, читайте в разделе Как получить список кампаний с одним бюджетом.

Удаление бюджета

Сами бюджеты, как и кампании, нельзя удалить – можно только установить для них статус REMOVED.

Прежде чем удалять бюджет, убедитесь, что он не используется в активных (ENABLED) или приостановленных (PAUSED) кампаниях, проверив поле referenceCount. Если значение в поле больше 0, значит, у вас есть кампании со статусом ENABLED или PAUSED, в которых он используется. Вы можете получить значение поля referenceCount с помощью операции BudgetService.get() или значение поля referenceCount с помощью операции CampaignService.get().

Убедившись, что Budget больше не используется, отправьте в BudgetService.mutate() команду BudgetOperation со следующими значениями:

  • operator = SET
  • Параметры объекта Budget в operand:
    • budgetId = идентификатор бюджета;
    • status = REMOVED.

Кроме того, частный бюджет, который используется только в одной кампании, можно удалить вместе с кампанией. Если установить для такой кампании статус REMOVED, статус связанного с ней необщего бюджета также автоматически изменится на REMOVED.

Как получить список кампаний с одним бюджетом

В целях управления бюджетом вам может понадобиться список кампаний, в которых он используется. Получить такой список можно с помощью следующего запроса AWQL:

SELECT Id WHERE BudgetId = <YOUR_BUDGET_ID>

Чтобы получить эту же информацию из отчета об эффективности кампаний, используйте следующее выражение AWQL:

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

Отслеживание эффективности

Статистику по бюджетам можно получать из отчета об эффективности бюджетов. По умолчанию все данные в нем агрегируются на уровне бюджета. Каждому бюджету соответствует одна строка. Если используются поля сегментирования, одному бюджету может соответствовать несколько строк. Подробнее о сегментировании…

Ограничения

У каждой кампании, с которой проводятся эксперименты, должен быть собственный необщий бюджет.

Распространенные ошибки

Ошибка Описание
BudgetError.CANNOT_UPDATE_BUDGET_TO_IMPLICITLY_SHARED Указывает, что вы попытались изменить значение поля isExplicitlyShared бюджета с true на false в операции SET. Сделав бюджет общим (isExplicitlyShared = true), вы уже не можете изменить значение isExplicitlyShared обратно на false.
EntityCountLimitExceeded.ACCOUNT_LIMIT В аккаунте достигнуто максимальное количество бюджетов.
CampaignError.CAMPAIGN_CANNOT_USE_SHARED_BUDGET В кампании, куда вы пытаетесь добавить бюджет, проводятся эксперименты либо бюджет уже используется в какой-либо другой кампании.
BudgetError.CANNOT_EDIT_SHARED_BUDGET Эта ошибка означает, что вы пытаетесь изменить бюджет, связанный с кампанией, с помощью службы CampaignService. Изменять бюджеты можно только с помощью службы BudgetService.
BudgetError.BUDGET_IN_USE Вы пытаетесь удалить бюджет, который связан как минимум с одной активной или приостановленной кампанией.

Оставить отзыв о...

Текущей странице
Нужна помощь? Обратитесь в службу поддержки.