Ява
// Copyright 2023 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.travel;
import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;
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.v17.common.MaximizeConversionValue;
import com.google.ads.googleads.v17.common.TravelAdInfo;
import com.google.ads.googleads.v17.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v17.enums.AdGroupStatusEnum.AdGroupStatus;
import com.google.ads.googleads.v17.enums.AdGroupTypeEnum.AdGroupType;
import com.google.ads.googleads.v17.enums.AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType;
import com.google.ads.googleads.v17.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v17.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod;
import com.google.ads.googleads.v17.enums.CampaignStatusEnum.CampaignStatus;
import com.google.ads.googleads.v17.errors.GoogleAdsError;
import com.google.ads.googleads.v17.errors.GoogleAdsException;
import com.google.ads.googleads.v17.resources.Ad;
import com.google.ads.googleads.v17.resources.AdGroup;
import com.google.ads.googleads.v17.resources.AdGroupAd;
import com.google.ads.googleads.v17.resources.Campaign;
import com.google.ads.googleads.v17.resources.Campaign.NetworkSettings;
import com.google.ads.googleads.v17.resources.Campaign.TravelCampaignSettings;
import com.google.ads.googleads.v17.resources.CampaignBudget;
import com.google.ads.googleads.v17.services.AdGroupAdOperation;
import com.google.ads.googleads.v17.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v17.services.AdGroupOperation;
import com.google.ads.googleads.v17.services.AdGroupServiceClient;
import com.google.ads.googleads.v17.services.CampaignBudgetOperation;
import com.google.ads.googleads.v17.services.CampaignBudgetServiceClient;
import com.google.ads.googleads.v17.services.CampaignOperation;
import com.google.ads.googleads.v17.services.CampaignServiceClient;
import com.google.ads.googleads.v17.services.MutateAdGroupAdResult;
import com.google.ads.googleads.v17.services.MutateAdGroupResult;
import com.google.ads.googleads.v17.services.MutateCampaignBudgetsResponse;
import com.google.ads.googleads.v17.services.MutateCampaignResult;
import com.google.ads.googleads.v17.services.MutateCampaignsResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Collections;
/**
* Creates a Things to do campaign, an ad group and a Things to do ad.
*
* <p>Prerequisite: You need to have an access to the Things to Do Center. The integration
* instructions can be found at: https://support.google.com/google-ads/answer/13387362.
*/
public class AddThingsToDoAd {
private static class AddThingsToDoAdParams extends CodeSampleParams {
@Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
private Long customerId;
@Parameter(names = ArgumentNames.THINGS_TO_DO_CENTER_ACCOUNT_ID, required = true)
private Long thingsToDoCenterAccountId;
}
public static void main(String[] args) {
AddThingsToDoAdParams params = new AddThingsToDoAdParams();
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");
params.thingsToDoCenterAccountId =
Long.parseLong("INSERT_THINGS_TO_DO_CENTER_ACCOUNT_ID_HERE");
}
GoogleAdsClient googleAdsClient = null;
try {
googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
} catch (FileNotFoundException fnfe) {
System.err.printf(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
System.exit(1);
} catch (IOException ioe) {
System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
System.exit(1);
}
try {
new AddThingsToDoAd()
.runExample(googleAdsClient, params.customerId, params.thingsToDoCenterAccountId);
} catch (GoogleAdsException gae) {
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System.err.printf(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
gae.getRequestId());
int i = 0;
for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
System.err.printf(" Error %d: %s%n", i++, googleAdsError);
}
System.exit(1);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param thingsToDoCenterAccountId the Things to Do Center account ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private void runExample(
GoogleAdsClient googleAdsClient, long customerId, long thingsToDoCenterAccountId) {
// Creates a budget to be used by the campaign that will be created below.
String budgetResourceName = addCampaignBudget(googleAdsClient, customerId);
// Creates a Things to do campaign.
String campaignResourceName =
addThingsToDoCampaign(
googleAdsClient, customerId, budgetResourceName, thingsToDoCenterAccountId);
// Creates an ad group.
String adGroupResourceName = addAdGroup(googleAdsClient, customerId, campaignResourceName);
// Creates an ad group ad.
addAddGroupAd(googleAdsClient, customerId, adGroupResourceName);
}
/**
* Creates a new campaign budget in the specified client account.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @return resource name of the newly created budget.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addCampaignBudget(GoogleAdsClient googleAdsClient, long customerId) {
CampaignBudget budget =
CampaignBudget.newBuilder()
.setName("Interplanetary Cruise Budget #" + getPrintableDateTime())
.setDeliveryMethod(BudgetDeliveryMethod.STANDARD)
// Sets the amount of the budget.
.setAmountMicros(5_000_000)
// Makes the budget explicitly shared. You cannot set it to false for Things to do
// campaigns.
.setExplicitlyShared(true)
.build();
// Creates a campaign budget operation.
CampaignBudgetOperation op = CampaignBudgetOperation.newBuilder().setCreate(budget).build();
// Issues a mutate request.
try (CampaignBudgetServiceClient campaignBudgetServiceClient =
googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) {
MutateCampaignBudgetsResponse response =
campaignBudgetServiceClient.mutateCampaignBudgets(
Long.toString(customerId), ImmutableList.of(op));
String budgetResourceName = response.getResults(0).getResourceName();
System.out.printf("Added a budget with resource name: '%s'%n", budgetResourceName);
return budgetResourceName;
}
}
/**
* Creates a new Things to do campaign in the specified client account.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param budgetResourceName the resource name of the budget for the campaign.
* @param thingsToDoCenterAccountId the Things to Do Center account ID.
* @return resource name of the newly created campaign.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addThingsToDoCampaign(
GoogleAdsClient googleAdsClient,
long customerId,
String budgetResourceName,
long thingsToDoCenterAccountId) {
// Creates the campaign.
Campaign campaign =
Campaign.newBuilder()
.setName("Interplanetary Cruise #" + getPrintableDateTime())
// Configures settings related to Things to do campaigns including advertising channel
// type, advertising channel sub type and travel campaign settings.
.setAdvertisingChannelType(AdvertisingChannelType.TRAVEL)
.setAdvertisingChannelSubType(AdvertisingChannelSubType.TRAVEL_ACTIVITIES)
.setTravelCampaignSettings(
TravelCampaignSettings.newBuilder().setTravelAccountId(thingsToDoCenterAccountId))
// Recommendation: Sets 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
.setStatus(CampaignStatus.PAUSED)
// Sets the bidding strategy to MaximizeConversionValue. Only this type can be used
// for Things to do campaigns.
.setMaximizeConversionValue(MaximizeConversionValue.newBuilder())
// Sets the budget.
.setCampaignBudget(budgetResourceName)
// Configures the campaign network options. Only Google Search is allowed for
// Things to do campaigns.
.setNetworkSettings(NetworkSettings.newBuilder().setTargetGoogleSearch(true))
.build();
// Creates a campaign operation.
CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();
// Issues a mutate request to add the campaign.
try (CampaignServiceClient campaignServiceClient =
googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
MutateCampaignsResponse response =
campaignServiceClient.mutateCampaigns(
Long.toString(customerId), Collections.singletonList(operation));
MutateCampaignResult result = response.getResults(0);
System.out.printf(
"Added a Things to do campaign with resource name: '%s'%n", result.getResourceName());
return result.getResourceName();
}
}
/**
* Creates a new ad group in the specified Things to do campaign.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param campaignResourceName the resource name of the campaign that the new ad group will belong
* to.
* @return resource name of the newly created ad group.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addAdGroup(
GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
// Creates an ad group.
AdGroup adGroup =
AdGroup.newBuilder()
.setName("Earth to Mars Cruises #" + getPrintableDateTime())
.setCampaign(campaignResourceName)
// Sets the ad group type to TRAVEL_ADS. This cannot be set to other types.
.setType(AdGroupType.TRAVEL_ADS)
.setStatus(AdGroupStatus.ENABLED)
.build();
// Creates an ad group operation.
AdGroupOperation operation = AdGroupOperation.newBuilder().setCreate(adGroup).build();
// Issues a mutate request to add an ad group.
try (AdGroupServiceClient adGroupServiceClient =
googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
MutateAdGroupResult mutateAdGroupResult =
adGroupServiceClient
.mutateAdGroups(Long.toString(customerId), Collections.singletonList(operation))
.getResults(0);
System.out.printf(
"Added an ad group with resource name: '%s'%n", mutateAdGroupResult.getResourceName());
return mutateAdGroupResult.getResourceName();
}
}
/**
* Creates a new ad group ad in the specified ad group.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupResourceName the resource name of the ad group that the new ad group ad will
* belong to.
* @return resource name of the newly created ad group ad.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private String addAddGroupAd(
GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName) {
// Creates a new travel ad.
Ad ad = Ad.newBuilder().setTravelAd(TravelAdInfo.newBuilder()).build();
// Creates a new ad group ad and sets its ad to the travel ad.
AdGroupAd adGroupAd =
AdGroupAd.newBuilder()
// Sets the ad to the ad created above.
.setAd(ad)
// Set the ad group ad to enabled. Setting this to paused will cause an error for
// Things to do campaigns. Pausing should happen at either the ad group or campaign
// level.
.setStatus(AdGroupAdStatus.ENABLED)
// Sets the ad group.
.setAdGroup(adGroupResourceName)
.build();
// Creates an ad group ad operation.
AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
// Issues a mutate request to add an ad group ad.
try (AdGroupAdServiceClient adGroupAdServiceClient =
googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
MutateAdGroupAdResult mutateAdGroupAdResult =
adGroupAdServiceClient
.mutateAdGroupAds(Long.toString(customerId), Collections.singletonList(operation))
.getResults(0);
System.out.printf(
"Added an ad group ad with resource name: '%s'%n",
mutateAdGroupAdResult.getResourceName());
return mutateAdGroupAdResult.getResourceName();
}
}
}
С#
// Copyright 2023 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.Gax.Examples;
using Google.Ads.Gax.Util;
using Google.Ads.GoogleAds.Extensions.Config;
using Google.Ads.GoogleAds.Config;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V17.Common;
using Google.Ads.GoogleAds.V17.Errors;
using Google.Ads.GoogleAds.V17.Resources;
using Google.Ads.GoogleAds.V17.Services;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using static Google.Ads.GoogleAds.V17.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.AdGroupStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.AdGroupTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.AdvertisingChannelSubTypeEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V17.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V17.Resources.Campaign.Types;
namespace Google.Ads.GoogleAds.Examples.V17
{
/// <summary>
/// This example creates a Things to do campaign, an ad group and a Things to do ad.
/// Prerequisite: You need to have access to a Things to Do Center account. The integration
/// instructions can be found at: https://support.google.com/google-ads/answer/13387362.
/// </summary>
public class AddThingsToDoAd : ExampleBase
{
/// <summary>
/// Command line options for running the
/// <see cref="AddThingsToDoAd"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer ID.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID.")]
public long CustomerId { get; set; }
/// <summary>
/// The Things To Do Center account ID.
/// </summary>
[Option("thingsToDoCenterAccountId", Required = true, HelpText =
"The Things To Do Center account ID.")]
public long ThingsToDoCenterAccountId { get; set; }
}
/// <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)
{
Options options = ExampleUtilities.ParseCommandLine<Options>(args);
AddThingsToDoAd codeExample = new AddThingsToDoAd();
Console.WriteLine(codeExample.Description);
GoogleAdsClient client = new GoogleAdsClient();
codeExample.Run(client, options.CustomerId,
options.ThingsToDoCenterAccountId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description => "This example creates a Things to do campaign, an " +
"ad group and a Things to do ad.\n" +
"Prerequisite: You need to have access to a Things to Do Center account. The " +
"integration instructions can be found at: " +
"https://support.google.com/google-ads/answer/13387362.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="thingsToDoCenterAccountId">The Things To Do Center account ID.</param>
public void Run(GoogleAdsClient client, long customerId, long thingsToDoCenterAccountId)
{
// Creates a budget to be used by the campaign that will be created below.
string budget = CreateBudget(client, customerId);
// Creates a Things to do campaign.
string campaign = CreateThingsToDoCampaign(client, customerId, budget,
thingsToDoCenterAccountId);
// Creates an ad group.
string adGroup = CreateAdGroup(client, customerId, campaign);
// Creates an ad.
CreateAdGroupAd(client, customerId, adGroup);
}
/// <summary>
/// Creates the budget for 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>
/// <returns>The resource name of the newly created campaign budget.</returns>
private static string CreateBudget(GoogleAdsClient client, long customerId)
{
// Get the BudgetService.
CampaignBudgetServiceClient budgetService = client.GetService(
Services.V17.CampaignBudgetService);
// Create the campaign budget.
CampaignBudget budget = new CampaignBudget()
{
Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
DeliveryMethod = BudgetDeliveryMethod.Standard,
AmountMicros = 500000,
ExplicitlyShared = true
};
// Create the operation.
CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
{
Create = budget
};
// Create the campaign budget.
MutateCampaignBudgetsResponse response = budgetService.MutateCampaignBudgets(
customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });
return response.Results[0].ResourceName;
}
/// <summary>
/// Creates a new Things to do campaign in the specified customer account.
/// </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="budget">The resource name of the budget for the new campaign.</param>
/// <param name="thingsToDoCenterAccountId">The Things to Do Center account ID.</param>
/// <returns>The resource name of the newly created campaign.</returns>
private static string CreateThingsToDoCampaign(GoogleAdsClient client, long customerId,
string budget, long thingsToDoCenterAccountId)
{
// Get the CampaignService.
CampaignServiceClient campaignService = client.GetService(Services.V17.CampaignService);
// Creates a campaign.
Campaign campaign = new Campaign()
{
Name = "Interplanetary Cruise #" + ExampleUtilities.GetRandomString(),
AdvertisingChannelType = AdvertisingChannelType.Travel,
AdvertisingChannelSubType = AdvertisingChannelSubType.TravelActivities,
TravelCampaignSettings = new TravelCampaignSettings()
{
TravelAccountId = thingsToDoCenterAccountId
},
// 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 bidding strategy and budget.
MaximizeConversionValue = new MaximizeConversionValue(),
CampaignBudget = budget,
// Set the campaign network options.
NetworkSettings = new NetworkSettings
{
TargetGoogleSearch = true
}
};
MutateCampaignsResponse response = campaignService.MutateCampaigns(
customerId.ToString(), new CampaignOperation[] { new CampaignOperation() {
Create = campaign
}}
);
string campaignResourceName = response.Results[0].ResourceName;
Console.WriteLine("Campaign with resource name = '{0}' was added.", campaignResourceName);
return campaignResourceName;
}
/// <summary>
/// Creates a new ad group in the specified Things to do 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="campaign">The resource name of the campaign for the new ad group.</param>
/// <returns>The resource name of the newly created ad group.</returns>
private static string CreateAdGroup(GoogleAdsClient client, long customerId,
string campaign)
{
// Get the AdGroupService.
AdGroupServiceClient adGroupService = client.GetService(Services.V17.AdGroupService);
// Create the ad group.
AdGroup adGroup = new AdGroup()
{
Name = $"Earth to Mars Cruises #{ExampleUtilities.GetRandomString()}",
Status = AdGroupStatus.Enabled,
Campaign = campaign,
Type = AdGroupType.TravelAds
};
MutateAdGroupsResponse response = adGroupService.MutateAdGroups(
customerId.ToString(), new AdGroupOperation[] { new AdGroupOperation() {
Create = adGroup
}}
);
string adGroupResourceName = response.Results[0].ResourceName;
Console.WriteLine("Ad group with resource name = '{0}' was added.", adGroupResourceName);
return adGroupResourceName;
}
/// <summary>
/// Creates a new ad group ad in the specified ad group.
/// </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="adGroup">The resource name of the ad group for the new ad group ad.</param>
private static void CreateAdGroupAd(GoogleAdsClient client, long customerId,
string adGroup)
{
// Get the AdGroupAdService.
AdGroupAdServiceClient adGroupAdService =
client.GetService(Services.V17.AdGroupAdService);
// Creates a new ad group ad and sets a travel ad info.
AdGroupAd adGroupAd = new AdGroupAd()
{
Ad = new Ad()
{
TravelAd = new TravelAdInfo()
},
// Set the ad group ad to enabled. Setting this to paused will cause an error for
// Things to do campaigns. Pausing should happen at either the ad group or campaign
// level.
Status = AdGroupAdStatus.Enabled,
AdGroup = adGroup
};
MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
customerId.ToString(), new AdGroupAdOperation[] { new AdGroupAdOperation() {
Create = adGroupAd
}}
);
string adGroupAdResourceName = response.Results[0].ResourceName;
Console.WriteLine("Ad group ad with resource name = '{0}' was added.",
adGroupAdResourceName);
}
}
}
PHP
<?php
/**
* Copyright 2023 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\Travel;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V17\GoogleAdsException;
use Google\Ads\GoogleAds\V17\Common\MaximizeConversionValue;
use Google\Ads\GoogleAds\V17\Common\TravelAdInfo;
use Google\Ads\GoogleAds\V17\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V17\Enums\AdGroupStatusEnum\AdGroupStatus;
use Google\Ads\GoogleAds\V17\Enums\AdGroupTypeEnum\AdGroupType;
use Google\Ads\GoogleAds\V17\Enums\AdvertisingChannelSubTypeEnum\AdvertisingChannelSubType;
use Google\Ads\GoogleAds\V17\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V17\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V17\Enums\CampaignStatusEnum\CampaignStatus;
use Google\Ads\GoogleAds\V17\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V17\Resources\Ad;
use Google\Ads\GoogleAds\V17\Resources\AdGroup;
use Google\Ads\GoogleAds\V17\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V17\Resources\Campaign;
use Google\Ads\GoogleAds\V17\Resources\Campaign\NetworkSettings;
use Google\Ads\GoogleAds\V17\Resources\Campaign\TravelCampaignSettings;
use Google\Ads\GoogleAds\V17\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V17\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V17\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V17\Services\CampaignOperation;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupAdsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateAdGroupsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignBudgetsRequest;
use Google\Ads\GoogleAds\V17\Services\MutateCampaignsRequest;
use Google\ApiCore\ApiException;
/**
* This example creates a Things to do campaign, an ad group and a Things to do ad.
*
* <p> Prerequisite: You need to have an access to the Things to Do Center. The integration
* instructions can be found at: https://support.google.com/google-ads/answer/13387362.
*/
class AddThingsToDoAd
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
// Specify your Things to Do Center account ID below.
private const THINGS_TO_DO_CENTER_ACCOUNT_ID = 'INSERT_THINGS_TO_DO_CENTER_ACCOUNT_ID_HERE';
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::THINGS_TO_DO_CENTER_ACCOUNT_ID => GetOpt::REQUIRED_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::THINGS_TO_DO_CENTER_ACCOUNT_ID]
?: self::THINGS_TO_DO_CENTER_ACCOUNT_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
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $thingsToDoCenterAccountId the Things to Do Center account ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $thingsToDoCenterAccountId
) {
// Creates a budget to be used by the campaign that will be created below.
$budgetResourceName = self::addCampaignBudget($googleAdsClient, $customerId);
// Creates a Things to do campaign.
$campaignResourceName = self::addThingsToDoCampaign(
$googleAdsClient,
$customerId,
$budgetResourceName,
$thingsToDoCenterAccountId
);
// Creates an ad group.
$adGroupResourceName =
self::addAdGroup($googleAdsClient, $customerId, $campaignResourceName);
// Creates an ad group ad.
self::addAdGroupAd($googleAdsClient, $customerId, $adGroupResourceName);
}
/**
* Creates a new campaign budget in the specified customer account.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @return string the resource name of the newly created budget
*/
private static function addCampaignBudget(GoogleAdsClient $googleAdsClient, int $customerId)
{
// Creates a campaign budget.
$budget = new CampaignBudget([
'name' => 'Interplanetary Cruise Budget #' . Helper::getPrintableDatetime(),
'delivery_method' => BudgetDeliveryMethod::STANDARD,
// Sets the amount of budget.
'amount_micros' => 50000000,
// Makes the budget explicitly shared. You cannot set it to `false` for Things to do
// campaigns.
'explicitly_shared' => true
]);
// Creates a campaign budget operation.
$campaignBudgetOperation = new CampaignBudgetOperation();
$campaignBudgetOperation->setCreate($budget);
// Issues a mutate request.
$campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
$response = $campaignBudgetServiceClient->mutateCampaignBudgets(
MutateCampaignBudgetsRequest::build($customerId, [$campaignBudgetOperation])
);
/** @var CampaignBudget $addedBudget */
$addedBudget = $response->getResults()[0];
printf(
"Added a budget with resource name '%s'.%s",
$addedBudget->getResourceName(),
PHP_EOL
);
return $addedBudget->getResourceName();
}
/**
* Creates a new Things to do campaign in the specified customer account.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param string $budgetResourceName the resource name of budget for a new campaign
* @param int $thingsToDoCenterAccountId the Things to Do Center account ID
* @return string the resource name of the newly created campaign
*/
private static function addThingsToDoCampaign(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $budgetResourceName,
int $thingsToDoCenterAccountId
) {
// Creates a campaign.
$campaign = new Campaign([
'name' => 'Interplanetary Cruise Campaign #' . Helper::getPrintableDatetime(),
// Configures settings related to Things to do campaigns including advertising channel
// type, advertising channel sub type and travel campaign settings.
'advertising_channel_type' => AdvertisingChannelType::TRAVEL,
'advertising_channel_sub_type' => AdvertisingChannelSubType::TRAVEL_ACTIVITIES,
'travel_campaign_settings'
=> new TravelCampaignSettings(['travel_account_id' => $thingsToDoCenterAccountId]),
// 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,
// Sets the bidding strategy to MaximizeConversionValue. Only this type can be used
// for Things to do campaigns.
'maximize_conversion_value' => new MaximizeConversionValue(),
// Sets the budget.
'campaign_budget' => $budgetResourceName,
// Configures the campaign network options. Only Google Search is allowed for
// Things to do campaigns.
'network_settings' => new NetworkSettings(['target_google_search' => true])
]);
// Creates a campaign operation.
$campaignOperation = new CampaignOperation();
$campaignOperation->setCreate($campaign);
// Issues a mutate request to add campaigns.
$campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
$response = $campaignServiceClient->mutateCampaigns(
MutateCampaignsRequest::build($customerId, [$campaignOperation])
);
/** @var Campaign $addedCampaign */
$addedCampaign = $response->getResults()[0];
printf(
"Added a Things to do campaign with resource name '%s'.%s",
$addedCampaign->getResourceName(),
PHP_EOL
);
return $addedCampaign->getResourceName();
}
/**
* Creates a new ad group in the specified Things to do campaign.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param string $campaignResourceName the resource name of campaign that a new ad group will
* belong to
* @return string the resource name of the newly created ad group
*/
private static function addAdGroup(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $campaignResourceName
) {
// Creates an ad group.
$adGroup = new AdGroup([
'name' => 'Earth to Mars Cruise #' . Helper::getPrintableDatetime(),
// Sets the campaign.
'campaign' => $campaignResourceName,
// Sets the ad group type to TRAVEL_ADS. This cannot be set to other types.
'type' => AdGroupType::TRAVEL_ADS,
'status' => AdGroupStatus::ENABLED,
]);
// Creates an ad group operation.
$adGroupOperation = new AdGroupOperation();
$adGroupOperation->setCreate($adGroup);
// Issues a mutate request to add an ad group.
$adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
$response = $adGroupServiceClient->mutateAdGroups(
MutateAdGroupsRequest::build($customerId, [$adGroupOperation])
);
/** @var AdGroup $addedAdGroup */
$addedAdGroup = $response->getResults()[0];
printf(
"Added an ad group with resource name '%s'.%s",
$addedAdGroup->getResourceName(),
PHP_EOL
);
return $addedAdGroup->getResourceName();
}
/**
* Creates a new ad group ad in the specified ad group.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param string $adGroupResourceName the resource name of ad group that a new ad group ad will
* belong to
*/
private static function addAdGroupAd(
GoogleAdsClient $googleAdsClient,
int $customerId,
string $adGroupResourceName
) {
// Creates a new ad group ad and sets a travel ad info.
$adGroupAd = new AdGroupAd([
'ad' => new Ad(['travel_ad' => new TravelAdInfo()]),
// Set the ad group ad to enabled. Setting this to paused will cause an error for Things
// to do campaigns. Pausing should happen at either the ad group or campaign level.
'status' => AdGroupAdStatus::ENABLED,
// Sets the ad group.
'ad_group' => $adGroupResourceName
]);
// Creates an ad group ad operation.
$adGroupAdOperation = new AdGroupAdOperation();
$adGroupAdOperation->setCreate($adGroupAd);
// Issues a mutate request to add an ad group ad.
$adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
$response = $adGroupAdServiceClient->mutateAdGroupAds(
MutateAdGroupAdsRequest::build($customerId, [$adGroupAdOperation])
);
/** @var AdGroupAd $addedAdGroupAd */
$addedAdGroupAd = $response->getResults()[0];
printf(
"Added an ad group ad with resource name '%s'.%s",
$addedAdGroupAd->getResourceName(),
PHP_EOL
);
}
}
AddThingsToDoAd::main();
Питон
#!/usr/bin/env python
# Copyright 2023 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 creates a Things to do campaign, ad group, and ad.
Prerequisite: You need to have an access to the Things to Do Center. The
integration instructions can be found at:
https://support.google.com/google-ads/answer/13387362
"""
import argparse
import sys
from examples.utils.example_helpers import get_printable_datetime
from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException
def main(client, customer_id, things_to_do_center_account_id):
"""The main method that creates all necessary entities for the example.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
things_to_do_center_account_id: the Things to Do Center account ID.
"""
# Creates a budget to be used by the campaign that will be created below.
budget_resource_name = add_campaign_budget(client, customer_id)
# Creates a Things to do campaign.
campaign_resource_name = add_things_to_do_campaign(
client,
customer_id,
budget_resource_name,
things_to_do_center_account_id,
)
# Creates an ad group.
ad_group_resource_name = add_ad_group(
client, customer_id, campaign_resource_name
)
# Creates an ad group ad.
add_ad_group_ad(client, customer_id, ad_group_resource_name)
def add_campaign_budget(client, customer_id):
"""Creates a new campaign budget in the specified customer account.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
Returns:
The resource name of the newly created budget.
"""
# Creates a campaign budget operation.
operation = client.get_type("CampaignBudgetOperation")
# Creates a campaign budget.
campaign_budget = operation.create
campaign_budget.name = (
f"Interplanetary Cruise Budget #{get_printable_datetime()}"
)
campaign_budget.delivery_method = (
client.enums.BudgetDeliveryMethodEnum.STANDARD
)
# Sets the amount of budget.
campaign_budget.amount_micros = 50000000
# Makes the budget explicitly shared. This cannot be set to false for a
# Things to do campaign.
campaign_budget.explicitly_shared = True
# Issues a mutate request.
campaign_budget_service = client.get_service("CampaignBudgetService")
response = campaign_budget_service.mutate_campaign_budgets(
customer_id=customer_id, operations=[operation]
)
resource_name = response.results[0].resource_name
print(f"Added a budget with resource name: '{resource_name}'.")
return resource_name
def add_things_to_do_campaign(
client, customer_id, budget_resource_name, things_to_do_center_account_id
):
"""Creates a new Things to do campaign in the specified customer account.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
budget_resource_name: the resource name of a budget for a new campaign.
things_to_do_center_account_id: the Things to Do Center account ID.
Returns:
The resource name of the newly created campaign.
"""
# Creates a campaign operation.
operation = client.get_type("CampaignOperation")
# Creates a campaign.
campaign = operation.create
campaign.name = (
f"Interplanetary Cruise Campaign #{get_printable_datetime()}"
)
# Configures settings related to Things to do campaigns including
# advertising channel type, advertising channel sub type and travel
# campaign settings.
campaign.advertising_channel_type = (
client.enums.AdvertisingChannelTypeEnum.TRAVEL
)
campaign.advertising_channel_sub_type = (
client.enums.AdvertisingChannelSubTypeEnum.TRAVEL_ACTIVITIES
)
campaign.travel_campaign_settings.travel_account_id = (
things_to_do_center_account_id
)
# Recommendation: Set the campaign to PAUSED when creating it to prevent
# the ads from immediately serving. Set to ENABLED once you've added
# targeting and the ads are ready to serve.
campaign.status = client.enums.CampaignStatusEnum.PAUSED
# Sets the bidding strategy to MaximizeConversionValue. Only this type can
# be used for Things to do campaigns.
campaign.maximize_conversion_value = client.get_type(
"MaximizeConversionValue"
)
# Sets the budget.
campaign.campaign_budget = budget_resource_name
# Configures the campaign network options. Only Google Search is allowed for
# Things to do campaigns.
campaign.network_settings.target_google_search = True
# Issues a mutate request to add campaigns.
campaign_service = client.get_service("CampaignService")
response = campaign_service.mutate_campaigns(
customer_id=customer_id, operations=[operation]
)
resource_name = response.results[0].resource_name
print(
f"Added a Things to do campaign with resource name: '{resource_name}'."
)
return resource_name
def add_ad_group(client, customer_id, campaign_resource_name):
"""Creates a new ad group in the specified Things to do campaign.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
campaign_resource_name: the resource name of campaign that a new ad
group will belong to.
Returns:
The resource name of the newly created ad group.
"""
# Creates an ad group operation.
operation = client.get_type("AdGroupOperation")
# Creates an ad group.
ad_group = operation.create
ad_group.name = f"Earth to Mars cruise #{get_printable_datetime()}"
# Sets the campaign.
ad_group.campaign = campaign_resource_name
# Sets the ad group type to TRAVEL_ADS. This is the only value allowed
# for this field on an ad group for a Things to do campaign.
ad_group.type_ = client.enums.AdGroupTypeEnum.TRAVEL_ADS
ad_group.status = client.enums.AdGroupStatusEnum.ENABLED
# Issues a mutate request to add an ad group.
ad_group_service = client.get_service("AdGroupService")
ad_group_response = ad_group_service.mutate_ad_groups(
customer_id=customer_id, operations=[operation]
)
resource_name = ad_group_response.results[0].resource_name
print(f"Added an ad group with resource name: '{resource_name}'.")
return resource_name
def add_ad_group_ad(client, customer_id, ad_group_resource_name):
"""Creates a new ad group ad in the specified ad group.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
ad_group_resource_name: the resource name of ad group that a new ad
group ad will belong to.
"""
# Creates an ad group ad operation.
operation = client.get_type("AdGroupAdOperation")
# Creates a new ad group ad and sets a travel ad info.
ad_group_ad = operation.create
# Sets the ad group ad to enabled. Setting this to paused will cause an error
# for Things to do campaigns. Pausing should happen at either the ad group
# or campaign level.
ad_group_ad.status = client.enums.AdGroupAdStatusEnum.ENABLED
ad_group_ad.ad.travel_ad = client.get_type("TravelAdInfo")
# Sets the ad group.
ad_group_ad.ad_group = ad_group_resource_name
# Issues a mutate request to add an ad group ad.
ad_group_ad_service = client.get_service("AdGroupAdService")
response = ad_group_ad_service.mutate_ad_group_ads(
customer_id=customer_id, operations=[operation]
)
resource_name = response.results[0].resource_name
print(f"Added an ad group ad with resource name: '{resource_name}'.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description=(
"Adds a Things to do campaign, ad group, and a Things to do ad."
)
)
# 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.",
)
parser.add_argument(
"-t",
"--things_to_do_center_account_id",
type=int,
required=True,
help=("The Things to Do Center account ID."),
)
args = parser.parse_args()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client = GoogleAdsClient.load_from_storage(version="v17")
try:
main(
googleads_client,
args.customer_id,
args.things_to_do_center_account_id,
)
except GoogleAdsException as ex:
print(
f'Request with ID "{ex.request_id}" failed with status '
f'"{ex.error.code().name}" and includes the following errors:'
)
for error in ex.failure.errors:
print(f'\tError with message "{error.message}".')
if error.location:
for field_path_element in error.location.field_path_elements:
print(f"\t\tOn field: {field_path_element.field_name}")
sys.exit(1)
Руби
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright 2023 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 creates a Things to Do campaign, an ad group and a Things to Do
# ad.
#
# Prerequisite: You need to have an access to the Things to Do Center. The
# integration instructions can be found at:
# https://support.google.com/google-ads/answer/13387362
require 'optparse'
require 'google/ads/google_ads'
require 'date'
def add_things_to_do_ad(customer_id, things_to_do_center_account_id)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client = Google::Ads::GoogleAds::GoogleAdsClient.new
# Creates a budget to be used by the campaign that will be created below.
budget_resource = add_campaign_budget(client, customer_id)
# Creates a Things to Do campaign.
campaign_resource = add_things_to_do_campaign(client, customer_id,
budget_resource, things_to_do_center_account_id)
# Create an ad group.
ad_group_resource = add_ad_group(client, customer_id, campaign_resource)
# Create an ad group ad.
add_ad_group_ad(client, customer_id, ad_group_resource)
end
# Creates a new campaign budget in the specified client account.
def add_campaign_budget(client, customer_id)
# Create the budget and set relevant fields.
campaign_budget_operation = client.operation.create_resource.campaign_budget do |cb|
cb.name = generate_random_name_field("Interplanetary Cruise Budget")
cb.delivery_method = :STANDARD
cb.amount_micros = 50_000_000
# Makes the budget explicitly shared. You cannot set it to `false` for
# Things to Do campaigns.
cb.explicitly_shared = true
end
# Issue a mutate request.
campaign_budget_service = client.service.campaign_budget
response = campaign_budget_service.mutate_campaign_budgets(
customer_id: customer_id,
operations: [campaign_budget_operation],
)
# Fetch the new budget's resource name.
budget_resource = response.results.first.resource_name
puts "Added budget with resource name '#{budget_resource}'."
budget_resource
end
# Creates a new Things to Do campaign in the specified customer account.
def add_things_to_do_campaign(client, customer_id, budget_resource,
things_to_do_center_account_id)
# Create a campaign.
campaign_operation = client.operation.create_resource.campaign do |c|
c.name = generate_random_name_field("Interplanetary Cruise Campaign")
# Configures settings related to Things to Do campaigns including
# advertising channel type, advertising channel sub type and
# travel campaign settings.
c.advertising_channel_type = :TRAVEL
c.advertising_channel_sub_type = :TRAVEL_ACTIVITIES
c.travel_campaign_settings = client.resource.travel_campaign_settings do |tcs|
tcs.travel_account_id = things_to_do_center_account_id
end
# 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.
c.status = :PAUSED
# Sets the bidding strategy to MaximizeConversionValue. Only this type can
# be used for Things to Do campaigns.
c.maximize_conversion_value = client.resource.maximize_conversion_value
# Set the budget.
c.campaign_budget = budget_resource
# Configures the campaign network options. Only Google Search is allowed for
# Things to Do campaigns.
c.network_settings = client.resource.network_settings do |ns|
ns.target_google_search = true
end
end
# Issue a mutate request to add the campaign.
campaign_service = client.service.campaign
response = campaign_service.mutate_campaigns(
customer_id: customer_id,
operations: [campaign_operation],
)
# Fetch the new campaign's resource name.
campaign_resource = response.results.first.resource_name
puts "Added Things To Do campaign with resource name '#{campaign_resource}'."
campaign_resource
end
# Creates a new ad group in the specified Things to Do campaign.
def add_ad_group(client, customer_id, campaign_resource)
# Create an ad group.
ad_group_operation = client.operation.create_resource.ad_group do |ag|
ag.name = generate_random_name_field("Earth to Mars Cruise")
# Set the campaign.
ag.campaign = campaign_resource
# Set the ad group type to TRAVEL_ADS.
# This cannot be set to other types.
ag.type = :TRAVEL_ADS
ag.status = :ENABLED
end
# Issue a mutate request to add the ad group.
ad_group_service = client.service.ad_group
response = ad_group_service.mutate_ad_groups(
customer_id: customer_id,
operations: [ad_group_operation]
)
# Fetch the new ad group's resource name.
ad_group_resource = response.results.first.resource_name
puts "Added an ad group with resource name '#{ad_group_resource}'."
ad_group_resource
end
# Creates a new ad group ad in the specified ad group
def add_ad_group_ad(client, customer_id, ad_group_resource)
# Creates a new ad group ad and sets a travel ad info.
ad_group_ad_operation = client.operation.create_resource.ad_group_ad do |aga|
aga.ad = client.resource.ad do |ad|
ad.travel_ad = client.resource.travel_ad_info
end
# Set the ad group ad to enabled. Setting this to paused will cause an error
# for Things to Do campaigns. Pausing should happen at either the ad group
# or campaign level.
aga.status = :ENABLED
# Set the ad group.
aga.ad_group = ad_group_resource
end
# Issue a mutate request to add the ad group ad.
ad_group_ad_service = client.service.ad_group_ad
response = ad_group_ad_service.mutate_ad_group_ads(
customer_id: customer_id,
operations: [ad_group_ad_operation],
)
# Fetch the new ad group ad's resource name.
ad_group_ad_resource = response.results.first.resource_name
puts "Added an ad group ad with resource name '#{ad_group_ad_resource}'."
end
# Appends a random number to the provided description text and returns it as a
# string-wrapped value
def generate_random_name_field(text)
"#{text} ##{(Time.new.to_f * 100).to_i}"
end
if __FILE__ == $0
options = {}
OptionParser.new do |opts|
opts.banner = sprintf('Usage: %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.on('-T', '--things-to-do-center-account-id THINGS-TO-DO-CENTER-ACCOUNT-ID',
Integer, 'Things to Do Account ID') do |v|
options[:things_to_do_center_account_id] = v
end
opts.separator ''
opts.separator 'Help:'
opts.on_tail('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
begin
add_things_to_do_ad(options.fetch(:customer_id).tr("-", ""), options.fetch(:things_to_do_center_account_id))
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
raise
end
end
Перл
#!/usr/bin/perl -w
#
# Copyright 2023, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example creates a Things to do campaign, an ad group and a Things to
# do ad.
#
# Prerequisite: You need to have access to the Things to do Center.
# The integration instructions can be found at:
# https://support.google.com/google-ads/answer/13387362
use strict;
use warnings;
use utf8;
use FindBin qw($Bin);
use lib "$Bin/../../lib";
use Google::Ads::GoogleAds::Client;
use Google::Ads::GoogleAds::Utils::GoogleAdsHelper;
use Google::Ads::GoogleAds::V17::Resources::CampaignBudget;
use Google::Ads::GoogleAds::V17::Resources::Campaign;
use Google::Ads::GoogleAds::V17::Resources::NetworkSettings;
use Google::Ads::GoogleAds::V17::Resources::AdGroup;
use Google::Ads::GoogleAds::V17::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V17::Resources::Ad;
use Google::Ads::GoogleAds::V17::Resources::TravelCampaignSettings;
use Google::Ads::GoogleAds::V17::Common::MaximizeConversionValue;
use Google::Ads::GoogleAds::V17::Common::TravelAdInfo;
use Google::Ads::GoogleAds::V17::Enums::BudgetDeliveryMethodEnum qw(STANDARD);
use Google::Ads::GoogleAds::V17::Enums::CampaignStatusEnum;
use Google::Ads::GoogleAds::V17::Enums::AdGroupTypeEnum qw(TRAVEL_ADS);
use Google::Ads::GoogleAds::V17::Enums::AdGroupStatusEnum;
use Google::Ads::GoogleAds::V17::Enums::AdGroupAdStatusEnum;
use Google::Ads::GoogleAds::V17::Enums::AdvertisingChannelTypeEnum qw(TRAVEL);
use Google::Ads::GoogleAds::V17::Enums::AdvertisingChannelSubTypeEnum
qw(TRAVEL_ACTIVITIES);
use
Google::Ads::GoogleAds::V17::Services::CampaignBudgetService::CampaignBudgetOperation;
use Google::Ads::GoogleAds::V17::Services::CampaignService::CampaignOperation;
use Google::Ads::GoogleAds::V17::Services::AdGroupService::AdGroupOperation;
use Google::Ads::GoogleAds::V17::Services::AdGroupAdService::AdGroupAdOperation;
use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);
sub add_things_to_do_ad {
my ($api_client, $customer_id, $things_to_do_center_account_id) = @_;
# Create a budget to be used by the campaign that will be created below.
my $budget_resource_name = add_campaign_budget($api_client, $customer_id);
# Create a Things to do campaign.
my $campaign_resource_name =
add_things_to_do_campaign($api_client, $customer_id,
$budget_resource_name, $things_to_do_center_account_id);
# Create an ad group.
my $ad_group_resource_name =
add_ad_group($api_client, $customer_id, $campaign_resource_name);
# Create an ad group ad.
add_ad_group_ad($api_client, $customer_id, $ad_group_resource_name);
return 1;
}
# Creates a new campaign budget in the specified client account.
sub add_campaign_budget {
my ($api_client, $customer_id) = @_;
# Create a campaign budget.
my $campaign_budget =
Google::Ads::GoogleAds::V17::Resources::CampaignBudget->new({
name => "Interplanetary Cruise Budget #" . uniqid(),
deliveryMethod => STANDARD,
# Set the amount of budget.
amountMicros => 5000000,
# Make the budget explicitly shared.
explicitlyShared => "true"
});
# Create a campaign budget operation.
my $campaign_budget_operation =
Google::Ads::GoogleAds::V17::Services::CampaignBudgetService::CampaignBudgetOperation
->new({create => $campaign_budget});
# Add the campaign budget.
my $campaign_budget_resource_name =
$api_client->CampaignBudgetService()->mutate({
customerId => $customer_id,
operations => [$campaign_budget_operation]})->{results}[0]{resourceName};
printf "Added a budget with resource name: '%s'.\n",
$campaign_budget_resource_name;
return $campaign_budget_resource_name;
}
# Creates a new Things to do campaign in the specified client account.
sub add_things_to_do_campaign {
my ($api_client, $customer_id, $budget_resource_name,
$things_to_do_center_account_id)
= @_;
# Create a campaign.
my $campaign = Google::Ads::GoogleAds::V17::Resources::Campaign->new({
name => "Interplanetary Cruise Campaign #" . uniqid(),
# Configure settings related to Things to do campaigns including
# advertising channel type, advertising channel sub type and travel
# campaign settings.
advertisingChannelType => TRAVEL,
advertisingChannelSubType => TRAVEL_ACTIVITIES,
travelCampaignSettings =>
Google::Ads::GoogleAds::V17::Resources::TravelCampaignSettings->new({
travelAccountId => $things_to_do_center_account_id
}
),
# 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 => Google::Ads::GoogleAds::V17::Enums::CampaignStatusEnum::PAUSED,
# Set the bidding strategy to MaximizeConversionValue. Only this type can be
# used for Things to do campaigns.
maximizeConversionValue =>
Google::Ads::GoogleAds::V17::Common::MaximizeConversionValue->new(),
# Set the budget.
campaignBudget => $budget_resource_name,
# Configure the campaign network options. Only Google Search is allowed for
# Things to do campaigns.
networkSettings =>
Google::Ads::GoogleAds::V17::Resources::NetworkSettings->new({
targetGoogleSearch => "true"
})});
# Create a campaign operation.
my $campaign_operation =
Google::Ads::GoogleAds::V17::Services::CampaignService::CampaignOperation->
new({create => $campaign});
# Add the campaign.
my $campaign_resource_name = $api_client->CampaignService()->mutate({
customerId => $customer_id,
operations => [$campaign_operation]})->{results}[0]{resourceName};
printf "Added a Things to do campaign with resource name: '%s'.\n",
$campaign_resource_name;
return $campaign_resource_name;
}
# Creates a new ad group in the specified Things to do campaign.
sub add_ad_group {
my ($api_client, $customer_id, $campaign_resource_name) = @_;
# Create an ad group.
my $ad_group = Google::Ads::GoogleAds::V17::Resources::AdGroup->new({
name => "Earth to Mars Cruise #" . uniqid(),
# Set the campaign.
campaign => $campaign_resource_name,
# Set the ad group type to TRAVEL_ADS.
# This cannot be set to other types.
type => TRAVEL_ADS,
status => Google::Ads::GoogleAds::V17::Enums::AdGroupStatusEnum::ENABLED
});
# Create an ad group operation.
my $ad_group_operation =
Google::Ads::GoogleAds::V17::Services::AdGroupService::AdGroupOperation->
new({create => $ad_group});
# Add the ad group.
my $ad_group_resource_name = $api_client->AdGroupService()->mutate({
customerId => $customer_id,
operations => [$ad_group_operation]})->{results}[0]{resourceName};
printf "Added an ad group with resource name: '%s'.\n",
$ad_group_resource_name;
return $ad_group_resource_name;
}
# Creates a new ad group ad in the specified ad group.
sub add_ad_group_ad {
my ($api_client, $customer_id, $ad_group_resource_name) = @_;
# Create an ad group ad and set a travel ad info.
my $ad_group_ad = Google::Ads::GoogleAds::V17::Resources::AdGroupAd->new({
# Set the ad group.
adGroup => $ad_group_resource_name,
ad => Google::Ads::GoogleAds::V17::Resources::Ad->new({
travelAd => Google::Ads::GoogleAds::V17::Common::TravelAdInfo->new()}
),
# Set the ad group to enabled. Setting this to paused will cause an error
# for Things to do campaigns. Pausing should happen at either the ad group
# or campaign level.
status => Google::Ads::GoogleAds::V17::Enums::AdGroupAdStatusEnum::ENABLED
});
# Create an ad group ad operation.
my $ad_group_ad_operation =
Google::Ads::GoogleAds::V17::Services::AdGroupAdService::AdGroupAdOperation
->new({create => $ad_group_ad});
# Add the ad group ad.
my $ad_group_ad_resource_name = $api_client->AdGroupAdService()->mutate({
customerId => $customer_id,
operations => [$ad_group_ad_operation]})->{results}[0]{resourceName};
printf "Added an ad group ad with resource name: '%s'.\n",
$ad_group_ad_resource_name;
return $ad_group_ad_resource_name;
}
# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
return 1;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();
# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);
my $customer_id = undef;
my $things_to_do_center_account_id = undef;
# Parameters passed on the command line will override any parameters set in code.
GetOptions(
"customer_id=s" => \$customer_id,
"things_to_do_center_account_id=i" => \$things_to_do_center_account_id
);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2)
if not check_params($customer_id, $things_to_do_center_account_id);
# Call the example.
add_things_to_do_ad(
$api_client,
$customer_id =~ s/-//gr,
$things_to_do_center_account_id
);
=pod
=head1 NAME
add_things_to_do_ad
=head1 DESCRIPTION
This example creates a Things to do campaign, an ad group and a Things to do ad.
Prerequisite: You need to have an access to the Things to Do Center. The integration
instructions can be found at: https://support.google.com/google-ads/answer/13387362.
=head1 SYNOPSIS
add_things_to_do_ad.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-things_to_do_center_account_id The Things to Do Center account ID.
=cut