Edit

Bagikan melalui


Profile Criteria Code Example

This example demonstrates how to use company, industry, and job function criteria to show ads to your target audience. For more details see the Show Ads to Your Target Audience technical guide.

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.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to apply Profile Criteria e.g., LinkedIn targeting with the Campaign Management service.
    /// </summary>
    public class ProfileCriteria : ExampleBase
    {
        public override string Description
        {
            get { return "Profile Criteria | 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 an Audience campaign with one ad group.

                var campaigns = new[]{
                    new Campaign
                    {
                        BudgetType = BudgetLimitType.DailyBudgetStandard,
                        // CampaignType must be set for Audience campaigns
                        CampaignType = CampaignType.Audience,
                        DailyBudget = 50,
                        // Languages must be set for Audience campaigns
                        Languages = new string[] { "All" },
                        Name = "Everyone's Shoes " + DateTime.UtcNow,
                        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 },
                        // Network cannot be set for ad groups in Audience campaigns
                        Network = null,
                        Settings = new[]
                        {
                            new TargetSetting
                            {
                                // Sets the "target and bid" option for CompanyName, Industry, and JobFunction. 
                                // Microsoft will only deliver ads to people who meet at least one of your criteria.
                                // By default the "bid only" option is set for Audience, Age, and Gender.
                                // Microsoft will deliver ads to all audiences, ages, and genders, if they meet
                                // your company name, industry, or job function criteria. 
                                Details = new []
                                {
                                    new TargetSettingDetail
                                    {
                                        CriterionTypeGroup = CriterionTypeGroup.CompanyName,
                                        TargetAndBid = true
                                    },
                                    new TargetSettingDetail
                                    {
                                        CriterionTypeGroup = CriterionTypeGroup.Industry,
                                        TargetAndBid = true
                                    },
                                    new TargetSettingDetail
                                    {
                                        CriterionTypeGroup = CriterionTypeGroup.JobFunction,
                                        TargetAndBid = true
                                    },
                                }
                            }
                        },
                    }
                };

                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);
                                
                // Whether or not the "target and bid" option has been set for a given
                // criterion type group, you can set bid adjustments for specific criteria.

                var adGroupCriterions = new List<AdGroupCriterion>();

                var adGroupCompanyNameCriterion = new BiddableAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    CriterionBid = new BidMultiplier
                    {
                        Multiplier = 15
                    },
                    Criterion = new ProfileCriterion
                    {
                        ProfileId = 808251207, // Microsoft
                        ProfileType = ProfileType.CompanyName
                    },
                };
                adGroupCriterions.Add(adGroupCompanyNameCriterion);

                var adGroupIndustryCriterion = new BiddableAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    CriterionBid = new BidMultiplier
                    {
                        Multiplier = 20
                    },
                    Criterion = new ProfileCriterion
                    {
                        ProfileId = 807658654, // Computer & Network Security
                        ProfileType = ProfileType.Industry
                    },
                };
                adGroupCriterions.Add(adGroupIndustryCriterion);

                var adGroupJobFunctionCriterion = new BiddableAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    CriterionBid = new BidMultiplier
                    {
                        Multiplier = 25
                    },
                    Criterion = new ProfileCriterion
                    {
                        ProfileId = 807658477, // Engineering
                        ProfileType = ProfileType.JobFunction
                    },
                };
                adGroupCriterions.Add(adGroupJobFunctionCriterion);

                // Exclude ages twenty-five through thirty-four.

                var adGroupNegativeAgeCriterion = new NegativeAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    Criterion = new AgeCriterion
                    {
                        AgeRange = AgeRange.TwentyFiveToThirtyFour
                    },
                };
                adGroupCriterions.Add(adGroupNegativeAgeCriterion);

                OutputStatusMessage("-----\nAddAdGroupCriterions:");
                CampaignManagementExampleHelper.OutputArrayOfAdGroupCriterion(adGroupCriterions);
                AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = await CampaignManagementExampleHelper.AddAdGroupCriterionsAsync(
                        adGroupCriterions: adGroupCriterions,
                        criterionType: AdGroupCriterionType.Targets);
                long?[] adGroupCriterionIds = addAdGroupCriterionsResponse.AdGroupCriterionIds.ToArray();
                OutputStatusMessage("AdGroupCriterionIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adGroupCriterionIds);
                BatchErrorCollection[] adGroupCriterionErrors =
                    addAdGroupCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(adGroupCriterionErrors);

                // 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<AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<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<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.ArrayList;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.util.Base64;
import java.util.Calendar;

public class ProfileCriteria extends ExampleBase {

    public static void main(java.lang.String[] args) {
    
        try
        {
            authorizationData = getAuthorizationData();
             
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                authorizationData, 
                API_ENVIRONMENT,
                ICampaignManagementService.class);

            // Create an Audience campaign with one ad group.
                        
            ArrayOfCampaign campaigns = new ArrayOfCampaign();
            Campaign campaign = new Campaign();
            campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
            // CampaignType must be set for Audience campaigns
            ArrayList<CampaignType> campaignTypes = new ArrayList<CampaignType>();
            campaignTypes.add(CampaignType.AUDIENCE);
            campaign.setCampaignType(campaignTypes);
            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);
            // Network cannot be set for ad groups in Audience campaigns
            adGroup.setNetwork(null);
            // Sets the "target and bid" option for CompanyName, Industry, and JobFunction. 
            // Microsoft will only deliver ads to people who meet at least one of your criteria.
            // By default the "bid only" option is set for Audience, Age, and Gender.
            // Microsoft will deliver ads to all audiences, ages, and genders, if they meet
            // your company name, industry, or job function criteria. 
            ArrayOfSetting settings = new ArrayOfSetting();
            TargetSetting targetSetting = new TargetSetting();
            ArrayOfTargetSettingDetail targetSettingDetails = new ArrayOfTargetSettingDetail();
            TargetSettingDetail adGroupCompanyNameTargetSettingDetail = new TargetSettingDetail();
            adGroupCompanyNameTargetSettingDetail.setCriterionTypeGroup(CriterionTypeGroup.COMPANY_NAME);
            adGroupCompanyNameTargetSettingDetail.setTargetAndBid(Boolean.TRUE);
            targetSettingDetails.getTargetSettingDetails().add(adGroupCompanyNameTargetSettingDetail);
            TargetSettingDetail adGroupIndustryTargetSettingDetail = new TargetSettingDetail();
            adGroupIndustryTargetSettingDetail.setCriterionTypeGroup(CriterionTypeGroup.INDUSTRY);
            adGroupIndustryTargetSettingDetail.setTargetAndBid(Boolean.TRUE);
            targetSettingDetails.getTargetSettingDetails().add(adGroupIndustryTargetSettingDetail);
            TargetSettingDetail adGroupJobFunctionTargetSettingDetail = new TargetSettingDetail();
            adGroupJobFunctionTargetSettingDetail.setCriterionTypeGroup(CriterionTypeGroup.JOB_FUNCTION);
            adGroupJobFunctionTargetSettingDetail.setTargetAndBid(Boolean.TRUE);
            targetSettingDetails.getTargetSettingDetails().add(adGroupJobFunctionTargetSettingDetail);
            targetSetting.setDetails(targetSettingDetails);
            settings.getSettings().add(targetSetting);
            adGroup.setSettings(settings);
            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);

            // Whether or not the "target and bid" option has been set for a given
            // criterion type group, you can set bid adjustments for specific criteria.
            
            ArrayOfAdGroupCriterion adGroupCriterions = new ArrayOfAdGroupCriterion();
            BidMultiplier criterionBid = new BidMultiplier();
            criterionBid.setMultiplier(20D);

            // ProfileCriterion for CompanyName
            BiddableAdGroupCriterion adGroupCompanyNameCriterion = new BiddableAdGroupCriterion();
            adGroupCompanyNameCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
            adGroupCompanyNameCriterion.setCriterionBid(criterionBid);
            ProfileCriterion companyNameCriterion = new ProfileCriterion();
            companyNameCriterion.setProfileId(808251207L); // Microsoft
            ArrayList<ProfileType> companyProfileType = new ArrayList<ProfileType>();
            companyProfileType.add(ProfileType.COMPANY_NAME);
            companyNameCriterion.setProfileType(companyProfileType);
            adGroupCompanyNameCriterion.setCriterion(companyNameCriterion);
            adGroupCriterions.getAdGroupCriterions().add(adGroupCompanyNameCriterion);
           
            // ProfileCriterion for Industry
            BiddableAdGroupCriterion adGroupIndustryCriterion = new BiddableAdGroupCriterion();
            adGroupIndustryCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
            adGroupIndustryCriterion.setCriterionBid(criterionBid);
            ProfileCriterion industryCriterion = new ProfileCriterion();
            industryCriterion.setProfileId(807658654L); // Computer & Network Security
            ArrayList<ProfileType> industryProfileType = new ArrayList<ProfileType>();
            industryProfileType.add(ProfileType.INDUSTRY);
            industryCriterion.setProfileType(industryProfileType);
            adGroupIndustryCriterion.setCriterion(industryCriterion);
            adGroupCriterions.getAdGroupCriterions().add(adGroupIndustryCriterion);
            
            // ProfileCriterion for JobFunction
            BiddableAdGroupCriterion adGroupJobFunctionCriterion = new BiddableAdGroupCriterion();
            adGroupJobFunctionCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
            adGroupJobFunctionCriterion.setCriterionBid(criterionBid);
            ProfileCriterion jobFunctionCriterion = new ProfileCriterion();
            jobFunctionCriterion.setProfileId(807658477L); // Engineering
            ArrayList<ProfileType> jobFunctionProfileType = new ArrayList<ProfileType>();
            jobFunctionProfileType.add(ProfileType.JOB_FUNCTION);
            jobFunctionCriterion.setProfileType(jobFunctionProfileType);
            adGroupJobFunctionCriterion.setCriterion(jobFunctionCriterion);
            adGroupCriterions.getAdGroupCriterions().add(adGroupJobFunctionCriterion);
            
            // Exclude ages twenty-five through thirty-four.
            
            NegativeAdGroupCriterion adGroupNegativeAgeCriterion = new NegativeAdGroupCriterion();
            adGroupNegativeAgeCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
            AgeCriterion ageCriterion = new AgeCriterion();
            ageCriterion.setAgeRange(AgeRange.TWENTY_FIVE_TO_THIRTY_FOUR);
            adGroupNegativeAgeCriterion.setCriterion(ageCriterion);
            adGroupCriterions.getAdGroupCriterions().add(adGroupNegativeAgeCriterion);
            
            outputStatusMessage("-----\nAddAdGroupCriterions:");
            CampaignManagementExampleHelper.outputArrayOfAdGroupCriterion(adGroupCriterions);
            ArrayList<AdGroupCriterionType> criterionType = new ArrayList<AdGroupCriterionType>();
            criterionType.add(AdGroupCriterionType.TARGETS);     
            AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = CampaignManagementExampleHelper.addAdGroupCriterions(
                    adGroupCriterions, 
                    criterionType);
            ArrayOfNullableOflong adGroupCriterionIds = addAdGroupCriterionsResponse.getAdGroupCriterionIds();
            outputStatusMessage("AdGroupCriterionIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupCriterionIds);
            outputStatusMessage("NestedPartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(addAdGroupCriterionsResponse.getNestedPartialErrors());

            // 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\CampaignType;
use Microsoft\BingAds\V13\CampaignManagement\AdGroup;
use Microsoft\BingAds\V13\CampaignManagement\BiddableAdGroupCriterion;
use Microsoft\BingAds\V13\CampaignManagement\NegativeAdGroupCriterion;
use Microsoft\BingAds\V13\CampaignManagement\AdGroupCriterionType;
use Microsoft\BingAds\V13\CampaignManagement\ProfileCriterion;
use Microsoft\BingAds\V13\CampaignManagement\ProfileType;
use Microsoft\BingAds\V13\CampaignManagement\AgeCriterion;
use Microsoft\BingAds\V13\CampaignManagement\AgeRange;
use Microsoft\BingAds\V13\CampaignManagement\CallToAction;
use Microsoft\BingAds\V13\CampaignManagement\Ad;
use Microsoft\BingAds\V13\CampaignManagement\ResponsiveAd;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
use Microsoft\BingAds\V13\CampaignManagement\BidMultiplier;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Date;
use Microsoft\BingAds\V13\CampaignManagement\Setting;
use Microsoft\BingAds\V13\CampaignManagement\TargetSettingDetail;
use Microsoft\BingAds\V13\CampaignManagement\TargetSetting;
use Microsoft\BingAds\V13\CampaignManagement\CriterionTypeGroup;

// 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 an Audience campaign with one ad group.

    $campaigns = array();   
    $campaign = new Campaign();
    $campaign->Name = "Women's Shoes " . $_SERVER['REQUEST_TIME'];
    // CampaignType must be set for Audience campaigns
    $campaign->CampaignType = CampaignType::Audience;
    $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; 
    // Sets the "target and bid" option for CompanyName, Industry, and JobFunction. 
    // Microsoft will only deliver ads to people who meet at least one of your criteria.
    // By default the "bid only" option is set for Audience, Age, and Gender.
    // Microsoft will deliver ads to all audiences, ages, and genders, if they meet
    // your company name, industry, or job function criteria.
    $adGroupSettings = array();
    $adGroupTargetSetting = new TargetSetting();
    $adGroupTargetSetting->Details = array();
    $adGroupCompanyNameTargetSettingDetail = new TargetSettingDetail();
    $adGroupCompanyNameTargetSettingDetail->CriterionTypeGroup = CriterionTypeGroup::CompanyName;
    $adGroupCompanyNameTargetSettingDetail->TargetAndBid = True;
    $adGroupTargetSetting->Details[] = $adGroupCompanyNameTargetSettingDetail;
    $adGroupIndustryTargetSettingDetail = new TargetSettingDetail();
    $adGroupIndustryTargetSettingDetail->CriterionTypeGroup = CriterionTypeGroup::Industry;
    $adGroupIndustryTargetSettingDetail->TargetAndBid = True;
    $adGroupTargetSetting->Details[] = $adGroupIndustryTargetSettingDetail;
    $adGroupJobFunctionTargetSettingDetail = new TargetSettingDetail();
    $adGroupJobFunctionTargetSettingDetail->CriterionTypeGroup = CriterionTypeGroup::JobFunction;
    $adGroupJobFunctionTargetSettingDetail->TargetAndBid = True;
    $adGroupTargetSetting->Details[] = $adGroupJobFunctionTargetSettingDetail;
    $encodedAdGroupTargetSetting = new SoapVar(
        $adGroupTargetSetting, 
        SOAP_ENC_OBJECT, 
        'TargetSetting', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupSettings[] = $encodedAdGroupTargetSetting;
    $adGroup->Settings=$adGroupSettings;   
    $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);

    // Whether or not the "target and bid" option has been set for a given
    // criterion type group, you can set bid adjustments for specific criteria.

    $adGroupCriterions = array();
    $criterionBid = new BidMultiplier();
    $criterionBid->Multiplier = 20;
    $encodedCriterionBid = new SoapVar(
        $criterionBid, 
        SOAP_ENC_OBJECT, 
        'BidMultiplier', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    // ProfileCriterion for CompanyName
    $adGroupCompanyNameCriterion = new BiddableAdGroupCriterion();
    $adGroupCompanyNameCriterion->AdGroupId = $adGroupIds->long[0];
    $adGroupCompanyNameCriterion->CriterionBid = $encodedCriterionBid;
    $companyNameCriterion = new ProfileCriterion();
    $companyNameCriterion->ProfileId = 808251207; // Microsoft
    $companyNameCriterion->ProfileType = ProfileType::CompanyName;
    $adGroupCompanyNameCriterion->Criterion = new SoapVar(
        $companyNameCriterion, 
        SOAP_ENC_OBJECT, 
        'ProfileCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupCriterions[] = new SoapVar(
        $adGroupCompanyNameCriterion, 
        SOAP_ENC_OBJECT, 
        'BiddableAdGroupCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    // ProfileCriterion for Industry
    $adGroupIndustryCriterion = new BiddableAdGroupCriterion();
    $adGroupIndustryCriterion->AdGroupId = $adGroupIds->long[0];
    $adGroupIndustryCriterion->CriterionBid = $encodedCriterionBid;
    $industryCriterion = new ProfileCriterion();
    $industryCriterion->ProfileId = 807658654; // Computer & Network Security
    $industryCriterion->ProfileType = ProfileType::Industry;
    $adGroupIndustryCriterion->Criterion = new SoapVar(
        $industryCriterion, 
        SOAP_ENC_OBJECT, 
        'ProfileCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupCriterions[] = new SoapVar(
        $adGroupIndustryCriterion, 
        SOAP_ENC_OBJECT, 
        'BiddableAdGroupCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    // ProfileCriterion for JobFunction
    $adGroupJobFunctionCriterion = new BiddableAdGroupCriterion();
    $adGroupJobFunctionCriterion->AdGroupId = $adGroupIds->long[0];
    $adGroupJobFunctionCriterion->CriterionBid = $encodedCriterionBid;
    $jobFunctionCriterion = new ProfileCriterion();
    $jobFunctionCriterion->ProfileId = 807658477; // Engineering
    $jobFunctionCriterion->ProfileType = ProfileType::JobFunction;
    $adGroupJobFunctionCriterion->Criterion = new SoapVar(
        $jobFunctionCriterion, 
        SOAP_ENC_OBJECT, 
        'ProfileCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupCriterions[] = new SoapVar(
        $adGroupJobFunctionCriterion, 
        SOAP_ENC_OBJECT, 
        'BiddableAdGroupCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    // Exclude ages twenty-five through thirty-four.

    $adGroupNegativeAgeCriterion = new NegativeAdGroupCriterion();
    $adGroupNegativeAgeCriterion->AdGroupId = $adGroupIds->long[0];
    $ageCriterion = new AgeCriterion();
    $ageCriterion->AgeRange = AgeRange::TwentyFiveToThirtyFour;
    $adGroupNegativeAgeCriterion->Criterion = new SoapVar(
        $ageCriterion, 
        SOAP_ENC_OBJECT, 
        'AgeCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupCriterions[] = new SoapVar(
        $adGroupNegativeAgeCriterion, 
        SOAP_ENC_OBJECT, 
        'NegativeAdGroupCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    print("-----\r\nAddAdGroupCriterions:\r\n");
    $addAdGroupCriterionsResponse =  CampaignManagementExampleHelper::AddAdGroupCriterions(
        $adGroupCriterions, 
        AdGroupCriterionType::Targets
    );
    $adGroupCriterionIds = $addAdGroupCriterionsResponse->AdGroupCriterionIds;
    print("AdGroupCriterionIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($adGroupCriterionIds);
    $adGroupCriterionErrors = $addAdGroupCriterionsResponse->NestedPartialErrors;
    print("NestedPartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchErrorCollection($adGroupCriterionErrors);

    // 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()."\r\n";
        print $e->getTraceAsString()."\r\n";
    }
}
from auth_helper import *
from campaignmanagement_example_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):

    try:
        # Create an Audience campaign with one ad group.

        campaigns=campaign_service.factory.create('ArrayOfCampaign')
        campaign=set_elements_to_none(campaign_service.factory.create('Campaign'))
        # CampaignType must be set for Audience campaigns
        campaign.CampaignType = ['Audience']
        # Languages must be set for Audience campaigns
        languages=campaign_service.factory.create('ns3:ArrayOfstring')
        languages.string.append('All')
        campaign.Languages = languages
        campaign.Name="Women's Shoes " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        campaign.DailyBudget = 50
        campaign.BudgetType = 'DailyBudgetStandard'
        campaign.TimeZone='PacificTimeUSCanadaTijuana'
        campaigns.Campaign.append(campaign)

        output_status_message("-----\nAddCampaigns:")
        add_campaigns_response=campaign_service.AddCampaigns(
            AccountId=authorization_data.account_id,
            Campaigns=campaigns
        )
        campaign_ids={
            'long': add_campaigns_response.CampaignIds['long'] if add_campaigns_response.CampaignIds['long'] else None
        }
        output_status_message("CampaignIds:")
        output_array_of_long(campaign_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_campaigns_response.PartialErrors)

        # Add an ad group within the campaign.

        ad_groups=campaign_service.factory.create('ArrayOfAdGroup')
        ad_group=set_elements_to_none(campaign_service.factory.create('AdGroup'))
        ad_group.Name="Women's Red Shoe Sale"
        ad_group.Network='OwnedAndOperatedAndSyndicatedSearch'
        ad_group.Status='Paused'
        end_date=campaign_service.factory.create('Date')
        end_date.Day=31
        end_date.Month=12
        end_date.Year=strftime("%Y", gmtime())
        ad_group.EndDate=end_date
        cpc_bid=campaign_service.factory.create('Bid')
        cpc_bid.Amount=0.09
        ad_group.CpcBid=cpc_bid
        # Network cannot be set for ad groups in Audience campaigns
        ad_group.Network = None
        # Sets the "target and bid" option for CompanyName, Industry, and JobFunction. 
        # Microsoft will only deliver ads to people who meet at least one of your criteria.
        # By default the "bid only" option is set for Audience, Age, and Gender.
        # Microsoft will deliver ads to all audiences, ages, and genders, if they meet
        # your company name, industry, or job function criteria.  
        ad_group_settings=campaign_service.factory.create('ArrayOfSetting')
        ad_group_target_setting=campaign_service.factory.create('TargetSetting')
        ad_group_companyname_target_setting_detail=campaign_service.factory.create('TargetSettingDetail')
        ad_group_companyname_target_setting_detail.CriterionTypeGroup='CompanyName'
        ad_group_companyname_target_setting_detail.TargetAndBid=True
        ad_group_target_setting.Details.TargetSettingDetail.append(ad_group_companyname_target_setting_detail)
        ad_group_industry_target_setting_detail=campaign_service.factory.create('TargetSettingDetail')
        ad_group_industry_target_setting_detail.CriterionTypeGroup='Industry'
        ad_group_industry_target_setting_detail.TargetAndBid=True
        ad_group_target_setting.Details.TargetSettingDetail.append(ad_group_industry_target_setting_detail)
        ad_group_jobfunction_target_setting_detail=campaign_service.factory.create('TargetSettingDetail')
        ad_group_jobfunction_target_setting_detail.CriterionTypeGroup='JobFunction'
        ad_group_jobfunction_target_setting_detail.TargetAndBid=True
        ad_group_target_setting.Details.TargetSettingDetail.append(ad_group_jobfunction_target_setting_detail)
        ad_group_settings.Setting.append(ad_group_target_setting)
        ad_group.Settings=ad_group_settings        
        ad_groups.AdGroup.append(ad_group)

        output_status_message("-----\nAddAdGroups:")
        add_ad_groups_response=campaign_service.AddAdGroups(
            CampaignId=campaign_ids['long'][0],
            AdGroups=ad_groups,
            ReturnInheritedBidStrategyTypes=False
        )
        ad_group_ids={
            'long': add_ad_groups_response.AdGroupIds['long'] if add_ad_groups_response.AdGroupIds['long'] else None
        }
        output_status_message("AdGroupIds:")
        output_array_of_long(ad_group_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_ad_groups_response.PartialErrors)

        # Whether or not the "target and bid" option has been set for a given
        # criterion type group, you can set bid adjustments for specific criteria.
                
        ad_group_criterions=campaign_service.factory.create('ArrayOfAdGroupCriterion')
        bid_multiplier=set_elements_to_none(campaign_service.factory.create('BidMultiplier'))
        bid_multiplier.Multiplier=20
        
        ad_group_companyname_criterion=set_elements_to_none(campaign_service.factory.create('BiddableAdGroupCriterion'))
        ad_group_companyname_criterion.AdGroupId=ad_group_ids['long'][0]
        ad_group_companyname_criterion.Status='Paused'
        companyname_criterion=set_elements_to_none(campaign_service.factory.create('ProfileCriterion'))
        companyname_criterion.ProfileId = 808251207 # Microsoft
        companyname_criterion.ProfileType = 'CompanyName'
        ad_group_companyname_criterion.Criterion=companyname_criterion        
        ad_group_companyname_criterion.CriterionBid=bid_multiplier
        ad_group_criterions.AdGroupCriterion.append(ad_group_companyname_criterion)

        ad_group_industry_criterion=set_elements_to_none(campaign_service.factory.create('BiddableAdGroupCriterion'))
        ad_group_industry_criterion.AdGroupId=ad_group_ids['long'][0]
        ad_group_industry_criterion.Status='Paused'
        industry_criterion=set_elements_to_none(campaign_service.factory.create('ProfileCriterion'))
        industry_criterion.ProfileId = 807658654 # Computer & Network Security
        industry_criterion.ProfileType = 'Industry'
        ad_group_industry_criterion.Criterion=industry_criterion        
        ad_group_industry_criterion.CriterionBid=bid_multiplier
        ad_group_criterions.AdGroupCriterion.append(ad_group_industry_criterion)

        ad_group_jobfunction_criterion=set_elements_to_none(campaign_service.factory.create('BiddableAdGroupCriterion'))
        ad_group_jobfunction_criterion.AdGroupId=ad_group_ids['long'][0]
        ad_group_jobfunction_criterion.Status='Paused'
        jobfunction_criterion=set_elements_to_none(campaign_service.factory.create('ProfileCriterion'))
        jobfunction_criterion.ProfileId = 807658477 # Engineering
        jobfunction_criterion.ProfileType = 'JobFunction'
        ad_group_jobfunction_criterion.Criterion=jobfunction_criterion        
        ad_group_jobfunction_criterion.CriterionBid=bid_multiplier
        ad_group_criterions.AdGroupCriterion.append(ad_group_jobfunction_criterion)

        # Exclude ages twenty-five through thirty-four.

        ad_group_negative_age_criterion=set_elements_to_none(campaign_service.factory.create('NegativeAdGroupCriterion'))
        ad_group_negative_age_criterion.AdGroupId=ad_group_ids['long'][0]
        ad_group_negative_age_criterion.Status='Paused'
        age_criterion=set_elements_to_none(campaign_service.factory.create('AgeCriterion'))
        age_criterion.AgeRange = 'TwentyFiveToThirtyFour'
        ad_group_negative_age_criterion.Criterion=age_criterion
        ad_group_criterions.AdGroupCriterion.append(ad_group_negative_age_criterion)

        output_status_message("-----\nAddAdGroupCriterions:")         
        add_ad_group_criterions_response = campaign_service.AddAdGroupCriterions(
            AdGroupCriterions=ad_group_criterions,
            CriterionType='Targets'
        )
        ad_group_criterion_ids={
            'long': add_ad_group_criterions_response.AdGroupCriterionIds['long'] if add_ad_group_criterions_response.AdGroupCriterionIds['long'] else None
        }
        output_status_message("AdGroupCriterionIds:")
        output_array_of_long(ad_group_criterion_ids)
        output_status_message("NestedPartialErrors:")
        output_array_of_batcherrorcollection(add_ad_group_criterions_response.NestedPartialErrors)

        # Delete the campaign and everything it contains e.g., ad groups and ads.

        output_status_message("-----\nDeleteCampaigns:")
        campaign_service.DeleteCampaigns(
            AccountId=authorization_data.account_id,
            CampaignIds=campaign_ids
        )
        output_status_message("Deleted Campaign Id {0}".format(campaign_ids['long'][0]))

    except WebFault as ex:
        output_webfault_errors(ex)
    except Exception as ex:
        output_status_message(ex)

# Main execution
if __name__ == '__main__':

    print("Loading the web service client proxies...")
    
    authorization_data=AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    campaign_service=ServiceClient(
        service='CampaignManagementService', 
        version=13,
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
    )

    authenticate(authorization_data)
    
    main(authorization_data)

See Also

Get Started with the Bing Ads API