Partager via


Exemple de code de critères cibles

Cet exemple montre comment utiliser des critères d’emplacement pour afficher des publicités à votre public cible. Pour plus d’informations, consultez le guide technique Afficher les publicités à votre public cible .

Conseil

Utilisez le sélecteur de langage dans l’en-tête de la documentation pour choisir C#, Java, Php ou Python.

Pour obtenir des jetons d’accès et d’actualisation pour votre utilisateur Microsoft Advertising et effectuer votre premier appel de service à l’aide de l’API Bing Ads, consultez le guide de démarrage rapide . Vous pouvez consulter le guide de prise en main et les procédures pas à pas pour votre langage préféré, par exemple, C#, Java, Php et Python.

Les fichiers de prise en charge pour les exemples C#, Java, Php et Python sont disponibles sur GitHub. Vous pouvez cloner chaque dépôt ou réaffecter des extraits de code en fonction des besoins.

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 show ads to people based on target criteria with the Campaign Management API.
    /// </summary>
    public class TargetCriteria : ExampleBase
    {
        public override string Description
        {
            get { return "Target 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);

                // Setup a campaign with one ad group.

                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);
                
                // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
                // target criteria. Effectively, the brand new campaign and ad group target all ages, days, hours, 
                // devices, genders, and locations. As a best practice, you should consider at a minimum 
                // adding a campaign location criterion corresponding to the customer market country.

                var campaignCriterions = new List<CampaignCriterion>();
                var campaignLocationCriterion = new BiddableCampaignCriterion
                {
                    CampaignId = (long)campaignIds[0],
                    Criterion = new LocationCriterion
                    {
                        // United States
                        LocationId = 190,
                        Type = "LocationCriterion"
                    },
                    CriterionBid = new BidMultiplier
                    {
                        Multiplier = 20
                    },
                };
                campaignCriterions.Add(campaignLocationCriterion);

                OutputStatusMessage("-----\nAddCampaignCriterions:");
                var addCampaignCriterionsResponse = await CampaignManagementExampleHelper.AddCampaignCriterionsAsync(
                    campaignCriterions: campaignCriterions,
                    criterionType: CampaignCriterionType.Targets);
                long?[] campaignCriterionIds = addCampaignCriterionsResponse.CampaignCriterionIds.ToArray();
                OutputStatusMessage("CampaignCriterionIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(campaignCriterionIds);
                BatchErrorCollection[] campaignCriterionErrors =
                    addCampaignCriterionsResponse.NestedPartialErrors.ToArray();
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(campaignCriterionErrors);
                
                // A negative location criterion is an excluded location.
                // Ads in this ad group will not be shown to people in Redmond, WA.

                var adGroupCriterions = new List<AdGroupCriterion>();
                var adGroupNegativeAgeCriterion = new NegativeAdGroupCriterion
                {
                    AdGroupId = (long)adGroupIds[0],
                    Criterion = new LocationCriterion
                    {
                        // Redmond|Washington|United States
                        LocationId = 67555,
                        Type = "LocationCriterion"
                    },
                };
                adGroupCriterions.Add(adGroupNegativeAgeCriterion);

                OutputStatusMessage("-----\nAddAdGroupCriterions:");
                var 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 com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;

import java.util.Calendar;
import java.util.ArrayList;

public class TargetCriteria extends ExampleBase {
        
    public static void main(java.lang.String[] args) 
    {        
        try
        {
            authorizationData = getAuthorizationData();
         
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                authorizationData, 
                API_ENVIRONMENT,
                ICampaignManagementService.class);
        
            // Setup a campaign with one ad group.

            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); 
            
            // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
            // target criteria. Effectively, the brand new campaign and ad group target all ages, days, hours, 
            // devices, genders, and locations. As a best practice, you should consider at a minimum 
            // adding a campaign location criterion corresponding to the customer market country.
            
            ArrayOfCampaignCriterion campaignCriterions = new ArrayOfCampaignCriterion();      
            BiddableCampaignCriterion biddableCampaignCriterion = new BiddableCampaignCriterion();
            biddableCampaignCriterion.setCampaignId(campaignIds.getLongs().get(0));            
            LocationCriterion biddableLocationCriterion = new LocationCriterion();
            biddableLocationCriterion.setLocationId((long)190); // United States
            biddableLocationCriterion.setType("LocationCriterion");        			
            BidMultiplier criterionBid = new BidMultiplier();
            criterionBid.setMultiplier(20D);
            biddableCampaignCriterion.setCriterionBid(criterionBid);
            biddableCampaignCriterion.setCriterion(biddableLocationCriterion);            
            campaignCriterions.getCampaignCriterions().add(biddableCampaignCriterion);
            
            ArrayList<CampaignCriterionType> criterionTypes = new ArrayList<CampaignCriterionType>();
            criterionTypes.add(CampaignCriterionType.TARGETS);
            
            outputStatusMessage("-----\nAddCampaignCriterions:");
            AddCampaignCriterionsResponse addCriterionsResponse = CampaignManagementExampleHelper.addCampaignCriterions(
                    campaignCriterions, 
                    criterionTypes);
            ArrayOfNullableOflong campaignCriterionIds = addCriterionsResponse.getCampaignCriterionIds();
            ArrayOfBatchErrorCollection campaignCriterionErrors = addCriterionsResponse.getNestedPartialErrors();
            outputStatusMessage("CampaignCriterionIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(campaignCriterionIds);
            outputStatusMessage("NestedPartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(campaignCriterionErrors); 
            
            // A negative location criterion is an excluded location.
            // Ads in this ad group will not be shown to people in Redmond, WA.
            
            ArrayOfAdGroupCriterion adGroupCriterions = new ArrayOfAdGroupCriterion();   
            NegativeAdGroupCriterion negativeAdGroupCriterion = new NegativeAdGroupCriterion();
            negativeAdGroupCriterion.setAdGroupId(adGroupIds.getLongs().get(0));
            LocationCriterion negativeLocationCriterion = new LocationCriterion();
            negativeLocationCriterion.setLocationId((long)190); // Redmond|Washington|United States
            negativeLocationCriterion.setType("LocationCriterion"); negativeAdGroupCriterion.setCriterion(negativeLocationCriterion);
            adGroupCriterions.getAdGroupCriterions().add(negativeAdGroupCriterion);
            
            ArrayList<AdGroupCriterionType> adGroupCriterionTypes = new ArrayList<AdGroupCriterionType>();
            adGroupCriterionTypes.add(AdGroupCriterionType.TARGETS);
            
            outputStatusMessage("-----\nAddCampaignCriterions:");
            AddAdGroupCriterionsResponse addAdGroupCriterionsResponse = CampaignManagementExampleHelper.addAdGroupCriterions(
                    adGroupCriterions, 
                    adGroupCriterionTypes);
            ArrayOfNullableOflong adGroupCriterionIds = addAdGroupCriterionsResponse.getAdGroupCriterionIds();
            ArrayOfBatchErrorCollection adGroupCriterionErrors = addAdGroupCriterionsResponse.getNestedPartialErrors();
            outputStatusMessage("CampaignCriterionIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupCriterionIds);
            outputStatusMessage("NestedPartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(adGroupCriterionErrors); 
            
            // 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\BiddableCampaignCriterion;
use Microsoft\BingAds\V13\CampaignManagement\NegativeAdGroupCriterion;
use Microsoft\BingAds\V13\CampaignManagement\LocationCriterion;
use Microsoft\BingAds\V13\CampaignManagement\BidMultiplier;
use Microsoft\BingAds\V13\CampaignManagement\AdGroupCriterionType;
use Microsoft\BingAds\V13\CampaignManagement\CampaignCriterionType;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
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();

    // Setup a campaign with one ad group.

    $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);
    
    // When you first create a campaign or ad group using the Bing Ads API, it will not have any 
    // target criteria. Effectively, the brand new campaign and ad group target all ages, days, hours, 
    // devices, genders, and locations. As a best practice, you should consider at a minimum 
    // adding a campaign location criterion corresponding to the customer market country.

    $campaignCriterions = array();
    $campaignLocationCriterion = new BiddableCampaignCriterion();
    $campaignLocationCriterion->CampaignId = $campaignIds->long[0];
    $locationCriterion = new LocationCriterion();
    // United States
    $locationCriterion->LocationId = 190;
    $campaignLocationCriterion->Criterion = new SoapVar(
        $locationCriterion, 
        SOAP_ENC_OBJECT, 
        'LocationCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $bidMultiplier = new BidMultiplier();
    $bidMultiplier->Multiplier = 0;
    $campaignLocationCriterion->CriterionBid = new SoapVar(
        $bidMultiplier, 
        SOAP_ENC_OBJECT, 
        'BidMultiplier', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $campaignCriterions[] = new SoapVar(
        $campaignLocationCriterion, 
        SOAP_ENC_OBJECT, 
        'BiddableCampaignCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    print("-----\r\nAddCampaignCriterions:\r\n");
    $addCampaignCriterionsResponse = CampaignManagementExampleHelper::AddCampaignCriterions(
        $campaignCriterions, 
        CampaignCriterionType::Targets
    );
    print("CampaignCriterionIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($addCampaignCriterionsResponse->CampaignCriterionIds);
    print("NestedPartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchErrorCollection($addCampaignCriterionsResponse->NestedPartialErrors);

    // A negative location criterion is an excluded location.
    // Ads in this ad group will not be shown to people in Redmond, WA.

    $adGroupCriterions = array();
    $adGroupNegativeLocationCriterion = new NegativeAdGroupCriterion();
    $adGroupNegativeLocationCriterion->AdGroupId = $adGroupIds->long[0];
    $locationCriterion = new LocationCriterion();
    // Redmond|Washington|United States
    $locationCriterion->LocationId = 67555;
    $adGroupNegativeLocationCriterion->Criterion = new SoapVar(
        $locationCriterion, 
        SOAP_ENC_OBJECT, 
        'LocationCriterion', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $adGroupCriterions[] = new SoapVar(
        $adGroupNegativeLocationCriterion, 
        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 CampaignId %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";
    }
}
from auth_helper import *
from campaignmanagement_example_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):

    try:
        # Setup a campaign with one ad group.
                
        campaigns=campaign_service.factory.create('ArrayOfCampaign')
        campaign=set_elements_to_none(campaign_service.factory.create('Campaign'))
        campaign.BudgetType='DailyBudgetStandard'
        campaign.DailyBudget=50
        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.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"
        end_date=campaign_service.factory.create('Date')
        end_date.Day=31
        end_date.Month=12
        current_time=gmtime()
        end_date.Year=current_time.tm_year + 1
        ad_group.EndDate=end_date
        cpc_bid=campaign_service.factory.create('Bid')
        cpc_bid.Amount=0.09
        ad_group.CpcBid=cpc_bid
        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)

        # When you first create a campaign or ad group using the Bing Ads API, it will not have any 
        # criterions. Effectively, the brand new campaign and ad group target all ages, days, hours, 
        # devices, genders, and locations. As a best practice, you should consider at a minimum 
        # adding a campaign location criterion corresponding to the customer market country.

        campaign_criterions=campaign_service.factory.create('ArrayOfCampaignCriterion')
        campaign_location_criterion=set_elements_to_none(campaign_service.factory.create('BiddableCampaignCriterion'))
        campaign_location_criterion.Type='BiddableCampaignCriterion'
        campaign_location_criterion.CampaignId=campaign_ids['long'][0]
        bid_multiplier=set_elements_to_none(campaign_service.factory.create('BidMultiplier'))
        bid_multiplier.Type='BidMultiplier'
        bid_multiplier.Multiplier=0
        campaign_location_criterion.CriterionBid=bid_multiplier                
        location_criterion=set_elements_to_none(campaign_service.factory.create('LocationCriterion'))
        location_criterion.Type='LocationCriterion'
        # United States
        location_criterion.LocationId=190
        campaign_location_criterion.Criterion=location_criterion
        campaign_criterions.CampaignCriterion.append(campaign_location_criterion)

        output_status_message("-----\nAddCampaignCriterions:")
        add_campaign_criterions_response = campaign_service.AddCampaignCriterions(
            CampaignCriterions=campaign_criterions,
            CriterionType='Targets'
        )
        campaign_criterion_ids={
            'long': add_campaign_criterions_response.CampaignCriterionIds['long'] 
            if add_campaign_criterions_response.CampaignCriterionIds['long'] else None
        }
        output_status_message("CampaignCriterionIds:")
        output_array_of_long(campaign_criterion_ids)
        output_status_message("NestedPartialErrors:")
        output_array_of_batcherrorcollection(add_campaign_criterions_response.NestedPartialErrors)  

        # A negative location criterion is an excluded location.
        # Ads in this ad group will not be shown to people in Redmond, WA.

        ad_group_criterions=campaign_service.factory.create('ArrayOfAdGroupCriterion')
        ad_group_negative_location_criterion=set_elements_to_none(campaign_service.factory.create('NegativeAdGroupCriterion'))
        ad_group_negative_location_criterion.AdGroupId=ad_group_ids['long'][0]
        ad_group_negative_location_criterion.Status='Active'
        location_criterion=set_elements_to_none(campaign_service.factory.create('LocationCriterion'))
        # Redmond|Washington|United States
        location_criterion.LocationId=67555
        location_criterion.Type='LocationCriterion'
        ad_group_negative_location_criterion.Criterion=location_criterion
        ad_group_criterions.AdGroupCriterion.append(ad_group_negative_location_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_batcherror(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)

Voir aussi

Prise en main de l’API Bing Ads