Partager via


Exemple de code de mots clés négatifs

Cet exemple montre comment associer des mots clés négatifs et des listes mot clé négatives à une campagne.

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

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to associate negative keywords and negative keyword lists with a campaign.
    /// </summary>
    public class NegativeKeywords : ExampleBase
    {
        public override string Description
        {
            get { return "Negative Keywords | 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);

                // Add a campaign that will later be associated with negative keywords. 

                var campaigns = new[]{
                    new Campaign
                    {
                        BudgetType = BudgetLimitType.DailyBudgetStandard,
                        DailyBudget = 50,
                        CampaignType = CampaignType.Search,
                        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);

                long campaignId = (long)campaignIds[0];

                // You may choose to associate an exclusive set of negative keywords to an individual campaign 
                // or ad group. An exclusive set of negative keywords cannot be shared with other campaigns 
                // or ad groups. This example only associates negative keywords with a campaign.

                var entityNegativeKeywords = new[]
                {
                    new EntityNegativeKeyword
                    {
                        EntityId = campaignId,
                        EntityType = "Campaign",
                        NegativeKeywords = new[]
                        {
                            new NegativeKeyword
                            {
                                MatchType = MatchType.Phrase,
                                Text = "auto"
                            },
                            new NegativeKeyword
                            {
                                MatchType = MatchType.Exact,
                                Text = "auto"
                            },
                        }
                    }
                };

                OutputStatusMessage("-----\nAddNegativeKeywordsToEntities:");
                AddNegativeKeywordsToEntitiesResponse addNegativeKeywordsToEntitiesResponse =
                    await CampaignManagementExampleHelper.AddNegativeKeywordsToEntitiesAsync(
                        entityNegativeKeywords: entityNegativeKeywords);
                OutputStatusMessage("Added an exclusive set of negative keywords to the Campaign");
                OutputStatusMessage("NegativeKeywordIds:");
                CampaignManagementExampleHelper.OutputArrayOfIdCollection(addNegativeKeywordsToEntitiesResponse.NegativeKeywordIds);
                OutputStatusMessage("NestedPartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(addNegativeKeywordsToEntitiesResponse.NestedPartialErrors);

                // If you attempt to delete a negative keyword without an identifier the operation will return
                // partial errors corresponding to the index of the negative keyword that was not deleted. 

                OutputStatusMessage("-----\nDeleteNegativeKeywordsFromEntities:");
                BatchErrorCollection[] nestedPartialErrors = (await CampaignManagementExampleHelper.DeleteNegativeKeywordsFromEntitiesAsync(
                    entityNegativeKeywords: entityNegativeKeywords)).NestedPartialErrors.ToArray();
                OutputStatusMessage("Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.");
                CampaignManagementExampleHelper.OutputArrayOfBatchErrorCollection(nestedPartialErrors);

                // Negative keywords can also be added and deleted from a shared negative keyword list. 
                // The negative keyword list can be shared or associated with multiple campaigns.
                // NegativeKeywordList inherits from SharedList which inherits from SharedEntity.

                var negativeKeywordList = new NegativeKeywordList
                {
                    Name = "My Negative Keyword List" + DateTime.UtcNow,
                    Type = "NegativeKeywordList"
                };

                SharedListItem[] negativeKeywords =
                {
                    new NegativeKeyword
                    {
                        Text = "car",
                        Type = "NegativeKeyword",
                        MatchType = MatchType.Exact
                    },
                    new NegativeKeyword
                    {
                        Text = "car",
                        Type = "NegativeKeyword",
                        MatchType = MatchType.Phrase
                    }
                };

                // Add a negative keyword list that can be shared.

                OutputStatusMessage("-----\nAddSharedEntity:");
                var addSharedEntityResponse = await CampaignManagementExampleHelper.AddSharedEntityAsync(
                    sharedEntity: negativeKeywordList, 
                    listItems: negativeKeywords,
                    sharedEntityScope: EntityScope.Account);
                var sharedEntityId = addSharedEntityResponse.SharedEntityId;
                long[] listItemIds = addSharedEntityResponse.ListItemIds.ToArray();

                OutputStatusMessage(string.Format(
                    "NegativeKeywordList added to account library and assigned identifer {0}",
                    sharedEntityId)
                );
                
                // Negative keywords were added to the negative keyword list above. You can associate the 
                // shared list of negative keywords with a campaign with or without negative keywords. 
                // Shared negative keyword lists cannot be associated with an ad group. An ad group can only 
                // be assigned an exclusive set of negative keywords. 

                var associations = new[]
                {
                    new SharedEntityAssociation
                    {
                        EntityId = campaignId,
                        EntityType = "Campaign",
                        SharedEntityId = sharedEntityId,
                        SharedEntityType = "NegativeKeywordList"
                    }
                };

                OutputStatusMessage("-----\nSetSharedEntityAssociations:");
                var partialErrors = (await CampaignManagementExampleHelper.SetSharedEntityAssociationsAsync(
                    associations: associations,
                    sharedEntityScope: EntityScope.Account)).PartialErrors;
                OutputStatusMessage(string.Format(
                    "Associated CampaignId {0} with Negative Keyword List Id {1}.",
                    campaignId, sharedEntityId)
                );
                                
                // 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]));

                // DeleteCampaigns does not delete the negative keyword list from the account's library. 
                // Call the DeleteSharedEntities operation to delete the negative keyword list.

                OutputStatusMessage("-----\nDeleteSharedEntities:");
                partialErrors = (await CampaignManagementExampleHelper.DeleteSharedEntitiesAsync(
                    sharedEntities: new SharedEntity[] { new NegativeKeywordList { Id = sharedEntityId } },
                    sharedEntityScope: EntityScope.Account))?.PartialErrors;
                OutputStatusMessage(string.Format("Deleted Negative Keyword List Id {0}", sharedEntityId));
            }
            // 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 com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;

public class NegativeKeywords extends ExampleBase {
        
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData();

            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                        authorizationData, 
                        API_ENVIRONMENT,
                        ICampaignManagementService.class);

            // Add a campaign that will later be associated with negative keywords. 

            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 nullableCampaignIds = addCampaignsResponse.getCampaignIds();
            ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
            outputStatusMessage("CampaignIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(nullableCampaignIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);
            
            ArrayOflong campaignIds = new ArrayOflong();
            campaignIds.getLongs().add(nullableCampaignIds.getLongs().get(0));
            
            // You may choose to associate an exclusive set of negative keywords to an individual campaign 
            // or ad group. An exclusive set of negative keywords cannot be shared with other campaigns 
            // or ad groups. This example only associates negative keywords with a campaign.

            ArrayOfNegativeKeyword negativeKeywords = new ArrayOfNegativeKeyword();
            NegativeKeyword autoPhrase = new NegativeKeyword();
            autoPhrase.setMatchType(MatchType.PHRASE);
            autoPhrase.setText("auto");
            negativeKeywords.getNegativeKeywords().add(autoPhrase);
            NegativeKeyword autoExact = new NegativeKeyword();
            autoExact.setMatchType(MatchType.EXACT);
            autoExact.setText("auto");
            negativeKeywords.getNegativeKeywords().add(autoExact);
            ArrayOfEntityNegativeKeyword entityNegativeKeywords = new ArrayOfEntityNegativeKeyword();
            EntityNegativeKeyword entityNegativeKeyword = new EntityNegativeKeyword();
            entityNegativeKeyword.setEntityId(nullableCampaignIds.getLongs().get(0));
            entityNegativeKeyword.setEntityType("Campaign");
            entityNegativeKeyword.setNegativeKeywords(negativeKeywords);
            entityNegativeKeywords.getEntityNegativeKeywords().add(entityNegativeKeyword);

            outputStatusMessage("-----\nAddNegativeKeywordsToEntities:");
            AddNegativeKeywordsToEntitiesResponse addNegativeKeywordsToEntitiesResponse = CampaignManagementExampleHelper.addNegativeKeywordsToEntities(
                    entityNegativeKeywords);
            outputStatusMessage("Added an exclusive set of negative keywords to the Campaign.");
            outputStatusMessage("NegativeKeywordIds:");
            CampaignManagementExampleHelper.outputArrayOfIdCollection(addNegativeKeywordsToEntitiesResponse.getNegativeKeywordIds());
            outputStatusMessage("NestedPartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(addNegativeKeywordsToEntitiesResponse.getNestedPartialErrors());
            
            // If you attempt to delete a negative keyword without an identifier the operation will return
            // partial errors corresponding to the index of the negative keyword that was not deleted. 
            
            outputStatusMessage("-----\nDeleteNegativeKeywordsFromEntities:");
            ArrayOfBatchErrorCollection nestedPartialErrors = CampaignManagementExampleHelper.deleteNegativeKeywordsFromEntities(
                    entityNegativeKeywords).getNestedPartialErrors();
            outputStatusMessage("Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.");
            CampaignManagementExampleHelper.outputArrayOfBatchErrorCollection(nestedPartialErrors);       

            // Negative keywords can also be added and deleted from a shared negative keyword list. 
            // The negative keyword list can be shared or associated with multiple campaigns.
            // NegativeKeywordList inherits from SharedList which inherits from SharedEntity.

            NegativeKeywordList negativeKeywordList = new NegativeKeywordList();
            negativeKeywordList.setName("My Negative Keyword List " + System.currentTimeMillis());
            negativeKeywordList.setType("NegativeKeywordList");

            ArrayOfSharedListItem sharedListItems = new ArrayOfSharedListItem();
            NegativeKeyword carExact = new NegativeKeyword();
            carExact.setText("car");
            carExact.setType("NegativeKeyword");
            carExact.setMatchType(MatchType.EXACT);
            sharedListItems.getSharedListItems().add(carExact);
            NegativeKeyword carPhrase = new NegativeKeyword();
            carPhrase.setText("car");
            carPhrase.setType("NegativeKeyword");
            carPhrase.setMatchType(MatchType.PHRASE);
            sharedListItems.getSharedListItems().add(carPhrase);

            // Add a negative keyword list that can be shared.

            outputStatusMessage("-----\nAddSharedEntity:");
            AddSharedEntityResponse addSharedEntityResponse = CampaignManagementExampleHelper.addSharedEntity(
                    negativeKeywordList, 
                    sharedListItems,
                    null);
            long sharedEntityId = addSharedEntityResponse.getSharedEntityId();
            ArrayOflong listItemIds = addSharedEntityResponse.getListItemIds();
            outputStatusMessage(String.format(
                "NegativeKeywordList added to account library and assigned identifer {0}",
                sharedEntityId)
            );

            // Negative keywords were added to the negative keyword list above. You can associate the 
            // shared list of negative keywords with a campaign with or without negative keywords. 
            // Shared negative keyword lists cannot be associated with an ad group. An ad group can only 
            // be assigned an exclusive set of negative keywords. 

            ArrayOfSharedEntityAssociation associations = new ArrayOfSharedEntityAssociation();
            SharedEntityAssociation association = new SharedEntityAssociation();
            association.setEntityId(nullableCampaignIds.getLongs().get(0));
            association.setEntityType("Campaign");
            association.setSharedEntityId(sharedEntityId);
            association.setSharedEntityType("NegativeKeywordList");
            associations.getSharedEntityAssociations().add(association);

            outputStatusMessage("-----\nSetSharedEntityAssociations:");
            ArrayOfBatchError partialErrors = CampaignManagementExampleHelper.setSharedEntityAssociations(
                associations,
                null).getPartialErrors();
            outputStatusMessage(String.format(
                "Associated CampaignId %d with Negative Keyword List Id %d.", 
                nullableCampaignIds.getLongs().get(0), sharedEntityId)
            );

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

            outputStatusMessage("-----\nDeleteCampaigns:");
            ArrayOflong deleteCampaignIds = new ArrayOflong();
            deleteCampaignIds.getLongs().add(nullableCampaignIds.getLongs().get(0));
            CampaignManagementExampleHelper.deleteCampaigns(
                    authorizationData.getAccountId(), 
                    deleteCampaignIds);
            outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0))); 
            
            // DeleteCampaigns does not delete the negative keyword list from the account's library. 
            // Call the DeleteSharedEntities operation to delete the negative keyword list.

            outputStatusMessage("-----\nDeleteSharedEntities:");
            ArrayOfSharedEntity sharedEntities = new ArrayOfSharedEntity();
            negativeKeywordList.setId(sharedEntityId);
            sharedEntities.getSharedEntities().add(negativeKeywordList);
            partialErrors = CampaignManagementExampleHelper.deleteSharedEntities(
                    sharedEntities,
                    null).getPartialErrors();
            outputStatusMessage(String.format("Deleted Negative Keyword List Id %d", sharedEntityId));		 
        } 
        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\EntityNegativeKeyword;
use Microsoft\BingAds\V13\CampaignManagement\SharedEntityAssociation;
use Microsoft\BingAds\V13\CampaignManagement\SharedEntity;
use Microsoft\BingAds\V13\CampaignManagement\SharedList;
use Microsoft\BingAds\V13\CampaignManagement\SharedListItem;
use Microsoft\BingAds\V13\CampaignManagement\NegativeKeyword;
use Microsoft\BingAds\V13\CampaignManagement\NegativeKeywordList;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\MatchType;

// 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();

    // Add a campaign that will later be associated with negative keywords. 
    
    $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);

    // You may choose to associate an exclusive set of negative keywords to an individual campaign 
    // or ad group. An exclusive set of negative keywords cannot be shared with other campaigns 
    // or ad groups. This sample only associates negative keywords with a campaign.

    $negativeKeyword = new NegativeKeyword();
    $negativeKeyword->MatchType = MatchType::Phrase;
    $negativeKeyword->Text = "auto";
             
    $entityNegativeKeyword = new EntityNegativeKeyword();
    $entityNegativeKeyword->EntityId = $campaignIds->long[0];
    $entityNegativeKeyword->EntityType = "Campaign";
    $entityNegativeKeyword->NegativeKeywords = array($negativeKeyword);

    print("-----\r\nAddNegativeKeywordsToEntities:\r\n");
    $addNegativeKeywordsToEntitiesResponse = CampaignManagementExampleHelper::AddNegativeKeywordsToEntities(
        array($entityNegativeKeyword)
    );
    print "Added an exclusive set of negative keywords to the Campaign.\r\n";
    print("NegativeKeywordIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfIdCollection($addNegativeKeywordsToEntitiesResponse->NegativeKeywordIds);
    print("NestedPartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchErrorCollection($addNegativeKeywordsToEntitiesResponse->NestedPartialErrors);
           
    // If you attempt to delete a negative keyword without an identifier the operation will return
    // partial errors corresponding to the index of the negative keyword that was not deleted. 

    print("-----\r\nDeleteNegativeKeywordsFromEntities:\r\n");
    $nestedPartialErrors = CampaignManagementExampleHelper::DeleteNegativeKeywordsFromEntities(
        array($entityNegativeKeyword)
    )->NestedPartialErrors;
    print "Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.\r\n";
    CampaignManagementExampleHelper::OutputArrayOfBatchErrorCollection($nestedPartialErrors);

    // Negative keywords can also be added and deleted from a shared negative keyword list. 
    // The negative keyword list can be shared or associated with multiple campaigns.
    // NegativeKeywordList inherits from SharedList which inherits from SharedEntity.

    $negativeKeywordList = new NegativeKeywordList();
    $negativeKeywordList->Name = "My Negative Keyword List" . $_SERVER['REQUEST_TIME'];
    $negativeKeywordList->Type = "NegativeKeywordList";
    $encodedNegativeKeywordList = new SoapVar(
        $negativeKeywordList, SOAP_ENC_OBJECT, 
        'NegativeKeywordList', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    $negativeKeywords = array();
    $negativeKeyword = new NegativeKeyword();
    $negativeKeyword->Text = "car";
    $negativeKeyword->Type = "NegativeKeyword";
    $negativeKeyword->MatchType = MatchType::Exact;
    $encodedNegativeKeyword = new SoapVar(
        $negativeKeyword, SOAP_ENC_OBJECT, 
        'NegativeKeyword', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $negativeKeywords[] = $encodedNegativeKeyword;

    $negativeKeyword = new NegativeKeyword();
    $negativeKeyword->Text = "car";
    $negativeKeyword->Type = "NegativeKeyword";
    $negativeKeyword->MatchType = MatchType::Phrase;
    $encodedNegativeKeyword = new SoapVar(
        $negativeKeyword, 
        SOAP_ENC_OBJECT, 
        'NegativeKeyword', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $negativeKeywords[] = $encodedNegativeKeyword;

    // Add a negative keyword list that can be shared.
       
    print("-----\r\nAddSharedEntity:\r\n");
    $addSharedEntityResponse = CampaignManagementExampleHelper::AddSharedEntity(
        $encodedNegativeKeywordList, 
        $negativeKeywords,
        null
    );
    $sharedEntityId = $addSharedEntityResponse->SharedEntityId;
    $listItemIds = $addSharedEntityResponse->ListItemIds;
    printf("NegativeKeywordList added to account library and assigned identifer %s\r\n", $sharedEntityId);
           
    // Negative keywords were added to the negative keyword list above. You can associate the 
    // shared list of negative keywords with a campaign with or without negative keywords. 
    // Shared negative keyword lists cannot be associated with an ad group. An ad group can only 
    // be assigned an exclusive set of negative keywords. 

    $associations = array();
    $association = new SharedEntityAssociation();
    $association->EntityId = $campaignIds->long[0];
    $association->EntityType = "Campaign";
    $association->SharedEntityId = $sharedEntityId;
    $association->SharedEntityType = "NegativeKeywordList";
    $associations[] = $association;

    print("-----\r\nSetSharedEntityAssociations:\r\n");
    $partialErrors = CampaignManagementExampleHelper::SetSharedEntityAssociations(
        $associations,
        null
    );
    printf(
        "Associated CampaignId %s with Negative Keyword List Id %s.\r\n", 
        $campaignIds->long[0], $sharedEntityId
    );
           
    // 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]);

    // DeleteCampaigns does not delete the negative keyword list from the account's library. 
    // Call the DeleteSharedEntities operation to delete the shared entities.

    print("-----\r\nDeleteSharedEntities:\r\n");
    $partialErrors = CampaignManagementExampleHelper::DeleteSharedEntities(
        array($encodedNegativeKeywordList),
        null
    );
    printf("Deleted Negative Keyword List Id %s\r\n", $sharedEntityId);
}
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 output_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):

    try:
        # Add a campaign that will later be associated with negative keywords. 

        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)

        # You may choose to associate an exclusive set of negative keywords to an individual campaign 
        # or ad group. An exclusive set of negative keywords cannot be shared with other campaigns 
        # or ad groups. This example only associates negative keywords with a campaign.

        entity_negative_keywords=campaign_service.factory.create('ArrayOfEntityNegativeKeyword')
        entity_negative_keyword=set_elements_to_none(campaign_service.factory.create('EntityNegativeKeyword'))
        entity_negative_keyword.EntityId=campaign_ids['long'][0]
        entity_negative_keyword.EntityType="Campaign"
        negative_keywords=campaign_service.factory.create('ArrayOfNegativeKeyword')
        auto_exact=campaign_service.factory.create('NegativeKeyword')
        auto_exact.MatchType='Exact'
        auto_exact.Text="auto"
        negative_keywords.NegativeKeyword.append(auto_exact)
        auto_phrase=campaign_service.factory.create('NegativeKeyword')
        auto_phrase.MatchType='Phrase'
        auto_phrase.Text="auto"
        negative_keywords.NegativeKeyword.append(auto_phrase)
        entity_negative_keyword.NegativeKeywords=negative_keywords
        entity_negative_keywords.EntityNegativeKeyword.append(entity_negative_keyword)

        output_status_message("-----\nAddNegativeKeywordsToEntities:")
        add_negative_keywords_to_entities_response=campaign_service.AddNegativeKeywordsToEntities(
            EntityNegativeKeywords=entity_negative_keywords
        )
        output_status_message("Added an exclusive set of negative keywords to the Campaign.")
        output_status_message("NegativeKeywordIds:")
        output_array_of_idcollection(add_negative_keywords_to_entities_response.NegativeKeywordIds)
        output_status_message("NestedPartialErrors:")
        output_array_of_batcherrorcollection(add_negative_keywords_to_entities_response.NestedPartialErrors)
        
        # If you attempt to delete a negative keyword without an identifier the operation will return
        # partial errors corresponding to the index of the negative keyword that was not deleted. 
        
        output_status_message("-----\nDeleteNegativeKeywordsFromEntities:")
        nested_partial_errors=campaign_service.DeleteNegativeKeywordsFromEntities(
            EntityNegativeKeywords=entity_negative_keywords
        )
        output_status_message("Attempt to DeleteNegativeKeywordsFromEntities without NegativeKeyword identifier partially fails by design.")
        output_array_of_batcherrorcollection(nested_partial_errors)

        # Negative keywords can also be added and deleted from a shared negative keyword list. 
        # The negative keyword list can be shared or associated with multiple campaigns.
        # NegativeKeywordList inherits from SharedList which inherits from SharedEntity.

        negative_keyword_list=set_elements_to_none(campaign_service.factory.create('NegativeKeywordList'))
        negative_keyword_list.Name="My Negative Keyword List " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        negative_keyword_list.Type="NegativeKeywordList"
        
        negative_keywords=campaign_service.factory.create('ArrayOfSharedListItem')
        car_exact=set_elements_to_none(campaign_service.factory.create('NegativeKeyword'))
        car_exact.Text="car"
        car_exact.Type="NegativeKeyword"
        car_exact.MatchType='Exact'
        negative_keywords.SharedListItem.append(car_exact)
        car_phrase=set_elements_to_none(campaign_service.factory.create('NegativeKeyword'))
        car_phrase.Text="car"
        car_phrase.Type="NegativeKeyword"
        car_phrase.MatchType='Phrase'
        negative_keywords.SharedListItem.append(car_phrase)

        # You can create a new list for negative keywords with or without negative keywords.

        output_status_message("-----\nAddSharedEntity:")
        add_shared_entity_response=campaign_service.AddSharedEntity(
            SharedEntity=negative_keyword_list, 
            ListItems=negative_keywords
        )
        shared_entity_id=add_shared_entity_response.SharedEntityId
        list_item_ids=add_shared_entity_response.ListItemIds
        output_status_message("NegativeKeywordList added to account library and assigned identifer {0}".format(shared_entity_id))
        
        # Negative keywords were added to the negative keyword list above. You can associate the 
        # shared list of negative keywords with a campaign with or without negative keywords. 
        # Shared negative keyword lists cannot be associated with an ad group. An ad group can only 
        # be assigned an exclusive set of negative keywords. 

        shared_entity_associations=campaign_service.factory.create('ArrayOfSharedEntityAssociation')
        shared_entity_association=set_elements_to_none(campaign_service.factory.create('SharedEntityAssociation'))
        shared_entity_association.EntityId=campaign_ids['long'][0]
        shared_entity_association.EntityType="Campaign"
        shared_entity_association.SharedEntityId=shared_entity_id
        shared_entity_association.SharedEntityType="NegativeKeywordList" 
        shared_entity_associations.SharedEntityAssociation.append(shared_entity_association)
        
        output_status_message("-----\nSetSharedEntityAssociations:")
        partial_errors=campaign_service.SetSharedEntityAssociations(
            Associations=shared_entity_associations)
        output_status_message(
            "Associated CampaignId {0} with Negative Keyword List Id {1}.".format(campaign_ids['long'][0], shared_entity_id)
        )

        # 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]))

        # DeleteCampaigns does not delete the negative keyword list from the account's library. 
        #/ Call the DeleteSharedEntities operation to delete the negative keyword list.

        negative_keyword_lists=campaign_service.factory.create('ArrayOfSharedEntity')
        negative_keyword_list=campaign_service.factory.create('NegativeKeywordList')
        negative_keyword_list.Id=shared_entity_id
        negative_keyword_lists.SharedEntity.append(negative_keyword_list)

        output_status_message("-----\nDeleteSharedEntities:")
        partial_errors=campaign_service.DeleteSharedEntities(
            SharedEntities=negative_keyword_lists)
        output_status_message("Deleted Negative Keyword List Id {0}".format(shared_entity_id))

    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