キャンペーンの予算

予算は AdWords キャンペーンの費用の管理に使います。このガイドでは AdWords API を使った予算管理の情報を提供し、予算の共有、割り当て、削除や効果のトラッキングなどを詳しく説明します。

予算を共有する

予算は 1 つのキャンペーンに適用するか、複数のキャンペーンで共有することができます。

AdWords API を使って作成した Budget はデフォルトで共有可能な状態です。 これを確認するには、BudgetService の API 呼び出しで isExplicitlyShared の値をチェックします。

  • isExplicitlyShared = true: 複数のキャンペーンで予算を共有できる
  • isExplicitlyShared = false: 予算は 1 つのキャンペーンに適用される

明示的に共有している予算は 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

予算をキャンペーンに割り当てる

BudgetService を使って Budget を作成または特定したら、作成した予算 ID を以降の CampaignService の呼び出しで使用します。なお、キャンペーンの処理が失敗して予算の処理だけ成功した場合は、孤立した状態の予算(どのキャンペーンにも関連付けられていない予算)がそのまま作成されます。そうした予算は再利用するか削除することをおすすめします。

新しいキャンペーン

新しいキャンペーンを作成したら、下記のコードサンプルのように CampaignService.mutate()ADD オペレーションでキャンペーンの budget 属性を Budget オブジェクトに設定します。その際、budgetId は予算の ID に設定してください。

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 も既存の予算の ID に設定します(キャンペーンの他の設定項目と一緒に処理できます)。なお、この処理ではキャンペーンに割り当てられている既存の予算が、budgetId で指定された予算に置換されます。キャンペーンには一度に 1 つの予算しか関連付けることができません。

予算とキャンペーンの関連付けを解除する

キャンペーンには常に予算が関連付けられている必要があります。キャンペーンに関連付けられている予算の ID を変更して別の予算に置換すれば、キャンペーンから予算を削除できます。特定の予算をどのキャンペーンが使用しているか確認する方法については、同じ予算を使用しているキャンペーンのリストを取得するをご覧ください。

予算を削除する

キャンペーンと同じように、予算も完全には削除できません。ステータスを REMOVED に設定できるだけです。

予算を削除する前に、referenceCount を確認して、ENABLED または PAUSED のキャンペーンがその予算を使用していないことを確認してください。 このフィールドが 0 より大きい場合、まだその予算を使用している ENABLED または PAUSED のキャンペーンがあります。予算の referenceCountBudgetService.get() オペレーションで取得できます。CampaignService.get() オペレーションから referenceCount フィールドを取得することもできます。

Budget が使用されていないことを確認したら、次のように設定して指定した BudgetOperationBudgetService.mutate() に渡します。

  • operator = SET
  • operand = Budget:
    • budgetId を予算の ID に設定
    • statusREMOVED に設定

また、1 つのキャンペーンだけで使用されている予算は、そのキャンペーンを削除することで削除できます。そうしたキャンペーンのステータスを REMOVED に設定すると、そのキャンペーンの予算のステータスも自動的に REMOVED に設定されます。

同じ予算を使用しているキャンペーンのリストを取得する

同じ予算を使用しているキャンペーンのリストを取得すると、予算の利用のバランスをとる際に便利です。CampaignService への次の AWQL クエリは、指定した予算 ID のすべてのキャンペーンを返します。

SELECT Id WHERE BudgetId = <YOUR_BUDGET_ID>

また、次の AWQL ステートメントを使用すると、キャンペーンの掲載結果レポートから同じ情報を得ることができます。

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

掲載結果のトラッキング

予算の掲載結果レポートを使用して、キャンペーンの予算に基づく掲載結果データを取得できます。このレポートには、予算ごとにデフォルトで集計されるすべての掲載結果データが表示されます。通常、各予算のデータは 1 行に表示されますが、セグメント フィールドを使用している場合は複数行になる場合もあります。詳細についてはセグメントをご覧ください。

制限事項

キャンペーンのテストを実施する場合は、どのキャンペーンとも共有しない専用の予算を設定する必要があります。

一般的なエラー

エラー 説明
BudgetError.CANNOT_UPDATE_BUDGET_TO_IMPLICITLY_SHARED 予算の isExplicitlyShared の値を SET オペレーションで true から false に変更しようとしました。予算を明示的に共有した場合は(isExplicitlyShared = true)、isExplicitlySharedfalse に戻すことはできません。
EntityCountLimitExceeded.ACCOUNT_LIMIT アカウントの予算が最大数に達しました。
CampaignError.CAMPAIGN_CANNOT_USE_SHARED_BUDGET 予算を追加しようとしているキャンペーンではテストが実施されており、その予算はすでに別のキャンペーンで使用されています。
BudgetError.CANNOT_EDIT_SHARED_BUDGET キャンペーンに関連付けられている予算を CampaignService を使って変更しようとしています。予算の変更は BudgetService で行ってください。
BudgetError.BUDGET_IN_USE 有効なキャンペーンや一時停止中のキャンペーンに関連付けられている予算を削除しようとしています。

フィードバックを送信...

ご不明な点がありましたら、Google のサポートページをご覧ください。