Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
In diesem Beispiel wird veranschaulicht, wie Sie responsive Suchanzeigen für eine Suchwerbkampagne einrichten.
Tipp
Verwenden Sie die Sprachauswahl im Dokumentationsheader, um C#, Java, Php oder Python auszuwählen.
Informationen zum Abrufen von Zugriffs- und Aktualisierungstoken für Ihren Microsoft Advertising-Benutzer und Zum ersten Dienstaufruf mithilfe der Bing Ads-API finden Sie im Schnellstarthandbuch . Sie sollten den Leitfaden für die ersten Schritte und exemplarische Vorgehensweisen für Ihre bevorzugte Sprache lesen, z. B. C#, Java, Php und Python.
Unterstützende Dateien für C#-, Java-, Php- und Python-Beispiele sind auf GitHub verfügbar. Sie können jedes Repository klonen oder Codeausschnitte nach Bedarf erneut verwenden.
using System;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;
namespace BingAdsExamplesLibrary.V13
{
/// <summary>
/// How to add responsive search ads in a new ad group.
/// </summary>
public class ResponsiveSearchAds : ExampleBase
{
public override string Description
{
get { return "Responsive Search Ads | Campaign Management V13"; }
}
public async override Task RunAsync(AuthorizationData authorizationData)
{
try
{
ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;
CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
OutputStatusMessageDefault: this.OutputStatusMessage);
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData: authorizationData,
environment: environment);
// Create a Search campaign with one ad group and a responsive search ad.
var campaigns = new[]{
new Campaign
{
Name = "Everyone's Shoes " + DateTime.UtcNow,
BudgetId = null,
DailyBudget = 50,
BudgetType = BudgetLimitType.DailyBudgetStandard,
Languages = new string[] { "All"},
TimeZone = "PacificTimeUSCanadaTijuana",
},
};
OutputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
accountId: authorizationData.AccountId,
campaigns: campaigns);
long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
OutputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);
// Add an ad group within the campaign.
var adGroups = new[] {
new AdGroup
{
Name = "Everyone's Red Shoe Sale",
StartDate = null,
EndDate = new Date {
Month = 12,
Day = 31,
Year = DateTime.UtcNow.Year + 1
},
CpcBid = new Bid { Amount = 0.09 },
}
};
OutputStatusMessage("-----\nAddAdGroups:");
AddAdGroupsResponse addAdGroupsResponse = await CampaignManagementExampleHelper.AddAdGroupsAsync(
campaignId: (long)campaignIds[0],
adGroups: adGroups,
returnInheritedBidStrategyTypes: false);
long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
OutputStatusMessage("AdGroupIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(adGroupIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(adGroupErrors);
// Add keywords and ads within the ad group.
var keywords = new[] {
new Keyword
{
Bid = new Bid { Amount = 0.47 },
Param2 = "10% Off",
MatchType = MatchType.Phrase,
Text = "Brand-A Shoes",
},
};
OutputStatusMessage("-----\nAddKeywords:");
AddKeywordsResponse addKeywordsResponse = await CampaignManagementExampleHelper.AddKeywordsAsync(
adGroupId: (long)adGroupIds[0],
keywords: keywords,
returnInheritedBidStrategyTypes: false);
long?[] keywordIds = addKeywordsResponse.KeywordIds.ToArray();
BatchError[] keywordErrors = addKeywordsResponse.PartialErrors.ToArray();
OutputStatusMessage("KeywordIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(keywordIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(keywordErrors);
// The responsive search ad descriptions and headlines are stored as text assets.
// You must set between 2-4 descriptions and 3-15 headlines.
var ads = new Ad[] {
new ResponsiveSearchAd
{
Descriptions = new AssetLink []
{
new AssetLink
{
Asset = new TextAsset
{
Text = "Find New Customers & Increase Sales!"
},
PinnedField = "Description1"
},
new AssetLink
{
Asset = new TextAsset
{
Text = "Start Advertising on Contoso Today."
},
PinnedField = "Description2"
},
},
Headlines = new AssetLink []
{
new AssetLink
{
Asset = new TextAsset
{
Text = "Contoso"
},
PinnedField = "Headline1"
},
new AssetLink
{
Asset = new TextAsset
{
Text = "Quick & Easy Setup"
},
PinnedField = null
},
new AssetLink
{
Asset = new TextAsset
{
Text = "Seemless Integration"
},
PinnedField = null
},
},
Path1 = "seattle",
Path2 = "shoe sale",
FinalUrls = new[] {
"https://www.contoso.com/womenshoesale"
},
},
};
OutputStatusMessage("-----\nAddAds:");
AddAdsResponse addAdsResponse = await CampaignManagementExampleHelper.AddAdsAsync(
adGroupId: (long)adGroupIds[0],
ads: ads);
long?[] adIds = addAdsResponse.AdIds.ToArray();
BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray();
OutputStatusMessage("AdIds:");
CampaignManagementExampleHelper.OutputArrayOfLong(adIds);
OutputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.OutputArrayOfBatchError(adErrors);
// Delete the campaign and everything it contains e.g., ad groups and ads.
OutputStatusMessage("-----\nDeleteCampaigns:");
await CampaignManagementExampleHelper.DeleteCampaignsAsync(
accountId: authorizationData.AccountId,
campaignIds: new[] { (long)campaignIds[0] });
OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
}
// Catch authentication exceptions
catch (OAuthTokenRequestException ex)
{
OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
}
// Catch Campaign Management service exceptions
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
{
OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
}
catch (Exception ex)
{
OutputStatusMessage(ex.Message);
}
}
}
}
package com.microsoft.bingads.examples.v13;
import java.util.Calendar;
import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
public class ResponsiveSearchAds extends ExampleBase {
public static void main(java.lang.String[] args) {
try
{
authorizationData = getAuthorizationData();
CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
authorizationData,
API_ENVIRONMENT,
ICampaignManagementService.class);
// Create a Search campaign with one ad group and a responsive search ad.
ArrayOfCampaign campaigns = new ArrayOfCampaign();
Campaign campaign = new Campaign();
campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
campaign.setDailyBudget(50.00);
ArrayOfstring languages = new ArrayOfstring();
languages.getStrings().add("All");
campaign.setLanguages(languages);
campaign.setName("Everyone's Shoes " + System.currentTimeMillis());
campaign.setTimeZone("PacificTimeUSCanadaTijuana");
campaigns.getCampaigns().add(campaign);
outputStatusMessage("-----\nAddCampaigns:");
AddCampaignsResponse addCampaignsResponse = CampaignManagementExampleHelper.addCampaigns(
authorizationData.getAccountId(),
campaigns);
ArrayOfNullableOflong campaignIds = addCampaignsResponse.getCampaignIds();
ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
outputStatusMessage("CampaignIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(campaignIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);
// Add an ad group within the campaign.
ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
AdGroup adGroup = new AdGroup();
adGroup.setName("Everyone's Red Shoe Sale");
adGroup.setStartDate(null);
Calendar calendar = Calendar.getInstance();
adGroup.setEndDate(new com.microsoft.bingads.v13.campaignmanagement.Date());
adGroup.getEndDate().setDay(31);
adGroup.getEndDate().setMonth(12);
adGroup.getEndDate().setYear(calendar.get(Calendar.YEAR));
Bid CpcBid = new Bid();
CpcBid.setAmount(0.09);
adGroup.setCpcBid(CpcBid);
adGroups.getAdGroups().add(adGroup);
outputStatusMessage("-----\nAddAdGroups:");
AddAdGroupsResponse addAdGroupsResponse = CampaignManagementExampleHelper.addAdGroups(
campaignIds.getLongs().get(0),
adGroups,
false);
ArrayOfNullableOflong adGroupIds = addAdGroupsResponse.getAdGroupIds();
ArrayOfBatchError adGroupErrors = addAdGroupsResponse.getPartialErrors();
outputStatusMessage("AdGroupIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(adGroupErrors);
// Add keywords and ads within the ad group.
ArrayOfKeyword keywords = new ArrayOfKeyword();
Keyword keyword = new Keyword();
keyword.setBid(new Bid());
keyword.getBid().setAmount(0.47);
keyword.setParam2("10% Off");
keyword.setMatchType(MatchType.PHRASE);
keyword.setText("Brand-A Shoes");
keywords.getKeywords().add(keyword);
outputStatusMessage("-----\nAddKeywords:");
AddKeywordsResponse addKeywordsResponse = CampaignManagementExampleHelper.addKeywords(
adGroupIds.getLongs().get(0),
keywords,
false);
ArrayOfNullableOflong keywordIds = addKeywordsResponse.getKeywordIds();
ArrayOfBatchError keywordErrors = addKeywordsResponse.getPartialErrors();
outputStatusMessage("KeywordIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(keywordIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(keywordErrors);
// The responsive search ad descriptions and headlines are stored as text assets.
// You must set between 2-4 descriptions and 3-15 headlines.
ArrayOfAd ads = new ArrayOfAd();
ResponsiveSearchAd responsiveSearchAd = new ResponsiveSearchAd();
ArrayOfAssetLink descriptionAssetLinks = new ArrayOfAssetLink();
AssetLink descriptionAssetLinkA = new AssetLink();
TextAsset descriptionTextAssetA = new TextAsset();
descriptionTextAssetA.setText("Find New Customers & Increase Sales!");
descriptionAssetLinkA.setAsset(descriptionTextAssetA);
descriptionAssetLinkA.setPinnedField("Description1");
descriptionAssetLinks.getAssetLinks().add(descriptionAssetLinkA);
AssetLink descriptionAssetLinkB = new AssetLink();
TextAsset descriptionTextAssetB = new TextAsset();
descriptionTextAssetB.setText("Start Advertising on Contoso Today.");
descriptionAssetLinkB.setAsset(descriptionTextAssetB);
descriptionAssetLinkB.setPinnedField("Description2");
descriptionAssetLinks.getAssetLinks().add(descriptionAssetLinkB);
responsiveSearchAd.setDescriptions(descriptionAssetLinks);
ArrayOfAssetLink headlineAssetLinks = new ArrayOfAssetLink();
AssetLink headlineAssetLinkA = new AssetLink();
TextAsset headlineTextAssetA = new TextAsset();
headlineTextAssetA.setText("Contoso");
headlineAssetLinkA.setAsset(headlineTextAssetA);
headlineAssetLinkA.setPinnedField("Headline1");
headlineAssetLinks.getAssetLinks().add(headlineAssetLinkA);
AssetLink headlineAssetLinkB = new AssetLink();
TextAsset headlineTextAssetB = new TextAsset();
headlineTextAssetB.setText("Quick & Easy Setup");
headlineAssetLinkB.setAsset(headlineTextAssetB);
headlineAssetLinkB.setPinnedField(null);
headlineAssetLinks.getAssetLinks().add(headlineAssetLinkB);
AssetLink headlineAssetLinkC = new AssetLink();
TextAsset headlineTextAssetC = new TextAsset();
headlineTextAssetC.setText("Seemless Integration");
headlineAssetLinkC.setAsset(headlineTextAssetC);
headlineAssetLinkC.setPinnedField(null);
headlineAssetLinks.getAssetLinks().add(headlineAssetLinkC);
responsiveSearchAd.setHeadlines(headlineAssetLinks);
responsiveSearchAd.setPath1("seattle");
responsiveSearchAd.setPath2("shoe sale");
com.microsoft.bingads.v13.campaignmanagement.ArrayOfstring finalUrls = new com.microsoft.bingads.v13.campaignmanagement.ArrayOfstring();
finalUrls.getStrings().add("https://www.contoso.com/womenshoesale");
responsiveSearchAd.setFinalUrls(finalUrls);
ads.getAds().add(responsiveSearchAd);
outputStatusMessage("-----\nAddAds:");
AddAdsResponse addAdsResponse = CampaignManagementExampleHelper.addAds(
adGroupIds.getLongs().get(0),
ads);
ArrayOfNullableOflong adIds = addAdsResponse.getAdIds();
ArrayOfBatchError adErrors = addAdsResponse.getPartialErrors();
outputStatusMessage("AdIds:");
CampaignManagementExampleHelper.outputArrayOfNullableOflong(adIds);
outputStatusMessage("PartialErrors:");
CampaignManagementExampleHelper.outputArrayOfBatchError(adErrors);
// Delete the campaign and everything it contains e.g., ad groups and ads.
outputStatusMessage("-----\nDeleteCampaigns:");
ArrayOflong deleteCampaignIds = new ArrayOflong();
deleteCampaignIds.getLongs().add(campaignIds.getLongs().get(0));
CampaignManagementExampleHelper.deleteCampaigns(
authorizationData.getAccountId(),
deleteCampaignIds);
outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0)));
}
catch (Exception ex) {
String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
outputStatusMessage(faultXml);
String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
outputStatusMessage(message);
}
}
}
<?php
namespace Microsoft\MsAds\Rest\Test\Services;
use Exception;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddKeywordsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AdGroup;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AssetLink;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Bid;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\BudgetLimitType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Campaign;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\CampaignType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Date;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\Keyword;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\MatchType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ResponsiveSearchAd;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\TextAsset;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;
class ResponsiveSearchAdsTest extends RestApiTestBase
{
/**
* @throws Exception
*/
public function testAddCampaign()
{
$campaign = (new Campaign())
->setName("Women's Shoes ".self::generateRandomAlphaNumeric())
->setCampaignType(CampaignType::SEARCH)
->setBudgetType(BudgetLimitType::DAILY_BUDGET_STANDARD)
->setDailyBudget(50.00)
->setLanguages(["All"])
->setTimeZone("PacificTimeUSCanadaTijuana");
return self::addCampaignsRequest([$campaign]);
}
/**
* @depends testAddCampaign
* @throws Exception
*/
public function testAddAdGroup(array $campaignIds)
{
$adGroup = (new AdGroup())
->setName("Women's Red Shoe Sale".self::generateRandomAlphaNumeric())
->setCpcBid((new Bid())->setAmount(0.09))
->setStartDate(null)
->setEndDate((new Date())->setDay(31)->setMonth(12)->setYear(date("Y")));
return self::addAdGroupsRequest($campaignIds[0], [$adGroup]);
}
/**
* @depends testAddAdGroup
* @throws Exception
*/
public function testAddKeywords(array $adGroupIds)
{
print("-----\r\nAdding Keywords:\r\n");
$keyword = (new Keyword())
->setMatchType(MatchType::BROAD)
->setBid((new Bid())->setAmount(0.47))
->setParam2("10% Off")
->setText("Brand-A Shoes");
$request = new AddKeywordsRequest([
'AdGroupId' => $adGroupIds[0],
'Keywords' => [$keyword]
]);
$response = self::$campaignManagementServiceApi->addKeywords($request);
print("KeywordIds:\r\n");
print_r($response->getKeywordIds());
self::assertNotEmpty($response->getKeywordIds());
print("PartialErrors:\r\n");
print_r($response->getPartialErrors());
self::assertEmpty($response->getPartialErrors());
}
/**
* @depends testAddAdGroup
* @throws Exception
*/
public function testAddResponsiveSearchAd(array $adGroupIds)
{
print("-----\r\nAdding Responsive Search Ad:\r\n");
$responsiveSearchAd = (new ResponsiveSearchAd())
->setFinalUrls(["http://www.contoso.com/womenshoesale"])
->setPath1("seattle")
->setPath2("shoe sale")
->setHeadlines([
(new AssetLink())->setAsset(
(new TextAsset())->setText("Contoso")
)->setPinnedField("Headline1"),
(new AssetLink())->setAsset(
(new TextAsset())->setText("Quick & Easy Setup")
),
(new AssetLink())->setAsset(
(new TextAsset())->setText("Seamless Integration")
)
])
->setDescriptions([
(new AssetLink())->setAsset(
(new TextAsset())->setText("Find New Customers & Increase Sales!")
)->setPinnedField("Description1"),
(new AssetLink())->setAsset(
(new TextAsset())->setText("Start Advertising on Contoso Today.")
)->setPinnedField("Description2")
]);
return self::addAdsRequest($adGroupIds[0], [$responsiveSearchAd]);
}
/**
* @depends testAddCampaign
* @throws Exception
*/
public function testDeleteCampaign(array $campaignIds)
{
self::deleteCampaignsRequest($campaignIds);
}
}
import uuid
from auth_helper import *
from openapi_client.models.campaign import *
def main(authorization_data):
try:
# Create a campaign
print("Creating campaign...")
campaign = Campaign(
name=f"Campaign_{uuid.uuid4()}",
budget_type=BudgetLimitType.DAILYBUDGETSTANDARD,
daily_budget=50.00,
languages=['All'],
time_zone='PacificTimeUSCanadaTijuana',
campaign_type=CampaignType.SEARCH
)
add_campaigns_request = AddCampaignsRequest(
account_id=authorization_data.account_id,
campaigns=[campaign]
)
add_campaigns_response = campaign_service.add_campaigns(
add_campaigns_request=add_campaigns_request
)
campaign_ids = add_campaigns_response.CampaignIds
print(f"Created Campaign ID: {campaign_ids[0]}")
# Create an ad group
print("\nCreating ad group...")
ad_group = AdGroup(
name=f"AdGroup_{uuid.uuid4()}",
start_date=None,
end_date=Date(day=31, month=12, year=datetime.now().year),
cpc_bid=Bid(amount=0.10),
language="English"
)
add_ad_groups_request = AddAdGroupsRequest(
campaign_id=campaign_ids[0],
ad_groups=[ad_group]
)
add_ad_groups_response = campaign_service.add_ad_groups(
add_ad_groups_request=add_ad_groups_request
)
ad_group_ids = add_ad_groups_response.AdGroupIds
print(f"Created Ad Group ID: {ad_group_ids[0]}")
# Create responsive search ads
print("\nCreating responsive search ads...")
ads = []
# Responsive Search Ad requires multiple headlines and descriptions
headlines = [
AssetLink(asset=TextAsset(text="Find New Customers"), pinned_field="Headline1"),
AssetLink(asset=TextAsset(text="Start Advertising on Contoso")),
AssetLink(asset=TextAsset(text="Drive Sales"), pinned_field="Headline2"),
AssetLink(asset=TextAsset(text="Increase Revenue")),
AssetLink(asset=TextAsset(text="Contoso Solutions")),
AssetLink(asset=TextAsset(text="Best Deals Here")),
AssetLink(asset=TextAsset(text="Shop Now")),
AssetLink(asset=TextAsset(text="Limited Time Offer")),
AssetLink(asset=TextAsset(text="Exclusive Discounts")),
AssetLink(asset=TextAsset(text="Top Quality Products")),
AssetLink(asset=TextAsset(text="Fast Shipping")),
AssetLink(asset=TextAsset(text="Customer Satisfaction")),
AssetLink(asset=TextAsset(text="Trusted Brand")),
AssetLink(asset=TextAsset(text="Great Prices")),
AssetLink(asset=TextAsset(text="Buy Online Today"))
]
descriptions = [
AssetLink(asset=TextAsset(text="Find New Customers & Increase Sales! Start Advertising on Contoso Today.")),
AssetLink(asset=TextAsset(text="Seamless Integration. Fast & Easy Setup. Get Started Today.")),
AssetLink(asset=TextAsset(text="Join Thousands of Satisfied Customers. Shop Our Wide Selection.")),
AssetLink(asset=TextAsset(text="Best Prices Guaranteed. Free Shipping on Orders Over $50."))
]
responsive_search_ad = ResponsiveSearchAd(
headlines=headlines,
descriptions=descriptions,
path1="seattle",
path2="shoes",
final_urls=["http://www.contoso.com/womenshoesale"],
final_mobile_urls=["http://mobile.contoso.com/womenshoesale"]
)
ads.append(responsive_search_ad)
add_ads_request = AddAdsRequest(
ad_group_id=ad_group_ids[0],
ads=ads
)
add_ads_response = campaign_service.add_ads(
add_ads_request=add_ads_request
)
ad_ids = add_ads_response.AdIds
print(f"Created {len(ad_ids)} responsive search ads")
print(f"Ad IDs: {ad_ids}")
if add_ads_response.PartialErrors:
print(f"Partial Errors: {add_ads_response.PartialErrors}")
# Get ads
print("\nGetting responsive search ads...")
get_ads_request = GetAdsByAdGroupIdRequest(
ad_group_id=ad_group_ids[0],
ad_types=[AdType.RESPONSIVESEARCH],
return_additional_fields=None
)
get_ads_response = campaign_service.get_ads_by_ad_group_id(
get_ads_by_ad_group_id_request=get_ads_request
)
retrieved_ads = get_ads_response.Ads
print(f"Retrieved {len(retrieved_ads)} ads")
for ad in retrieved_ads:
if ad and hasattr(ad, 'Id'):
print(f" Ad ID: {ad.Id}")
if hasattr(ad, 'Headlines'):
print(f" Number of Headlines: {len(ad.Headlines)}")
if hasattr(ad, 'Descriptions'):
print(f" Number of Descriptions: {len(ad.Descriptions)}")
# Update ad
print("\nUpdating responsive search ad...")
update_ads = []
if len(retrieved_ads) > 0 and retrieved_ads[0]:
# Update with new headlines and descriptions
updated_headlines = [
AssetLink(asset=TextAsset(text="Updated Find Customers")),
AssetLink(asset=TextAsset(text="Updated Start Advertising")),
AssetLink(asset=TextAsset(text="Updated Drive Sales")),
AssetLink(asset=TextAsset(text="Updated Increase Revenue")),
AssetLink(asset=TextAsset(text="Updated Solutions")),
AssetLink(asset=TextAsset(text="Updated Best Deals")),
AssetLink(asset=TextAsset(text="Updated Shop Now")),
AssetLink(asset=TextAsset(text="Updated Time Offer")),
AssetLink(asset=TextAsset(text="Updated Discounts"))
]
updated_descriptions = [
AssetLink(asset=TextAsset(text="Updated - Find New Customers & Increase Sales Today.")),
AssetLink(asset=TextAsset(text="Updated - Seamless Integration & Fast Setup.")),
AssetLink(asset=TextAsset(text="Updated - Join Satisfied Customers."))
]
update_ad = ResponsiveSearchAd(
id=ad_ids[0],
headlines=updated_headlines,
descriptions=updated_descriptions,
final_urls=["http://www.contoso.com/womenshoesale"]
)
update_ads.append(update_ad)
if update_ads:
update_ads_request = UpdateAdsRequest(
ad_group_id=ad_group_ids[0],
ads=update_ads
)
update_ads_response = campaign_service.update_ads(
update_ads_request=update_ads_request
)
if update_ads_response.PartialErrors:
print(f"Partial Errors: {update_ads_response.PartialErrors}")
else:
print("Responsive search ad updated successfully")
# Delete ads
print("\nDeleting ads...")
delete_ads_request = DeleteAdsRequest(
ad_group_id=ad_group_ids[0],
ad_ids=ad_ids
)
delete_ads_response = campaign_service.delete_ads(
delete_ads_request=delete_ads_request
)
if delete_ads_response.PartialErrors:
print(f"Partial Errors: {delete_ads_response.PartialErrors}")
else:
print(f"Deleted {len(ad_ids)} ads")
# Delete ad group
print("\nDeleting ad group...")
delete_ad_groups_request = DeleteAdGroupsRequest(
campaign_id=campaign_ids[0],
ad_group_ids=ad_group_ids
)
campaign_service.delete_ad_groups(
delete_ad_groups_request=delete_ad_groups_request
)
print(f"Deleted Ad Group ID {ad_group_ids[0]}")
# Delete campaign
print("\nDeleting campaign...")
delete_campaigns_request = DeleteCampaignsRequest(
account_id=authorization_data.account_id,
campaign_ids=campaign_ids
)
campaign_service.delete_campaigns(
delete_campaigns_request=delete_campaigns_request
)
print(f"Deleted Campaign ID {campaign_ids[0]}")
except Exception as ex:
print(f"Error occurred: {str(ex)}")
if __name__ == '__main__':
print("Loading the web service client...")
authorization_data = AuthorizationData(
account_id=None,
customer_id=None,
developer_token=DEVELOPER_TOKEN,
authentication=None,
)
authenticate(authorization_data)
campaign_service = ServiceClient(
service='CampaignManagementService',
version=13,
authorization_data=authorization_data,
environment=ENVIRONMENT,
)
main(authorization_data)