Java
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.extensions; 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.v13.common.AdScheduleInfo; import com.google.ads.googleads.v13.common.KeywordInfo; import com.google.ads.googleads.v13.common.SitelinkFeedItem; import com.google.ads.googleads.v13.enums.DayOfWeekEnum.DayOfWeek; import com.google.ads.googleads.v13.enums.ExtensionTypeEnum.ExtensionType; import com.google.ads.googleads.v13.enums.FeedItemTargetDeviceEnum.FeedItemTargetDevice; import com.google.ads.googleads.v13.enums.KeywordMatchTypeEnum.KeywordMatchType; import com.google.ads.googleads.v13.enums.MinuteOfHourEnum.MinuteOfHour; import com.google.ads.googleads.v13.errors.GoogleAdsError; import com.google.ads.googleads.v13.errors.GoogleAdsException; import com.google.ads.googleads.v13.resources.CampaignExtensionSetting; import com.google.ads.googleads.v13.resources.ExtensionFeedItem; import com.google.ads.googleads.v13.services.CampaignExtensionSettingOperation; import com.google.ads.googleads.v13.services.CampaignExtensionSettingServiceClient; import com.google.ads.googleads.v13.services.ExtensionFeedItemOperation; import com.google.ads.googleads.v13.services.ExtensionFeedItemServiceClient; import com.google.ads.googleads.v13.services.MutateCampaignExtensionSettingResult; import com.google.ads.googleads.v13.services.MutateCampaignExtensionSettingsResponse; import com.google.ads.googleads.v13.services.MutateExtensionFeedItemResult; import com.google.ads.googleads.v13.services.MutateExtensionFeedItemsResponse; import com.google.ads.googleads.v13.utils.ResourceNames; import com.google.common.collect.ImmutableList; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; /** Adds sitelinks to a campaign. To create a campaign, run AddCampaigns.java. */ // DEPRECATION WARNING! // THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION // All extensions should migrate to Assets. See AddSitelinksUsingAssets.java @Deprecated public class AddSitelinks { private static class AddSitelinksParams extends CodeSampleParams { @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true) private Long customerId; @Parameter(names = ArgumentNames.CAMPAIGN_ID, required = true) private Long campaignId; } public static void main(String[] args) throws IOException { AddSitelinksParams params = new AddSitelinksParams(); 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.campaignId = Long.parseLong("INSERT_CAMPAIGN_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 AddSitelinks().runExample(googleAdsClient, params.customerId, params.campaignId); } 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 campaignId the campaign ID. * @throws GoogleAdsException if an API request failed with one or more service errors. */ private void runExample(GoogleAdsClient googleAdsClient, long customerId, long campaignId) { String campaignResourceName = ResourceNames.campaign(customerId, campaignId); List<String> extensionFeedItems = createExtensionFeedItems(googleAdsClient, customerId, campaignResourceName); // Creates a CampaignExtensionSetting. CampaignExtensionSetting campaignExtensionSetting = CampaignExtensionSetting.newBuilder() .setCampaign(campaignResourceName) .setExtensionType(ExtensionType.SITELINK) .addAllExtensionFeedItems(extensionFeedItems) .build(); // Creates the operation. CampaignExtensionSettingOperation operation = CampaignExtensionSettingOperation.newBuilder().setCreate(campaignExtensionSetting).build(); // Creates the CampaignExtensionSettingServiceClient. try (CampaignExtensionSettingServiceClient campaignExtensionSettingServiceClient = googleAdsClient.getLatestVersion().createCampaignExtensionSettingServiceClient()) { // Adds the CampaignExtensionSettingServiceClient. MutateCampaignExtensionSettingsResponse response = campaignExtensionSettingServiceClient.mutateCampaignExtensionSettings( Long.toString(customerId), ImmutableList.of(operation)); for (MutateCampaignExtensionSettingResult result : response.getResultsList()) { System.out.printf( "Created CampaignExtensionSetting with resource name '%s'.%n", result.getResourceName()); } } } /** * Creates a list of ExtensionFeedItems. * * @param googleAdsClient the Google Ads API client. * @param customerId the client customer ID. * @param campaignResourceName the resource name of the campaign to target. */ private static List<String> createExtensionFeedItems( GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) { SitelinkFeedItem sitelinkFeedItem1 = createSitelinkFeedItem("Store Hours", "http://www.example.com/storehours"); // Creates an ExtensionFeedItem from the SitelinkFeedItem. ExtensionFeedItem extensionFeedItem1 = ExtensionFeedItem.newBuilder() .setExtensionType(ExtensionType.SITELINK) .setSitelinkFeedItem(sitelinkFeedItem1) .setTargetedCampaign(campaignResourceName) .build(); List<ExtensionFeedItemOperation> operations = new ArrayList<>(); // Creates an ExtensionFeedItemOperation and adds it to the operations List. operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem1).build()); SitelinkFeedItem sitelinkFeedItem2 = createSitelinkFeedItem("Thanksgiving Specials", "http://www.example.com/thanksgiving"); DateTime startTime = new DateTime(DateTime.now().getYear(), 11, 20, 0, 0, 0); if (startTime.isBeforeNow()) { // Move the startTime to next year if the current date is past November 20th. startTime = startTime.plusYears(1); } // Converts to a string in the required format. String startTimeString = startTime.toString("yyyy-MM-dd hh:mm:ss"); // Use the same year as startTime when creating endTime. DateTime endTime = new DateTime(startTime.getYear(), 11, 27, 23, 59, 59); String endTimeString = endTime.toString("yyyy-MM-dd hh:mm:ss"); // Targets this sitelink for United States only. // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets String unitedStates = ResourceNames.geoTargetConstant(2840); ExtensionFeedItem extensionFeedItem2 = ExtensionFeedItem.newBuilder() .setExtensionType(ExtensionType.SITELINK) .setSitelinkFeedItem(sitelinkFeedItem2) .setTargetedCampaign(campaignResourceName) .setStartDateTime(startTimeString) .setEndDateTime(endTimeString) .setTargetedGeoTargetConstant(unitedStates) .build(); operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem2).build()); SitelinkFeedItem sitelinkFeedItem3 = createSitelinkFeedItem("Wifi available", "http://www.example.com/mobile/wifi"); ExtensionFeedItem extensionFeedItem3 = ExtensionFeedItem.newBuilder() .setExtensionType(ExtensionType.SITELINK) .setSitelinkFeedItem(sitelinkFeedItem3) .setTargetedCampaign(campaignResourceName) .setDevice(FeedItemTargetDevice.MOBILE) .setTargetedKeyword( KeywordInfo.newBuilder() .setText("free wifi") .setMatchType(KeywordMatchType.BROAD) .build()) .build(); operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem3).build()); SitelinkFeedItem sitelinkFeedItem4 = createSitelinkFeedItem("Happy hours", "http://www.example.com/happyhours"); ExtensionFeedItem extensionFeedItem4 = ExtensionFeedItem.newBuilder() .setExtensionType(ExtensionType.SITELINK) .setSitelinkFeedItem(sitelinkFeedItem4) .setTargetedCampaign(campaignResourceName) .addAdSchedules( createAdScheduleInfo( DayOfWeek.MONDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO)) .addAdSchedules( createAdScheduleInfo( DayOfWeek.TUESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO)) .addAdSchedules( createAdScheduleInfo( DayOfWeek.WEDNESDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO)) .addAdSchedules( createAdScheduleInfo( DayOfWeek.THURSDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO)) .addAdSchedules( createAdScheduleInfo( DayOfWeek.FRIDAY, 18, MinuteOfHour.ZERO, 21, MinuteOfHour.ZERO)) .build(); operations.add(ExtensionFeedItemOperation.newBuilder().setCreate(extensionFeedItem4).build()); // Creates the ExtensionFeedItemServiceClient. try (ExtensionFeedItemServiceClient extensionFeedItemServiceClient = googleAdsClient.getLatestVersion().createExtensionFeedItemServiceClient()) { // Adds the ExtensionFeedItem. MutateExtensionFeedItemsResponse response = extensionFeedItemServiceClient.mutateExtensionFeedItems( Long.toString(customerId), operations); System.out.printf("Added %d ExtensionFeedItems:%n", response.getResultsCount()); List<String> resourceNames = new ArrayList<>(); for (MutateExtensionFeedItemResult result : response.getResultsList()) { System.out.printf( "Created ExtensionFeedItems with resource name '%s'.%n", result.getResourceName()); resourceNames.add(result.getResourceName()); } return resourceNames; } } /** * Creates a new SitelinkFeedItem with the specified attributes. * * @param sitelinkText the text of the sitelink feed item. * @param sitelinkUrl the URL of the sitelink feed item. */ private static SitelinkFeedItem createSitelinkFeedItem(String sitelinkText, String sitelinkUrl) { return SitelinkFeedItem.newBuilder() .setLinkText(sitelinkText) .addFinalUrls(sitelinkUrl) .build(); } /** * Creates a new AdScheduleInfo with the specified attributes. * * @param day day of the week of the AdScheduleInfo. * @param startHour the starting hour of the AdScheduleInfo. * @param startMinute the starting minute of the AdScheduleInfo. * @param endHour the ending hour of the AdScheduleInfo. * @param endMinute ending minute of the AdScheduleInfo. */ private static AdScheduleInfo createAdScheduleInfo( DayOfWeek day, int startHour, MinuteOfHour startMinute, int endHour, MinuteOfHour endMinute) { return AdScheduleInfo.newBuilder() .setDayOfWeek(day) .setStartHour(startHour) .setStartMinute(startMinute) .setEndHour(endHour) .setEndMinute(endMinute) .build(); } }
C#
// Copyright 2020 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.GoogleAds.Lib; using Google.Ads.GoogleAds.V13.Common; using Google.Ads.GoogleAds.V13.Enums; using Google.Ads.GoogleAds.V13.Errors; using Google.Ads.GoogleAds.V13.Resources; using Google.Ads.GoogleAds.V13.Services; using System; using System.Collections.Generic; using static Google.Ads.GoogleAds.V13.Enums.ExtensionTypeEnum.Types; using static Google.Ads.GoogleAds.V13.Enums.FeedItemTargetDeviceEnum.Types; using static Google.Ads.GoogleAds.V13.Enums.KeywordMatchTypeEnum.Types; using static Google.Ads.GoogleAds.V13.Enums.MinuteOfHourEnum.Types; namespace Google.Ads.GoogleAds.Examples.V13 { /// <summary> /// This code example adds sitelinks to a campaign. To create a campaign, run AddCampaigns.cs. /// </summary> [Obsolete("THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION. All " + "extensions should migrate to Assets. See AddSitelinksUsingAssets.cs.")] public class AddSitelinks : ExampleBase { /// <summary> /// Command line options for running the <see cref="AddSitelinks"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// ID of the campaign to which sitelinks are added. /// </summary> [Option("campaignId", Required = true, HelpText = "ID of the campaign to which sitelinks are added.")] public long CampaignId { 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); AddSitelinks codeExample = new AddSitelinks(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.CampaignId); } /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example adds sitelinks to a campaign. To create a campaign, run " + "AddCampaigns.cs."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="campaignId">ID of the campaign to which sitelinks are added.</param> public void Run(GoogleAdsClient client, long customerId, long campaignId) { // Get the CampaignExtensionSettingServiceClient. CampaignExtensionSettingServiceClient campaignExtensionSettingService = client.GetService(Services.V13.CampaignExtensionSettingService); string campaignResourceName = ResourceNames.Campaign(customerId, campaignId); List<string> extensionFeedItems = CreateExtensionFeedItems(client, customerId, campaignResourceName); // Creates a CampaignExtensionSetting. CampaignExtensionSetting campaignExtensionSetting = new CampaignExtensionSetting() { Campaign = campaignResourceName, ExtensionType = ExtensionType.Sitelink, ExtensionFeedItems = { extensionFeedItems } }; // Creates the operation. CampaignExtensionSettingOperation operation = new CampaignExtensionSettingOperation() { Create = campaignExtensionSetting }; try { MutateCampaignExtensionSettingsResponse response = campaignExtensionSettingService.MutateCampaignExtensionSettings( customerId.ToString(), new[] { operation }); foreach (MutateCampaignExtensionSettingResult result in response.Results) { Console.WriteLine($"Created CampaignExtensionSetting with resource" + $" name '{result.ResourceName}'."); } } catch (GoogleAdsException e) { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); throw; } } /// <summary> /// Creates a list of ExtensionFeedItems. /// </summary> ///<param name="client">The Google Ads API client.</param> ///<param name="customerId">The client customer ID.</param> ///<param name="campaignResourceName">The resource name of the campaign to target.</param> private static List<string> CreateExtensionFeedItems(GoogleAdsClient client, long customerId, string campaignResourceName) { // Get the ExtensionFeedItemServiceClient. ExtensionFeedItemServiceClient extensionFeedItemService = client.GetService(Services.V13.ExtensionFeedItemService); SitelinkFeedItem sitelinkFeedItem1 = CreateSitelinkFeedItem( "Store Hours", "http://www.example.com/storehours"); // Creates an ExtensionFeedItem from the SitelinkFeedItem. ExtensionFeedItem extensionFeedItem1 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem1, TargetedCampaign = campaignResourceName }; List<ExtensionFeedItemOperation> operations = new List<ExtensionFeedItemOperation>(); // Creates an ExtensionFeedItemOperation and adds it to the operations List. operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem1 }); SitelinkFeedItem sitelinkFeedItem2 = CreateSitelinkFeedItem( "Thanksgiving Specials", "http://www.example.com/thanksgiving"); DateTime startTime = new DateTime(DateTime.Now.Year, 11, 20, 0, 0, 0); if (startTime < DateTime.Now) { // Move the startTime to next year if the current date is past November 20th. startTime = startTime.AddYears(1); } // Converts to a string in the required format. string startTimeString = startTime.ToString("yyyy-MM-dd hh:mm:ss"); // Use the same year as startTime when creating endTime. DateTime endTime = new DateTime(startTime.Year, 11, 27, 23, 59, 59); string unitedStates = ResourceNames.GeoTargetConstant(2840); ExtensionFeedItem extensionFeedItem2 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem2, TargetedCampaign = campaignResourceName, // StartDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format. StartDateTime = startTime.ToString("yyyy-MM-dd hh:mm:ss"), // EndDateTime should be formatted in "yyyy-MM-dd hh:mm:ss" format. EndDateTime = endTime.ToString("yyyy-MM-dd hh:mm:ss"), // Targets this sitelink for United States only. // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets TargetedGeoTargetConstant = ResourceNames.GeoTargetConstant(2840) }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem2 }); SitelinkFeedItem sitelinkFeedItem3 = CreateSitelinkFeedItem( "Wifi available", "http://www.example.com/mobile/wifi"); ExtensionFeedItem extensionFeedItem3 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem3, TargetedCampaign = campaignResourceName, Device = FeedItemTargetDevice.Mobile, TargetedKeyword = new KeywordInfo() { Text = "free wifi", MatchType = KeywordMatchType.Broad } }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem3 }); SitelinkFeedItem sitelinkFeedItem4 = CreateSitelinkFeedItem( "Happy hours", "http://www.example.com/happyhours"); ExtensionFeedItem extensionFeedItem4 = new ExtensionFeedItem() { ExtensionType = ExtensionType.Sitelink, SitelinkFeedItem = sitelinkFeedItem4, TargetedCampaign = campaignResourceName, AdSchedules = { CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Monday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Tuesday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Wednesday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Thursday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek.Friday, 18, MinuteOfHour.Zero, 21, MinuteOfHour.Zero), } }; operations.Add(new ExtensionFeedItemOperation() { Create = extensionFeedItem4 }); // Adds the ExtensionFeedItem. MutateExtensionFeedItemsResponse response = extensionFeedItemService.MutateExtensionFeedItems(customerId.ToString(), operations); Console.WriteLine($"Added {response.Results.Count}:"); List<string> resourceNames = new List<string>(); foreach (MutateExtensionFeedItemResult result in response.Results) { Console.WriteLine($"Created ExtensionFeedItems with " + $"resource name '{result.ResourceName}'."); resourceNames.Add(result.ResourceName); } return resourceNames; } /// <summary> /// Creates a new SitelinkFeedItem with the specified attributes. /// </summary> /// <param name="sitelinkText">The text of the sitelink feed item.</param> /// <param name="sitelinkUrl">The URL of the sitelink feed item.</param> /// <returns>The sitelink feed item.</returns> private static SitelinkFeedItem CreateSitelinkFeedItem(string sitelinkText, string sitelinkUrl) { return new SitelinkFeedItem() { LinkText = sitelinkText, FinalUrls = { sitelinkUrl } }; } /// <summary> /// Creates a new AdScheduleInfo with the specified attributes. /// </summary> /// <param name="day">Day of the week of the AdScheduleInfo.</param> /// <param name="startHour">The starting hour of the AdScheduleInfo.</param> /// <param name="startMinute">The starting minute of the AdScheduleInfo.</param> /// <param name="endHour">The ending hour of the AdScheduleInfo.</param> /// <param name="endMinute">The ending minute of the AdScheduleInfo.</param> /// <returns>The ad schedule info.</returns> private static AdScheduleInfo CreateAdScheduleInfo(DayOfWeekEnum.Types.DayOfWeek day, int startHour, MinuteOfHour startMinute, int endHour, MinuteOfHour endMinute) { return new AdScheduleInfo() { DayOfWeek = day, StartHour = startHour, StartMinute = startMinute, EndHour = endHour, EndMinute = endMinute }; } } }
PHP
<?php /** * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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\Extensions; require __DIR__ . '/../../vendor/autoload.php'; use GetOpt\GetOpt; use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames; use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser; use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClient; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsClientBuilder; use Google\Ads\GoogleAds\Lib\V13\GoogleAdsException; use Google\Ads\GoogleAds\Util\V13\ResourceNames; use Google\Ads\GoogleAds\V13\Common\AdScheduleInfo; use Google\Ads\GoogleAds\V13\Common\KeywordInfo; use Google\Ads\GoogleAds\V13\Common\SitelinkFeedItem; use Google\Ads\GoogleAds\V13\Enums\DayOfWeekEnum\DayOfWeek; use Google\Ads\GoogleAds\V13\Enums\ExtensionTypeEnum\ExtensionType; use Google\Ads\GoogleAds\V13\Enums\FeedItemTargetDeviceEnum\FeedItemTargetDevice; use Google\Ads\GoogleAds\V13\Enums\KeywordMatchTypeEnum\KeywordMatchType; use Google\Ads\GoogleAds\V13\Enums\MinuteOfHourEnum\MinuteOfHour; use Google\Ads\GoogleAds\V13\Errors\GoogleAdsError; use Google\Ads\GoogleAds\V13\Resources\CampaignExtensionSetting; use Google\Ads\GoogleAds\V13\Resources\ExtensionFeedItem; use Google\Ads\GoogleAds\V13\Services\CampaignExtensionSettingOperation; use Google\Ads\GoogleAds\V13\Services\ExtensionFeedItemOperation; use Google\ApiCore\ApiException; /** * DEPRECATION WARNING! * THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION * All extensions should migrate to Assets. See AddSitelinksUsingAssets.php. * * Adds sitelinks to a campaign. To create a campaign, run AddCampaigns.php. */ class AddSitelinks { private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE'; private const CAMPAIGN_ID = 'INSERT_CAMPAIGN_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::CAMPAIGN_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::CAMPAIGN_ID] ?: self::CAMPAIGN_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 client customer ID * @param int $campaignId the campaign ID */ public static function runExample( GoogleAdsClient $googleAdsClient, int $customerId, int $campaignId ) { $campaignResourceName = ResourceNames::forCampaign($customerId, $campaignId); // Creates extension feed items as sitelinks. $extensionFeedItems = self::createExtensionFeedItems($googleAdsClient, $customerId, $campaignResourceName); // Creates a campaign extension setting using the previously created extension feed items. $campaignExtensionSetting = new CampaignExtensionSetting([ 'campaign' => $campaignResourceName, 'extension_type' => ExtensionType::SITELINK, 'extension_feed_items' => $extensionFeedItems ]); // Creates the campaign extension setting operation. $campaignExtensionSettingOperation = new CampaignExtensionSettingOperation(); $campaignExtensionSettingOperation->setCreate($campaignExtensionSetting); // Issues a mutate request to add the campaign extension setting. $campaignExtensionSettingServiceClient = $googleAdsClient->getCampaignExtensionSettingServiceClient(); $response = $campaignExtensionSettingServiceClient->mutateCampaignExtensionSettings( $customerId, [$campaignExtensionSettingOperation] ); // Prints the resource name of the created campaign extension setting. /** @var CampaignExtensionSetting $addedCampaignExtensionSetting */ $addedCampaignExtensionSetting = $response->getResults()[0]; printf( "Created a campaign extension setting with resource name: '%s'%s", $addedCampaignExtensionSetting->getResourceName(), PHP_EOL ); } /** * Creates a list of extension feed items. * * @param GoogleAdsClient $googleAdsClient the Google Ads API client * @param int $customerId the client customer ID * @param string $campaignResourceName the resource name of the campaign to target * @return string[] the list of extension feed items' resource names */ private static function createExtensionFeedItems( GoogleAdsClient $googleAdsClient, int $customerId, string $campaignResourceName ) { // Creates the first sitelink feed item. $sitelinkFeedItem1 = self::createSitelinkFeedItem('Store Hours', 'http://www.example.com/storehours'); // Creates an extension feed item from the sitelink feed item. $extensionFeedItem1 = new ExtensionFeedItem([ 'extension_type' => ExtensionType::SITELINK, 'sitelink_feed_item' => $sitelinkFeedItem1, 'targeted_campaign' => $campaignResourceName ]); // Creates the second sitelink feed item. $sitelinkFeedItem2 = self::createSitelinkFeedItem( 'Thanksgiving Specials', 'http://www.example.com/thanksgiving' ); // Start date is set to November 20th. If it's already passed that date for this year, // use the same date for the next year instead. $targetYearString = date('Y'); if (strtotime('now') > strtotime('20 November')) { $targetYearString = date('Y', strtotime('+1 year')); } $startTimeString = date('Y-m-d H:i:s', mktime(0, 0, 0, 11, 20, intval($targetYearString))); // Use the same year as start time when creating end time. $endTimeString = date('Y-m-d H:i:s', mktime(23, 59, 59, 11, 27, intval($targetYearString))); // Targets this sitelink for United States only. // A list of country codes can be referenced here: // https://developers.google.com/google-ads/api/reference/data/geotargets. $unitedStates = ResourceNames::forGeoTargetConstant(2840); // Creates an extension feed item from the sitelink feed item. $extensionFeedItem2 = new ExtensionFeedItem([ 'extension_type' => ExtensionType::SITELINK, 'sitelink_feed_item' => $sitelinkFeedItem2, 'targeted_campaign' => $campaignResourceName, 'start_date_time' => $startTimeString, 'end_date_time' => $endTimeString, 'targeted_geo_target_constant' => $unitedStates ]); // Creates the third sitelink feed item. $sitelinkFeedItem3 = self::createSitelinkFeedItem('Wifi available', 'http://www.example.com/mobile/wifi'); // Creates an extension feed item from the sitelink feed item. $extensionFeedItem3 = new ExtensionFeedItem([ 'extension_type' => ExtensionType::SITELINK, 'sitelink_feed_item' => $sitelinkFeedItem3, 'targeted_campaign' => $campaignResourceName, 'device' => FeedItemTargetDevice::MOBILE, 'targeted_keyword' => new KeywordInfo([ 'text' => 'free wifi', 'match_type' => KeywordMatchType::BROAD ]) ]); // Creates the fourth sitelink feed item. $sitelinkFeedItem4 = self::createSitelinkFeedItem('Happy hours', 'http://www.example.com/happyhours'); // Creates an extension feed item from the sitelink feed item. $extensionFeedItem4 = new ExtensionFeedItem([ 'extension_type' => ExtensionType::SITELINK, 'sitelink_feed_item' => $sitelinkFeedItem4, 'targeted_campaign' => $campaignResourceName, 'ad_schedules' => [ self::createAdScheduleInfo( DayOfWeek::MONDAY, 18, MinuteOfHour::ZERO, 21, MinuteOfHour::ZERO ), self::createAdScheduleInfo( DayOfWeek::TUESDAY, 18, MinuteOfHour::ZERO, 21, MinuteOfHour::ZERO ), self::createAdScheduleInfo( DayOfWeek::WEDNESDAY, 18, MinuteOfHour::ZERO, 21, MinuteOfHour::ZERO ), self::createAdScheduleInfo( DayOfWeek::THURSDAY, 18, MinuteOfHour::ZERO, 21, MinuteOfHour::ZERO ), self::createAdScheduleInfo( DayOfWeek::FRIDAY, 18, MinuteOfHour::ZERO, 21, MinuteOfHour::ZERO ) ] ]); // Issues a mutate request to add the extension feed items. $extensionFeedItemServiceClient = $googleAdsClient->getExtensionFeedItemServiceClient(); $response = $extensionFeedItemServiceClient->mutateExtensionFeedItems( $customerId, [ new ExtensionFeedItemOperation(['create' => $extensionFeedItem1]), new ExtensionFeedItemOperation(['create' => $extensionFeedItem2]), new ExtensionFeedItemOperation(['create' => $extensionFeedItem3]), new ExtensionFeedItemOperation(['create' => $extensionFeedItem4]) ] ); // Prints some information about the created extension feed items. printf( "Created %d extension feed items with the following resource names:%s", $response->getResults()->count(), PHP_EOL ); $createdExtensionFeedItemsResourceNames = []; foreach ($response->getResults() as $addedExtensionFeedItem) { /** @var ExtensionFeedItem $addedExtensionFeedItem */ $addedExtensionFeedItemResourceName = $addedExtensionFeedItem->getResourceName(); print $addedExtensionFeedItemResourceName . PHP_EOL; $createdExtensionFeedItemsResourceNames[] = $addedExtensionFeedItemResourceName; } return $createdExtensionFeedItemsResourceNames; } /** * Creates a new sitelink feed item with the specified attributes. * * @param $sitelinkText string the text of the sitelink feed item * @param $sitelinkUrl string the URL of the sitelink feed item * @return SitelinkFeedItem the created sitelink feed item */ private static function createSitelinkFeedItem(string $sitelinkText, string $sitelinkUrl) { return new SitelinkFeedItem(['link_text' => $sitelinkText, 'final_urls' => [$sitelinkUrl]]); } /** * Creates a new ad schedule info object with the specified attributes. * * @param int $day the enum value of day of the week of the ad schedule info * @param int $startHour the starting hour of the ad schedule info * @param int $startMinute the enum value of the starting minute of the ad schedule info * @param int $endHour the ending hour of the ad schedule info * @param int $endMinute the enum value of ending minute of the ad schedule info * @return AdScheduleInfo the created ad schedule info */ private static function createAdScheduleInfo( int $day, int $startHour, int $startMinute, int $endHour, int $endMinute ) { return new AdScheduleInfo([ 'day_of_week' => $day, 'start_hour' => $startHour, 'start_minute' => $startMinute, 'end_hour' => $endHour, 'end_minute' => $endMinute ]); } } AddSitelinks::main();
Python
#!/usr/bin/env python # Copyright 2020 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. """Adds sitelinks to a campaign. To create a campaign, run add_campaigns.py. DEPRECATION WARNING! THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION. All extensions should migrate to Assets. See add_sitelinks_using_assets.py """ import argparse import datetime import sys from collections import namedtuple from google.ads.googleads.client import GoogleAdsClient from google.ads.googleads.errors import GoogleAdsException _DateRange = namedtuple("_DateRange", ["start_datetime", "end_datetime"]) _date_format = "%Y-%m-%d %H:%M:%S" def main(client, customer_id, campaign_id): """The main method that creates all necessary entities for the example.""" # Create an extension setting. campaign_service = client.get_service("CampaignService") campaign_ext_setting_service = client.get_service( "CampaignExtensionSettingService" ) campaign_resource_name = campaign_service.campaign_path( customer_id, campaign_id ) feed_item_resource_names = create_extension_feed_items( client, customer_id, campaign_resource_name ) campaign_ext_setting_operation = client.get_type( "CampaignExtensionSettingOperation" ) extension_type_enum = client.enums.ExtensionTypeEnum campaign_ext_setting = campaign_ext_setting_operation.create campaign_ext_setting.campaign = campaign_resource_name campaign_ext_setting.extension_type = extension_type_enum.SITELINK campaign_ext_setting.extension_feed_items.extend(feed_item_resource_names) # Add campaign extension setting with site link feed items. response = campaign_ext_setting_service.mutate_campaign_extension_settings( customer_id=customer_id, operations=[campaign_ext_setting_operation] ) print( "Created CampaignExtensionSetting: " f"'{response.results[0].resource_name}'." ) def create_extension_feed_items(client, customer_id, campaign_resource_name): """Helper method that creates extension feed items. Args: client: a GoogleAdsClient instance. customer_id: a str Google Ads customer ID, that the extension feed items will be created for. campaign_resource_name: a str resource name for the campaign that will be tracked by the created extension feed items. Returns: A list containing resource names for the created extension feed items. """ extension_feed_item_service = client.get_service("ExtensionFeedItemService") geo_target_constant_service = client.get_service("GeoTargetConstantService") extension_type_enum = client.enums.ExtensionTypeEnum feed_item_target_device_enum = client.enums.FeedItemTargetDeviceEnum day_of_week_enum = client.enums.DayOfWeekEnum minute_of_hour_enum = client.enums.MinuteOfHourEnum extension_feed_item_operation1 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item1 = extension_feed_item_operation1.create extension_feed_item1.extension_type = extension_type_enum.SITELINK extension_feed_item1.sitelink_feed_item.link_text = "Store Hours" extension_feed_item1.targeted_campaign = campaign_resource_name extension_feed_item1.sitelink_feed_item.final_urls.append( "http://www.example.com/storehours" ) extension_feed_item_operation2 = client.get_type( "ExtensionFeedItemOperation" ) date_range = get_thanksgiving_string_date_range() extension_feed_item2 = extension_feed_item_operation2.create extension_feed_item2.extension_type = extension_type_enum.SITELINK extension_feed_item2.sitelink_feed_item.link_text = "Thanksgiving Specials" extension_feed_item2.targeted_campaign = campaign_resource_name extension_feed_item2.start_date_time = date_range.start_datetime extension_feed_item2.end_date_time = date_range.end_datetime # Targets this sitelink for the United States only. # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets united_states = geo_target_constant_service.geo_target_constant_path(2048) extension_feed_item2.targeted_geo_target_constant = united_states extension_feed_item2.sitelink_feed_item.final_urls.append( "http://www.example.com/thanksgiving" ) extension_feed_item_operation3 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item3 = extension_feed_item_operation3.create extension_feed_item3.extension_type = extension_type_enum.SITELINK extension_feed_item3.sitelink_feed_item.link_text = "Wifi available" extension_feed_item3.targeted_campaign = campaign_resource_name extension_feed_item3.device = feed_item_target_device_enum.MOBILE extension_feed_item3.sitelink_feed_item.final_urls.append( "http://www.example.com/mobile/wifi" ) extension_feed_item_operation4 = client.get_type( "ExtensionFeedItemOperation" ) extension_feed_item4 = extension_feed_item_operation4.create extension_feed_item4.extension_type = extension_type_enum.SITELINK extension_feed_item4.sitelink_feed_item.link_text = "Happy hours" extension_feed_item4.targeted_campaign = campaign_resource_name extension_feed_item4.device = feed_item_target_device_enum.MOBILE extension_feed_item4.sitelink_feed_item.final_urls.append( "http://www.example.com/happyhours" ) for day_of_week in [ day_of_week_enum.MONDAY, day_of_week_enum.TUESDAY, day_of_week_enum.WEDNESDAY, day_of_week_enum.THURSDAY, day_of_week_enum.FRIDAY, ]: ad_schedule = client.get_type("AdScheduleInfo") populate_ad_schedule( ad_schedule, day_of_week, 18, minute_of_hour_enum.ZERO, 21, minute_of_hour_enum.ZERO, ) extension_feed_item4.ad_schedules.append(ad_schedule) # Add extension feed items feed_response = extension_feed_item_service.mutate_extension_feed_items( customer_id=customer_id, operations=[ extension_feed_item_operation1, extension_feed_item_operation2, extension_feed_item_operation3, extension_feed_item_operation4, ], ) print("Created ExtensionFeedItems:") for feed_item in feed_response.results: print(f"\tResource name: {feed_item.resource_name}") return [result.resource_name for result in feed_response.results] def get_thanksgiving_string_date_range(): """Retrieves a _DateRange with formatted datetime start/end strings.""" now = datetime.datetime.now() start_dt = datetime.datetime(now.year, 11, 20, 0, 0, 0) if start_dt < now: # Move start_dt to next year if the current date is past November 20th. start_dt = start_dt + datetime.timedelta(days=365) end_dt = datetime.datetime(start_dt.year, 11, 27, 23, 59, 59) return DateRange( start_dt.strftime(_date_format), end_dt.strftime(_date_format) ) def populate_ad_schedule( ad_schedule, day_of_week, start_hour, start_minute, end_hour, end_minute ): """Helper method to populate a given AdScheduleInfo instance.""" ad_schedule.day_of_week = day_of_week ad_schedule.start_hour = start_hour ad_schedule.start_minute = start_minute ad_schedule.end_hour = end_hour ad_schedule.end_minute = end_minute if __name__ == "__main__": # GoogleAdsClient will read the google-ads.yaml configuration file in the # home directory if none is specified. googleads_client = GoogleAdsClient.load_from_storage(version="v13") parser = argparse.ArgumentParser( description="Adds sitelinks to the specified campaign." ) # 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( "-i", "--campaign_id", type=str, required=True, help="The campaign ID sitelinks will be added to.", ) args = parser.parse_args() try: main(googleads_client, args.customer_id, args.campaign_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("\t\tOn field: {field_path_element.field_name}") sys.exit(1)
Ruby
#!/usr/bin/env ruby # Encoding: utf-8 # # Copyright 2020 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. # # Adds sitelinks to a campaign. To create a campaign, run add_campaigns.rb. # DEPRECATION WARNING! # THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION # All extensions should migrate to Assets. See add_sitelinks_using_assets.rb. require 'optparse' require 'google/ads/google_ads' require 'date' def add_sitelinks(customer_id, campaign_id) # GoogleAdsClient will read a config file from # ENV['HOME']/google_ads_config.rb when called without parameters client = Google::Ads::GoogleAds::GoogleAdsClient.new campaign_resource_name = client.path.campaign(customer_id, campaign_id) extension_feed_items = create_extension_feed_items(client, customer_id, campaign_resource_name) operation = client.operation.create_resource.campaign_extension_setting do |ces| ces.campaign = campaign_resource_name ces.extension_type = :SITELINK extension_feed_items.each do |efi| ces.extension_feed_items << efi end end response = client.service.campaign_extension_setting.mutate_campaign_extension_settings( customer_id: customer_id, operations: [operation], ) puts "Created a campaign extension setting with resource name '#{response.results.first.resource_name}'" end def create_extension_feed_items(client, customer_id, campaign_resource_name) extension_feed_items = [ client.resource.extension_feed_item do |efi| efi.extension_type = :SITELINK efi.sitelink_feed_item = create_sitelink_feed_item( client, 'Store Hours', 'http://www.example.com/storehours') efi.targeted_campaign = campaign_resource_name end, client.resource.extension_feed_item do |efi| efi.extension_type = :SITELINK efi.sitelink_feed_item = create_sitelink_feed_item( client, 'Thanksgiving Specials', 'http://www.example.com/thanksgiving') efi.targeted_campaign = campaign_resource_name today = Date.today efi.start_date_time = DateTime.new( today.year, today.month, today.day, 0, 0, 0 ).strftime("%Y-%m-%d %H:%M:%S") end_date = today + 7 efi.end_date_time = DateTime.new( end_date.year, end_date.month, end_date.day, 23, 59, 59 ).strftime("%Y-%m-%d %H:%M:%S") # Targets this sitelink for United States only. # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets efi.targeted_geo_target_constant = client.path.geo_target_constant(2840) end, client.resource.extension_feed_item do |efi| efi.extension_type = :SITELINK efi.sitelink_feed_item = create_sitelink_feed_item( client, 'Wifi available', 'http://www.example.com/wifi') efi.targeted_campaign = campaign_resource_name efi.device = :MOBILE efi.targeted_keyword = client.resource.keyword_info do |ki| ki.text = 'free wifi' ki.match_type = :BROAD end end, client.resource.extension_feed_item do |efi| efi.extension_type = :SITELINK efi.sitelink_feed_item = create_sitelink_feed_item( client, 'Happy hours', 'http://www.example.com/happyhours') efi.targeted_campaign = campaign_resource_name efi.ad_schedules << create_ad_schedule(client, :MONDAY, 18, :ZERO, 21, :ZERO) efi.ad_schedules << create_ad_schedule(client, :TUESDAY, 18, :ZERO, 21, :ZERO) efi.ad_schedules << create_ad_schedule(client, :WEDNESDAY, 18, :ZERO, 21, :ZERO) efi.ad_schedules << create_ad_schedule(client, :THURSDAY, 18, :ZERO, 21, :ZERO) efi.ad_schedules << create_ad_schedule(client, :FRIDAY, 18, :ZERO, 21, :ZERO) end ] operations = extension_feed_items.map do |efi| client.operation.create_resource.extension_feed_item(efi) end response = client.service.extension_feed_item.mutate_extension_feed_items( customer_id: customer_id, operations: operations, ) puts "Created #{response.results.size} extension feed items with the following resource names:" response.results.map do |result| puts "\t#{result.resource_name}" result.resource_name end end def create_sitelink_feed_item(client, sitelink_text, sitelink_url) client.resource.sitelink_feed_item do |sfi| sfi.link_text = sitelink_text sfi.final_urls << sitelink_url end end def create_ad_schedule(client, day, start_hour, start_minute, end_hour, end_minute) client.resource.ad_schedule_info do |asi| asi.day_of_week = day asi.start_hour = start_hour asi.start_minute = start_minute asi.end_hour = end_hour asi.end_minute = end_minute end end if __FILE__ == $0 options = {} # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE' options[:campaign_id] = 'INSERT_CAMPAIGN_ID_HERE' 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('-c', '--campaign-id CAMPAIGN-ID', String, 'Campaign ID') do |v| options[:campaign_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_sitelinks(options.fetch(:customer_id).tr("-", ""), options.fetch(:campaign_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
Perl
#!/usr/bin/perl -w # # Copyright 2019, Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This example adds sitelinks to a campaign. To create a campaign, run add_campaigns.pl. # # DEPRECATION WARNING! # THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION # All extensions should migrate to Assets. See add_sitelinks_using_assets.pl 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::V13::Resources::CampaignExtensionSetting; use Google::Ads::GoogleAds::V13::Resources::ExtensionFeedItem; use Google::Ads::GoogleAds::V13::Common::KeywordInfo; use Google::Ads::GoogleAds::V13::Common::SitelinkFeedItem; use Google::Ads::GoogleAds::V13::Common::AdScheduleInfo; use Google::Ads::GoogleAds::V13::Enums::ExtensionTypeEnum qw(SITELINK); use Google::Ads::GoogleAds::V13::Enums::FeedItemTargetDeviceEnum qw(MOBILE); use Google::Ads::GoogleAds::V13::Enums::KeywordMatchTypeEnum qw(BROAD); use Google::Ads::GoogleAds::V13::Enums::DayOfWeekEnum qw(MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY); use Google::Ads::GoogleAds::V13::Enums::MinuteOfHourEnum qw(ZERO); use Google::Ads::GoogleAds::V13::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation; use Google::Ads::GoogleAds::V13::Services::ExtensionFeedItemService::ExtensionFeedItemOperation; use Google::Ads::GoogleAds::V13::Utils::ResourceNames; use Getopt::Long qw(:config auto_help); use Pod::Usage; use Cwd qw(abs_path); use POSIX qw(strftime mktime); # The following parameter(s) should be provided to run the example. You can # either specify these by changing the INSERT_XXX_ID_HERE values below, or on # the command line. # # Parameters passed on the command line will override any parameters set in # code. # # Running the example with -h will print the command line usage. my $customer_id = "INSERT_CUSTOMER_ID_HERE"; my $campaign_id = "INSERT_CAMPAIGN_ID_HERE"; sub add_sitelinks { my ($api_client, $customer_id, $campaign_id) = @_; my $campaign_resource_name = Google::Ads::GoogleAds::V13::Utils::ResourceNames::campaign($customer_id, $campaign_id); # Create extension feed items as sitelinks. my $extension_feed_items = create_extension_feed_items($api_client, $customer_id, $campaign_resource_name); # Create a campaign extension setting. my $campaign_extension_setting = Google::Ads::GoogleAds::V13::Resources::CampaignExtensionSetting->new({ campaign => $campaign_resource_name, extensionType => SITELINK, extensionFeedItems => $extension_feed_items }); # Create a campaign extension setting operation. my $campaign_extension_setting_operation = Google::Ads::GoogleAds::V13::Services::CampaignExtensionSettingService::CampaignExtensionSettingOperation ->new({ create => $campaign_extension_setting }); # Add the campaign extension setting. my $campaign_extension_settings_response = $api_client->CampaignExtensionSettingService()->mutate({ customerId => $customer_id, operations => [$campaign_extension_setting_operation]}); printf "Created campaign extension setting with resource name '%s'.\n", $campaign_extension_settings_response->{results}[0]{resourceName}; return 1; } # Creates a list of extension feed items. sub create_extension_feed_items { my ($api_client, $customer_id, $campaign_resource_name) = @_; my $operations = []; my $sitelink_feed_item_1 = create_sitelink_feed_item("Store Hours", "http://www.example.com/storehours"); # Create an extension feed item from the sitelink feed item. my $extension_feed_item_1 = Google::Ads::GoogleAds::V13::Resources::ExtensionFeedItem->new({ extensionType => SITELINK, sitelinkFeedItem => $sitelink_feed_item_1, targetedCampaign => $campaign_resource_name }); # Create an extension feed item operation and add it to the operations list. push @$operations, Google::Ads::GoogleAds::V13::Services::ExtensionFeedItemService::ExtensionFeedItemOperation ->new({ create => $extension_feed_item_1 }); my $sitelink_feed_item_2 = create_sitelink_feed_item("Thanksgiving Specials", "http://www.example.com/thanksgiving"); # Set the start_time and end_time to show the Thanksgiving specials link only # from 20 - 27 Nov. my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time); my $start_time = mktime(0, 0, 0, 20, 10, $year); if ($start_time < time) { # Move the start_time to next year if the current date is past November 20th. $year += 1; $start_time = mktime(0, 0, 0, 20, 10, $year); } # Convert to a string in the required format. my $start_time_string = strftime("%Y-%m-%d %H:%M:%S", localtime($start_time)); # Use the same year as start_time when creating end_time. my $end_time = mktime(59, 59, 23, 27, 10, $year); my $end_time_string = strftime("%Y-%m-%d %H:%M:%S", localtime($end_time)); # Target this sitelink for United States only. # A list of country codes can be referenced here: # https://developers.google.com/google-ads/api/reference/data/geotargets my $united_states = Google::Ads::GoogleAds::V13::Utils::ResourceNames::geo_target_constant( 2840); my $extension_feed_item_2 = Google::Ads::GoogleAds::V13::Resources::ExtensionFeedItem->new({ extensionType => SITELINK, sitelinkFeedItem => $sitelink_feed_item_2, targetedCampaign => $campaign_resource_name, startDateTime => $start_time_string, endDateTime => $end_time_string, targetedGeoTargetConstant => $united_states }); push @$operations, Google::Ads::GoogleAds::V13::Services::ExtensionFeedItemService::ExtensionFeedItemOperation ->new({ create => $extension_feed_item_2 }); my $sitelink_feed_item_3 = create_sitelink_feed_item("Wifi available", "http://www.example.com/mobile/wifi"); # Set the targeted device to show the wifi details primarily for high end # mobile users. # Target this sitelink for the keyword "free wifi". my $extension_feed_item_3 = Google::Ads::GoogleAds::V13::Resources::ExtensionFeedItem->new({ extensionType => SITELINK, sitelinkFeedItem => $sitelink_feed_item_3, targetedCampaign => $campaign_resource_name, device => MOBILE, targetedKeyword => Google::Ads::GoogleAds::V13::Common::KeywordInfo->new( { text => "free wifi", matchType => BROAD })}); push @$operations, Google::Ads::GoogleAds::V13::Services::ExtensionFeedItemService::ExtensionFeedItemOperation ->new({ create => $extension_feed_item_3 }); my $sitelink_feed_item_4 = create_sitelink_feed_item("Happy hours", "http://www.example.com/happyhours"); # Set the feed item schedules to show the happy hours link only during Mon - Fri # 6PM to 9PM. my $extension_feed_item_4 = Google::Ads::GoogleAds::V13::Resources::ExtensionFeedItem->new({ extensionType => SITELINK, sitelinkFeedItem => $sitelink_feed_item_4, targetedCampaign => $campaign_resource_name, adSchedules => [ create_ad_schedule_info(MONDAY, 18, ZERO, 21, ZERO), create_ad_schedule_info(TUESDAY, 18, ZERO, 21, ZERO), create_ad_schedule_info(WEDNESDAY, 18, ZERO, 21, ZERO), create_ad_schedule_info(THURSDAY, 18, ZERO, 21, ZERO), create_ad_schedule_info(FRIDAY, 18, ZERO, 21, ZERO)]}); push @$operations, Google::Ads::GoogleAds::V13::Services::ExtensionFeedItemService::ExtensionFeedItemOperation ->new({ create => $extension_feed_item_4 }); # Add the extension feed item. my $extension_feed_items_response = $api_client->ExtensionFeedItemService()->mutate({ customerId => $customer_id, operations => $operations }); my $extension_feed_item_results = $extension_feed_items_response->{results}; printf "Added %d extension feed items:\n", scalar @$extension_feed_item_results; my $resource_names = []; foreach my $extension_feed_item_result (@$extension_feed_item_results) { printf "\tCreated extension feed item with resource name '%s'.\n", $extension_feed_item_result->{resourceName}; push @$resource_names, $extension_feed_item_result->{resourceName}; } return $resource_names; } # Creates a new sitelink feed item with the specified attributes. sub create_sitelink_feed_item { my ($sitelink_text, $sitelink_url) = @_; return Google::Ads::GoogleAds::V13::Common::SitelinkFeedItem->new({ linkText => $sitelink_text, finalUrls => $sitelink_url }); } # Creates a new ad schedule info with the specified attributes. sub create_ad_schedule_info { my ($day, $start_hour, $start_minute, $end_hour, $end_minute) = @_; return Google::Ads::GoogleAds::V13::Common::AdScheduleInfo->new({ dayOfWeek => $day, startHour => $start_hour, startMinute => $start_minute, endHour => $end_hour, endMinute => $end_minute }); } # 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); # Parameters passed on the command line will override any parameters set in code. GetOptions("customer_id=s" => \$customer_id, "campaign_id=i" => \$campaign_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, $campaign_id); # Call the example. add_sitelinks($api_client, $customer_id =~ s/-//gr, $campaign_id); =pod =head1 NAME add_sitelinks =head1 DESCRIPTION This example adds sitelinks to a campaign. To create a campaign, run add_campaigns.pl. DEPRECATION WARNING! THIS USAGE IS DEPRECATED AND WILL BE REMOVED IN AN UPCOMING API VERSION All extensions should migrate to Assets. See add_sitelinks_using_assets.pl =head1 SYNOPSIS add_sitelinks.pl [options] -help Show the help message. -customer_id The Google Ads customer ID. -campaign_id The campaign ID. =cut