Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
This example demonstrates how to setup Responsive Search Ads for a search advertising campaign.
Tip
Use the language selector in the documentation header to choose C#, Java, Php, or Python.
To get access and refresh tokens for your Microsoft Advertising user and make your first service call using the Bing Ads API, see the Quick Start guide. You'll want to review the Get Started guide and walkthroughs for your preferred language e.g., C#, Java, Php, and Python.
Supporting files for C#, Java, Php, and Python examples are available at GitHub. You can clone each repository or repurpose snippets as needed.
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\BingAds\Samples\V13;
// For more information about installing and using the Bing Ads PHP SDK,
// see https://go.microsoft.com/fwlink/?linkid=838593.
require_once __DIR__ . "/../vendor/autoload.php";
include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";
use SoapVar;
use SoapFault;
use Exception;
//Specify the Microsoft\BingAds\V13\CampaignManagement classes that will be used.
use Microsoft\BingAds\V13\CampaignManagement\Campaign;
use Microsoft\BingAds\V13\CampaignManagement\AdGroup;
use Microsoft\BingAds\V13\CampaignManagement\Keyword;
use Microsoft\BingAds\V13\CampaignManagement\Ad;
use Microsoft\BingAds\V13\CampaignManagement\AdType;
use Microsoft\BingAds\V13\CampaignManagement\ResponsiveSearchAd;
use Microsoft\BingAds\V13\CampaignManagement\AssetLink;
use Microsoft\BingAds\V13\CampaignManagement\ImageAsset;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
use Microsoft\BingAds\V13\CampaignManagement\MatchType;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Date;
// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;
// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;
try
{
// Authenticate user credentials and set the account ID for the sample.
AuthHelper::Authenticate();
// Create a Search campaign with one ad group and a responsive search ad.
$campaigns = array();
$campaign = new Campaign();
$campaign->Name = "Women's Shoes " . $_SERVER['REQUEST_TIME'];
$campaign->BudgetType = BudgetLimitType::DailyBudgetStandard;
$campaign->DailyBudget = 50.00;
$campaign->Languages = array("All");
$campaign->TimeZone = "PacificTimeUSCanadaTijuana";
$campaigns[] = $campaign;
print("-----\r\nAddCampaigns:\r\n");
$addCampaignsResponse = CampaignManagementExampleHelper::AddCampaigns(
$GLOBALS['AuthorizationData']->AccountId,
$campaigns
);
$campaignIds = $addCampaignsResponse->CampaignIds;
print("CampaignIds:\r\n");
CampaignManagementExampleHelper::OutputArrayOfLong($campaignIds);
print("PartialErrors:\r\n");
CampaignManagementExampleHelper::OutputArrayOfBatchError($addCampaignsResponse->PartialErrors);
// Add an ad group within the campaign.
$adGroups = array();
$adGroup = new AdGroup();
$adGroup->CpcBid = new Bid();
$adGroup->CpcBid->Amount = 0.09;
date_default_timezone_set('UTC');
$endDate = new Date();
$endDate->Day = 31;
$endDate->Month = 12;
$endDate->Year = date("Y");
$adGroup->EndDate = $endDate;
$adGroup->Name = "Women's Red Shoe Sale";
$adGroup->StartDate = null;
$adGroups[] = $adGroup;
print("-----\r\nAddAdGroups:\r\n");
$addAdGroupsResponse = CampaignManagementExampleHelper::AddAdGroups(
$campaignIds->long[0],
$adGroups,
null
);
$adGroupIds = $addAdGroupsResponse->AdGroupIds;
print("AdGroupIds:\r\n");
CampaignManagementExampleHelper::OutputArrayOfLong($adGroupIds);
print("PartialErrors:\r\n");
CampaignManagementExampleHelper::OutputArrayOfBatchError($addAdGroupsResponse->PartialErrors);
// Add keywords and ads within the ad group.
$keywords = array();
$keyword = new Keyword();
$keyword->Bid = new Bid();
$keyword->Bid->Amount = 0.47;
$keyword->Param2 = "10% Off";
$keyword->MatchType = MatchType::Broad;
$keyword->Text = "Brand-A Shoes";
$keywords[] = $keyword;
print("-----\r\nAddKeywords:\r\n");
$addKeywordsResponse = CampaignManagementExampleHelper::AddKeywords(
$adGroupIds->long[0],
$keywords,
null
);
print("KeywordIds:\r\n");
CampaignManagementExampleHelper::OutputArrayOfLong($addKeywordsResponse->KeywordIds);
print("PartialErrors:\r\n");
CampaignManagementExampleHelper::OutputArrayOfBatchError($addKeywordsResponse->PartialErrors);
// The responsive search ad descriptions and headlines are stored as text assets.
// You must set between 2-4 descriptions and 3-15 headlines.
$ads = array();
$responsiveSearchAd = new ResponsiveSearchAd();
$descriptionAssetLinks = array();
$descriptionAssetLinkA = new AssetLink();
$descriptionTextAssetA = new ImageAsset();
$descriptionTextAssetA->Text = "Find New Customers & Increase Sales!";
$descriptionAssetLinkA->Asset = new SoapVar(
$descriptionTextAssetA,
SOAP_ENC_OBJECT,
'TextAsset',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
$descriptionAssetLinkA->PinnedField = "Description1";
$descriptionAssetLinks[] = $descriptionAssetLinkA;
$descriptionAssetLinkB = new AssetLink();
$descriptionTextAssetB = new ImageAsset();
$descriptionTextAssetB->Text = "Start Advertising on Contoso Today.";
$descriptionAssetLinkB->Asset = new SoapVar(
$descriptionTextAssetB,
SOAP_ENC_OBJECT,
'TextAsset',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
$descriptionAssetLinkB->PinnedField = "Description2";
$descriptionAssetLinks[] = $descriptionAssetLinkB;
$responsiveSearchAd->Descriptions = $descriptionAssetLinks;
$headlineAssetLinks = array();
$headlineAssetLinkA = new AssetLink();
$headlineTextAssetA = new ImageAsset();
$headlineTextAssetA->Text = "Contoso";
$headlineAssetLinkA->Asset = new SoapVar(
$headlineTextAssetA,
SOAP_ENC_OBJECT,
'TextAsset',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
$headlineAssetLinkA->PinnedField = "Headline1";
$headlineAssetLinks[] = $headlineAssetLinkA;
$headlineAssetLinkB = new AssetLink();
$headlineTextAssetB = new ImageAsset();
$headlineTextAssetB->Text = "Quick & Easy Setup";
$headlineAssetLinkB->Asset = new SoapVar(
$headlineTextAssetB,
SOAP_ENC_OBJECT,
'TextAsset',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
$headlineAssetLinkB->PinnedField = null;
$headlineAssetLinks[] = $headlineAssetLinkB;
$headlineAssetLinkC = new AssetLink();
$headlineTextAssetC = new ImageAsset();
$headlineTextAssetC->Text = "Seemless Integration";
$headlineAssetLinkC->Asset = new SoapVar(
$headlineTextAssetC,
SOAP_ENC_OBJECT,
'TextAsset',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
$headlineAssetLinkC->PinnedField = null;
$headlineAssetLinks[] = $headlineAssetLinkC;
$responsiveSearchAd->Headlines = $headlineAssetLinks;
$responsiveSearchAd->Path1 = "seattle";
$responsiveSearchAd->Path2 = "shoe sale";
$responsiveSearchAd->FinalUrls = array("http://www.contoso.com/womenshoesale");
$ads[] = new SoapVar(
$responsiveSearchAd,
SOAP_ENC_OBJECT,
'ResponsiveSearchAd',
$GLOBALS['CampaignManagementProxy']->GetNamespace()
);
print("-----\r\nAddAds:\r\n");
$addAdsResponse = CampaignManagementExampleHelper::AddAds(
$adGroupIds->long[0],
$ads
);
print("AdIds:\r\n");
CampaignManagementExampleHelper::OutputArrayOfLong($addAdsResponse->AdIds);
print("PartialErrors:\r\n");
CampaignManagementExampleHelper::OutputArrayOfBatchError($addAdsResponse->PartialErrors);
// Delete the campaign and everything it contains e.g., ad groups and ads.
print("-----\r\nDeleteCampaigns:\r\n");
CampaignManagementExampleHelper::DeleteCampaigns(
$GLOBALS['AuthorizationData']->AccountId,
array($campaignIds->long[0])
);
printf("Deleted Campaign Id %s\r\n", $campaignIds->long[0]);
}
catch (SoapFault $e)
{
printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
var_dump($e->detail);
print "-----\r\nLast SOAP request/response:\r\n";
print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
// Ignore fault exceptions that we already caught.
if ($e->getPrevious())
{ ; }
else
{
print $e->getCode()." ".$e->getMessage()."\n\n";
print $e->getTraceAsString()."\n\n";
}
}
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)