Codebeispiel für Konvertierungsziele

In diesem Beispiel wird veranschaulicht, wie UET-Tags und Konvertierungsziele verwaltet werden.

Tipp

Verwenden Sie die Sprachauswahl im Dokumentationsheader, um C#, Java, Php oder Python auszuwählen.

Informationen zum Abrufen von Zugriffs- und Aktualisierungstoken für Ihren Microsoft Advertising-Benutzer und Zum ersten Dienstaufruf mithilfe der Bing Ads-API finden Sie im Schnellstarthandbuch . Sie sollten den Leitfaden für die ersten Schritte und exemplarische Vorgehensweisen für Ihre bevorzugte Sprache lesen, z. B. C#, Java, Php und Python.

Unterstützende Dateien für C#-, Java-, Php- und Python-Beispiele sind auf GitHub verfügbar. Sie können jedes Repository klonen oder Codeausschnitte nach Bedarf erneut verwenden.

using System;
using System.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 manage UET tags and conversion goals.
    /// </summary>
    public class ConversionGoals : ExampleBase
    {
        public override string Description
        {
            get { return "UET Tags and Conversion Goals | 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);

                // Before you can track conversions or target audiences using a remarketing list 
                // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
                // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

                // First you should call the GetUetTagsByIds operation to check whether a tag has already been created. 
                // You can leave the TagIds element null or empty to request all UET tags available for the customer.

                OutputStatusMessage("-----\nGetUetTagsByIds:");
                var getUetTagsByIdsResponse = (await CampaignManagementExampleHelper.GetUetTagsByIdsAsync(
                    tagIds: null));
                var uetTags = getUetTagsByIdsResponse.UetTags.ToArray();
                BatchError[] uetTagErrors = getUetTagsByIdsResponse.PartialErrors.ToArray();
                OutputStatusMessage("UetTags:");
                CampaignManagementExampleHelper.OutputArrayOfUetTag(uetTags);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(uetTagErrors);

                // If you do not already have a UET tag that can be used, or if you need another UET tag, 
                // call the AddUetTags service operation to create a new UET tag. If the call is successful, 
                // the tracking script that you should add to your website is included in a corresponding 
                // UetTag within the response message. 

                if (uetTags == null || uetTags.Length < 1)
                {
                    var uetTag = new UetTag
                    {
                        Description = "My First Uet Tag",
                        Name = "New Uet Tag",
                    };
                    OutputStatusMessage("-----\nAddUetTags:");
                    var addUetTagsResponse = await CampaignManagementExampleHelper.AddUetTagsAsync(
                        uetTags: uetTags);
                    uetTags = addUetTagsResponse.UetTags.ToArray();
                    uetTagErrors = addUetTagsResponse.PartialErrors.ToArray();
                    OutputStatusMessage("UetTags:");
                    CampaignManagementExampleHelper.OutputArrayOfUetTag(uetTags);
                    OutputStatusMessage("PartialErrors:");
                    CampaignManagementExampleHelper.OutputArrayOfBatchError(uetTagErrors);
                }

                if (uetTags == null || uetTags.Length < 1)
                {
                    OutputStatusMessage(
                        string.Format("You do not have any UET tags registered for CustomerId {0}.", authorizationData.CustomerId)
                    );
                    return;
                }

                // After you retreive the tracking script from the AddUetTags or GetUetTagsByIds operation, 
                // the next step is to add the UET tag tracking code to your website.
                // We will use the same UET tag for the remainder of this example.

                var tagId = uetTags[0].Id;                               
                
                // Add conversion goals that depend on the UET Tag Id retreived above.
                // Please note that you cannot delete conversion goals. If you want to stop 
                // tracking conversions for the goal, you can set the goal status to Paused.

                var conversionGoals = new ConversionGoal[]
                {
                    new DurationGoal
                    {
                        ConversionWindowInMinutes = 30,
                        CountType = ConversionGoalCountType.All,
                        MinimumDurationInSeconds = 60,
                        Name = "My Duration Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        Scope = EntityScope.Account,
                        Status = ConversionGoalStatus.Active,
                        TagId = tagId,
                    },
                    new EventGoal
                    {
                        GoalCategory = ConversionGoalCategory.Purchase,
                        // The type of user interaction you want to track.
                        ActionExpression = "play",
                        ActionOperator = ExpressionOperator.Contains,
                        // The category of event you want to track. 
                        CategoryExpression = "video",
                        CategoryOperator = ExpressionOperator.Contains,
                        ConversionWindowInMinutes = 30,
                        CountType = ConversionGoalCountType.All,
                        // The name of the element that caused the action.
                        LabelExpression = "trailer",
                        LabelOperator = ExpressionOperator.Contains,
                        Name = "My Event Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        Scope = EntityScope.Account,
                        Status = ConversionGoalStatus.Active,
                        TagId = tagId,
                        // A numerical value associated with that event. 
                        // Could be length of the video played etc.
                        Value = 5.00m,
                        ValueOperator = ValueOperator.Equals,
                    },
                    new PagesViewedPerVisitGoal
                    {
                        ConversionWindowInMinutes = 30,
                        CountType = ConversionGoalCountType.All,
                        MinimumPagesViewed = 5,
                        Name = "My Pages Viewed Per Visit Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        Scope = EntityScope.Account,
                        Status = ConversionGoalStatus.Active,
                        TagId = tagId,
                    },
                    new UrlGoal
                    {
                        GoalCategory = ConversionGoalCategory.Purchase,
                        ConversionWindowInMinutes = 30,
                        CountType = ConversionGoalCountType.All,
                        Name = "My Url Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        Scope = EntityScope.Account,
                        Status = ConversionGoalStatus.Active,
                        TagId = tagId,
                        UrlExpression = "contoso",
                        UrlOperator = ExpressionOperator.Contains
                    },
                    new AppInstallGoal
                    {
                        // You must provide a valid app platform and app store identifier, 
                        // otherwise this goal will not be added successfully. 
                        AppPlatform = "Windows",
                        AppStoreId = "AppStoreIdGoesHere",
                        ConversionWindowInMinutes = 30,
                        CountType = ConversionGoalCountType.All,
                        Name = "My App Install Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        // Account scope is not supported for app install goals. You can
                        // set scope to Customer or don't set it for the same result.
                        Scope = EntityScope.Customer,
                        Status = ConversionGoalStatus.Active,
                        // The TagId is inherited from the ConversionGoal base class,
                        // however, App Install goals do not use a UET tag.
                        TagId = null,
                    },
                };

                OutputStatusMessage("-----\nAddConversionGoals:");
                var addConversionGoalsResponse = await CampaignManagementExampleHelper.AddConversionGoalsAsync(
                    conversionGoals: conversionGoals);
                var goalIds = addConversionGoalsResponse.ConversionGoalIds.ToArray();
                BatchError[] conversionGoalErrors = addConversionGoalsResponse.PartialErrors.ToArray();
                OutputStatusMessage("ConversionGoalIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(goalIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(conversionGoalErrors);

                // Find the conversion goals that were added successfully. 

                List<long> conversionGoalIds = GetNonNullableIds(goalIds);

                var conversionGoalTypes =
                    ConversionGoalType.AppInstall |
                    ConversionGoalType.Duration |
                    ConversionGoalType.Event |
                    ConversionGoalType.PagesViewedPerVisit |
                    ConversionGoalType.Url;

                OutputStatusMessage("-----\nGetConversionGoalsByIds:");
                var getConversionGoalsResponse =  (await CampaignManagementExampleHelper.GetConversionGoalsByIdsAsync(
                        conversionGoalIds: conversionGoalIds,
                        conversionGoalTypes: conversionGoalTypes,
                        returnAdditionalFields: ConversionGoalAdditionalField.ViewThroughConversionWindowInMinutes));
                var getConversionGoals = getConversionGoalsResponse.ConversionGoals;
                conversionGoalErrors = getConversionGoalsResponse.PartialErrors.ToArray();
                OutputStatusMessage("ConversionGoals:");
                CampaignManagementExampleHelper.OutputArrayOfConversionGoal(getConversionGoals);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(conversionGoalErrors);

                // Update the conversion goals

                var updateConversionGoals = new ConversionGoal[]
                {
                    new DurationGoal
                    {
                        ConversionWindowInMinutes = 60,
                        CountType = ConversionGoalCountType.Unique,
                        // You can change the conversion goal type e.g. in this example an event goal
                        // had been created above at index 1. Now we are using the returned identifier
                        // at index 1 to update the type from EventGoal to DurationGoal.
                        Id = conversionGoalIds[1],
                        MinimumDurationInSeconds = 120,
                        Name = "My Updated Duration Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 10.00m,
                            CurrencyCode = null
                        },
                        // The Scope cannot be updated, even if you update the goal type.
                        // You can either send the same value or leave Scope empty.
                        Scope = EntityScope.Account,
                        Status = ConversionGoalStatus.Paused,
                        // You can update the tag as needed. In this example we will explicitly use the same UET tag.
                        // To keep the UET tag unchanged, you can also leave this element nil or empty.
                        TagId = tagId,
                    },
                    new EventGoal
                    {
                        // For both add and update conversion goal operations, you must include one or more  
                        // of the following events: 
                        // ActionExpression, CategoryExpression, LabelExpression, or Value.                        
                        // For example if you do not include ActionExpression during update, 
                        // any existing ActionOperator and ActionExpression settings will be deleted.
                        ActionExpression = null,
                        ActionOperator = null,
                        CategoryExpression = "video",
                        CategoryOperator = ExpressionOperator.Equals,
                        Id = conversionGoalIds[0],
                        // You cannot update the operator unless you also include the expression.
                        // The following attempt to update LabelOperator will result in an error.
                        LabelExpression = null,
                        LabelOperator = ExpressionOperator.Equals,
                        Name = "My Updated Event Goal",
                        Revenue = new ConversionGoalRevenue
                        {
                            Type = ConversionGoalRevenueType.FixedValue,
                            Value = 5.00m,
                            CurrencyCode = null
                        },
                        // You must specify the previous settings unless you want
                        // them replaced during the update conversion goal operation.
                        Value = 5.00m,
                        ValueOperator = ValueOperator.Equals,
                    },
                    new PagesViewedPerVisitGoal
                    {
                        Id = conversionGoalIds[2],
                        Name = "My Updated Pages Viewed Per Visit Goal",
                        // When updating a conversion goal, if the Revenue element is nil or empty then none 
                        // of the nested properties will be updated. However, if this element is not nil or empty 
                        // then you are effectively replacing any existing revenue properties. For example to delete 
                        // any previous revenue settings, set the Revenue element to an empty ConversionGoalRevenue object.
                        Revenue = new ConversionGoalRevenue(),
                    },
                    new UrlGoal
                    {
                        Id = conversionGoalIds[3],
                        Name = "My Updated Url Goal" + DateTime.UtcNow,
                        // If not specified during update, the previous Url settings are retained.
                        // If the expression is set, then the operator must also be set, and vice versa.
                        UrlExpression = "contoso",
                        UrlOperator = ExpressionOperator.BeginsWith
                    }
                };

                OutputStatusMessage("-----\nUpdateConversionGoals:");
                var updateConversionGoalsResponse = await CampaignManagementExampleHelper.UpdateConversionGoalsAsync(
                    conversionGoals: updateConversionGoals);
                conversionGoalErrors = updateConversionGoalsResponse.PartialErrors.ToArray();
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(conversionGoalErrors);

                OutputStatusMessage("-----\nGetConversionGoalsByIds:");
                getConversionGoals = (await CampaignManagementExampleHelper.GetConversionGoalsByIdsAsync(
                        conversionGoalIds: conversionGoalIds, 
                        conversionGoalTypes: conversionGoalTypes,
                        returnAdditionalFields: ConversionGoalAdditionalField.ViewThroughConversionWindowInMinutes)).ConversionGoals;
                getConversionGoals = getConversionGoalsResponse.ConversionGoals;
                conversionGoalErrors = getConversionGoalsResponse.PartialErrors.ToArray();
                OutputStatusMessage("ConversionGoals:");
                CampaignManagementExampleHelper.OutputArrayOfConversionGoal(getConversionGoals);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(conversionGoalErrors);
            }
            // 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 ConversionGoal 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.*;

import java.util.ArrayList;

public class ConversionGoals extends ExampleBase {

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

            // Before you can track conversions or target audiences using a remarketing list 
            // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
            // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

            // First you should call the GetUetTagsByIds operation to check whether a tag has already been created. 
            // You can leave the TagIds element null or empty to request all UET tags available for the customer.

            outputStatusMessage("-----\nGetUetTagsByIds:");
            GetUetTagsByIdsResponse getUetTagsByIdsResponse = CampaignManagementExampleHelper.getUetTagsByIds(
                    null);
            ArrayOfUetTag uetTags = getUetTagsByIdsResponse.getUetTags();
            ArrayOfBatchError uetTagErrors = getUetTagsByIdsResponse.getPartialErrors();
            outputStatusMessage("UetTags:");
            CampaignManagementExampleHelper.outputArrayOfUetTag(uetTags);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(uetTagErrors);

            // If you do not already have a UET tag that can be used, or if you need another UET tag, 
            // call the AddUetTags service operation to create a new UET tag. If the call is successful, 
            // the tracking script that you should add to your website is included in a corresponding 
            // UetTag within the response message.  

            if (uetTags == null || uetTags.getUetTags().size() < 1)
            {
                ArrayOfUetTag addUetTags = new ArrayOfUetTag();
                UetTag uetTag = new UetTag();
                uetTag.setDescription("My First Uet Tag");
                uetTag.setName("New Uet Tag");
                addUetTags.getUetTags().add(uetTag);
                        
                outputStatusMessage("-----\nAddUetTags:");
                AddUetTagsResponse addUetTagsResponse = CampaignManagementExampleHelper.addUetTags(addUetTags);
                uetTags = addUetTagsResponse.getUetTags();
                uetTagErrors = addUetTagsResponse.getPartialErrors();
                outputStatusMessage("UetTags:");
                CampaignManagementExampleHelper.outputArrayOfUetTag(uetTags);
                outputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.outputArrayOfBatchError(uetTagErrors);
            }

            if (uetTags == null || uetTags.getUetTags().size() < 1)
            {
                outputStatusMessage(String.format(
                    "You do not have any UET tags registered for CustomerId {0}.", 
                    authorizationData.getCustomerId())
                );
                return;
            }

            // After you retreive the tracking script from the AddUetTags or GetUetTagsByIds operation, 
            // the next step is to add the UET tag tracking code to your website.
            // We will use the same UET tag for the remainder of this example.

            java.lang.Long tagId = uetTags.getUetTags().get(0).getId();
            
            // Add conversion goals that depend on the UET Tag Id retreived above.
            // Please note that you cannot delete conversion goals. If you want to stop 
            // tracking conversions for the goal, you can set the goal status to Paused.

            ArrayOfConversionGoal addConversionGoals = new ArrayOfConversionGoal();
            
            DurationGoal addDurationGoal = new DurationGoal();
            addDurationGoal.setConversionWindowInMinutes(30);
            addDurationGoal.setCountType(ConversionGoalCountType.ALL);
            addDurationGoal.setMinimumDurationInSeconds(60);
            addDurationGoal.setName("My Duration Goal");
            ConversionGoalRevenue addDurationGoalRevenue = new ConversionGoalRevenue();
            addDurationGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            addDurationGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            addDurationGoalRevenue.setCurrencyCode(null);
            addDurationGoal.setRevenue(addDurationGoalRevenue);
            addDurationGoal.setScope(EntityScope.ACCOUNT);
            addDurationGoal.setStatus(ConversionGoalStatus.ACTIVE);
            addDurationGoal.setTagId(tagId);
            addConversionGoals.getConversionGoals().add(addDurationGoal);
            
            EventGoal addEventGoal = new EventGoal();
            addEventGoal.setGoalCategory(ConversionGoalCategory.PURCHASE);
            // The type of user interaction you want to track.
            addEventGoal.setActionExpression("play");
            addEventGoal.setActionOperator(ExpressionOperator.CONTAINS);
            // The category of event you want to track. 
            addEventGoal.setCategoryExpression("video");
            addEventGoal.setCategoryOperator(ExpressionOperator.CONTAINS);
            addEventGoal.setConversionWindowInMinutes(30);
            addEventGoal.setCountType(ConversionGoalCountType.ALL);
            // The name of the element that caused the action.
            addEventGoal.setLabelExpression("trailer");
            addEventGoal.setLabelOperator(ExpressionOperator.CONTAINS);
            addEventGoal.setName("My Event Goal");
            ConversionGoalRevenue addEventGoalRevenue = new ConversionGoalRevenue();
            addEventGoalRevenue.setType(ConversionGoalRevenueType.VARIABLE_VALUE);
            addEventGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            addEventGoalRevenue.setCurrencyCode(null);
            addEventGoal.setRevenue(addEventGoalRevenue);
            addEventGoal.setScope(EntityScope.ACCOUNT);
            addEventGoal.setStatus(ConversionGoalStatus.ACTIVE);
            addEventGoal.setTagId(tagId);
            // A numerical value associated with that event. 
            // Could be length of the video played etc.
            addEventGoal.setValue(new java.math.BigDecimal(5.00));
            addEventGoal.setValueOperator(ValueOperator.EQUALS);
            addConversionGoals.getConversionGoals().add(addEventGoal);
            
            PagesViewedPerVisitGoal addPagesViewedPerVisitGoal = new PagesViewedPerVisitGoal();
            addPagesViewedPerVisitGoal.setConversionWindowInMinutes(30);
            addPagesViewedPerVisitGoal.setCountType(ConversionGoalCountType.ALL);
            addPagesViewedPerVisitGoal.setMinimumPagesViewed(5);
            addPagesViewedPerVisitGoal.setName("My Pages Viewed Per Visit Goal");
            ConversionGoalRevenue addPagesViewedPerVisitGoalRevenue = new ConversionGoalRevenue();
            addPagesViewedPerVisitGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            addPagesViewedPerVisitGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            addPagesViewedPerVisitGoalRevenue.setCurrencyCode(null);
            addPagesViewedPerVisitGoal.setRevenue(addPagesViewedPerVisitGoalRevenue);
            addPagesViewedPerVisitGoal.setScope(EntityScope.ACCOUNT);
            addPagesViewedPerVisitGoal.setStatus(ConversionGoalStatus.ACTIVE);
            addPagesViewedPerVisitGoal.setTagId(tagId);
            addConversionGoals.getConversionGoals().add(addPagesViewedPerVisitGoal);
            
            UrlGoal addUrlGoal = new UrlGoal();
            addUrlGoal.setGoalCategory(ConversionGoalCategory.PURCHASE);
            addUrlGoal.setConversionWindowInMinutes(30);
            addUrlGoal.setCountType(ConversionGoalCountType.ALL);
            addUrlGoal.setName("My Url Goal");
            ConversionGoalRevenue addUrlGoalRevenue = new ConversionGoalRevenue();
            addUrlGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            addUrlGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            addUrlGoalRevenue.setCurrencyCode(null);
            addUrlGoal.setRevenue(addUrlGoalRevenue);
            addUrlGoal.setScope(EntityScope.ACCOUNT);
            addUrlGoal.setStatus(ConversionGoalStatus.ACTIVE);
            addUrlGoal.setUrlExpression("contoso");
            addUrlGoal.setUrlOperator(ExpressionOperator.CONTAINS);
            addUrlGoal.setTagId(tagId);
            addConversionGoals.getConversionGoals().add(addUrlGoal);
            
            AppInstallGoal addAppInstallGoal = new AppInstallGoal();
            // You must provide a valid app platform and app store identifier, 
            // otherwise this goal will not be added successfully. 
            addAppInstallGoal.setAppPlatform("Windows");
            addAppInstallGoal.setAppStoreId("AppStoreIdGoesHere");
            addAppInstallGoal.setConversionWindowInMinutes(30);
            addAppInstallGoal.setCountType(ConversionGoalCountType.ALL);
            addAppInstallGoal.setName("My App Install Goal");
            ConversionGoalRevenue addAppInstallGoalRevenue = new ConversionGoalRevenue();
            addAppInstallGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            addAppInstallGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            addAppInstallGoalRevenue.setCurrencyCode(null);
            addAppInstallGoal.setRevenue(addAppInstallGoalRevenue);
            // Account scope is not supported for app install goals. You can
            // set scope to Customer or don't set it for the same result.
            addAppInstallGoal.setScope(EntityScope.CUSTOMER);
            addAppInstallGoal.setStatus(ConversionGoalStatus.ACTIVE);
            // The TagId is inherited from the ConversionGoal base class,
            // however, App Install goals do not use a UET tag.
            addAppInstallGoal.setTagId(null);
            addConversionGoals.getConversionGoals().add(addAppInstallGoal);
            
            
            
            outputStatusMessage("-----\nAddConversionGoals:");
            AddConversionGoalsResponse addConversionGoalsResponse = CampaignManagementExampleHelper.addConversionGoals(
                    addConversionGoals);
            ArrayOfNullableOflong goalIds = addConversionGoalsResponse.getConversionGoalIds();
            ArrayOfBatchError conversionGoalErrors = addConversionGoalsResponse.getPartialErrors();
            outputStatusMessage("ConversionGoalIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(goalIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(conversionGoalErrors);

            // Find the conversion goals that were added successfully. 

            ArrayOflong conversionGoalIds = new ArrayOflong();
            for (java.lang.Long goalId : goalIds.getLongs())
            {
                if (goalId != null)
                {
                    conversionGoalIds.getLongs().add((long)goalId);
                }
            }

            outputStatusMessage("List of errors returned from AddConversionGoals (if any):");
            CampaignManagementExampleHelper.outputArrayOfBatchError(addConversionGoalsResponse.getPartialErrors());

            ArrayList<ConversionGoalType> conversionGoalTypes = new ArrayList<ConversionGoalType>();
            conversionGoalTypes.add(ConversionGoalType.APP_INSTALL);
            conversionGoalTypes.add(ConversionGoalType.DURATION);
            conversionGoalTypes.add(ConversionGoalType.EVENT);
            conversionGoalTypes.add(ConversionGoalType.PAGES_VIEWED_PER_VISIT);
            conversionGoalTypes.add(ConversionGoalType.URL);
            
            ArrayList<ConversionGoalAdditionalField> returnAdditionalFields = new ArrayList<ConversionGoalAdditionalField>();
            returnAdditionalFields.add(ConversionGoalAdditionalField.VIEW_THROUGH_CONVERSION_WINDOW_IN_MINUTES);
            
            outputStatusMessage("-----\nGetConversionGoalsByIds:");
            GetConversionGoalsByIdsResponse getConversionGoalsByIdsResponse = CampaignManagementExampleHelper.getConversionGoalsByIds(
                    conversionGoalIds, 
                    conversionGoalTypes,
                    returnAdditionalFields);
            ArrayOfConversionGoal getConversionGoals = getConversionGoalsByIdsResponse.getConversionGoals();
            conversionGoalErrors = getConversionGoalsByIdsResponse.getPartialErrors();
            outputStatusMessage("ConversionGoals:");
            CampaignManagementExampleHelper.outputArrayOfConversionGoal(getConversionGoals);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(conversionGoalErrors);

            // Update the conversion goals

            ArrayOfConversionGoal updateConversionGoals = new ArrayOfConversionGoal();
            DurationGoal updateDurationGoal = new DurationGoal();
            updateDurationGoal.setConversionWindowInMinutes(60);
            updateDurationGoal.setCountType(ConversionGoalCountType.UNIQUE);
            // You can change the conversion goal type e.g. in this example an event goal
            // had been created above at index 1. Now we are using the returned identifier
            // at index 1 to update the type from EventGoal to DurationGoal.
            updateDurationGoal.setId(conversionGoalIds.getLongs().get(1));
            updateDurationGoal.setMinimumDurationInSeconds(120);
            updateDurationGoal.setName("My Updated Duration Goal");
            ConversionGoalRevenue updateDurationGoalRevenue = new ConversionGoalRevenue();
            updateDurationGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            updateDurationGoalRevenue.setValue(new java.math.BigDecimal(10.00));
            updateDurationGoalRevenue.setCurrencyCode(null);
            updateDurationGoal.setRevenue(updateDurationGoalRevenue);
            // The Scope cannot be updated, even if you update the goal type.
            // You can either send the same value or leave Scope empty.
            updateDurationGoal.setScope(EntityScope.ACCOUNT);
            updateDurationGoal.setStatus(ConversionGoalStatus.PAUSED);
            // You can update the tag as needed. In this example we will explicitly use the same UET tag.
            // To keep the UET tag unchanged, you can also leave this element nil or empty.
            updateDurationGoal.setTagId(tagId);
            updateConversionGoals.getConversionGoals().add(updateDurationGoal);
            
            EventGoal updateEventGoal = new EventGoal();
            // For both add and update conversion goal operations, you must include one or more  
            // of the following events: 
            // ActionExpression, CategoryExpression, LabelExpression, or Value.

            // For example if you do not include ActionExpression during update, 
            // any existing ActionOperator and ActionExpression settings will be deleted.
            updateEventGoal.setActionExpression(null);
            updateEventGoal.setActionOperator(null);
            updateEventGoal.setCategoryExpression("video");
            updateEventGoal.setCategoryOperator(ExpressionOperator.EQUALS);
            updateEventGoal.setId(conversionGoalIds.getLongs().get(0));
            updateEventGoal.setConversionWindowInMinutes(30);
            updateEventGoal.setCountType(ConversionGoalCountType.ALL);
            // You cannot update the operator unless you also include the expression.
            // The following attempt to update LabelOperator will result in an error.
            updateEventGoal.setLabelExpression(null);
            updateEventGoal.setLabelOperator(ExpressionOperator.EQUALS);
            updateEventGoal.setName("My Updated Event Goal");
            ConversionGoalRevenue updateEventGoalRevenue = new ConversionGoalRevenue();
            updateEventGoalRevenue.setType(ConversionGoalRevenueType.FIXED_VALUE);
            updateEventGoalRevenue.setValue(new java.math.BigDecimal(5.00));
            updateEventGoalRevenue.setCurrencyCode(null);
            updateEventGoal.setRevenue(updateEventGoalRevenue);
            // You must specify the previous settings unless you want
            // them replaced during the update conversion goal operation.
            updateEventGoal.setValue(new java.math.BigDecimal(5.00));
            updateEventGoal.setValueOperator(ValueOperator.EQUALS);
            updateConversionGoals.getConversionGoals().add(updateEventGoal);
            
            PagesViewedPerVisitGoal updatePagesViewedPerVisitGoal = new PagesViewedPerVisitGoal();
            updatePagesViewedPerVisitGoal.setId(conversionGoalIds.getLongs().get(2));
            updatePagesViewedPerVisitGoal.setName("My Updated Pages Viewed Per Visit Goal");
            // When updating a conversion goal, if the Revenue element is nil or empty then none 
            // of the nested properties will be updated. However, if this element is not nil or empty 
            // then you are effectively replacing any existing revenue properties. For example to delete 
            // any previous revenue settings, set the Revenue element to an empty ConversionGoalRevenue object.
            ConversionGoalRevenue updatePagesViewedPerVisitGoalRevenue = new ConversionGoalRevenue();
            updatePagesViewedPerVisitGoal.setRevenue(updatePagesViewedPerVisitGoalRevenue);
            updateConversionGoals.getConversionGoals().add(updatePagesViewedPerVisitGoal);
            
            UrlGoal updateUrlGoal = new UrlGoal();
            updateUrlGoal.setId(conversionGoalIds.getLongs().get(3));
            updateUrlGoal.setName("My Updated Url Goal");
            // If not specified during update, the previous Url settings are retained.
            // If the expression is set, then the operator must also be set, and vice versa.
            updateUrlGoal.setUrlExpression("contoso");
            updateUrlGoal.setUrlOperator(ExpressionOperator.BEGINS_WITH);
            updateConversionGoals.getConversionGoals().add(updateUrlGoal);
            
            outputStatusMessage("-----\nUpdateConversionGoals:");
            UpdateConversionGoalsResponse updateConversionGoalsResponse = CampaignManagementExampleHelper.updateConversionGoals(
                    updateConversionGoals);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(updateConversionGoalsResponse.getPartialErrors());
            
            outputStatusMessage("-----\nGetConversionGoalsByIds:");
            getConversionGoalsByIdsResponse = CampaignManagementExampleHelper.getConversionGoalsByIds(
                    conversionGoalIds, 
                    conversionGoalTypes,
                    returnAdditionalFields);
            getConversionGoals = getConversionGoalsByIdsResponse.getConversionGoals();
            conversionGoalErrors = getConversionGoalsByIdsResponse.getPartialErrors();
            outputStatusMessage("ConversionGoals:");
            CampaignManagementExampleHelper.outputArrayOfConversionGoal(getConversionGoals);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(conversionGoalErrors);
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }     
}
<?php

use Microsoft\MsAds\Rest\ApiException;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddConversionGoalsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AddUetTagsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\AppInstallGoal;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalAdditionalField;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalCategory;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalCountType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalRevenue;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalRevenueType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalStatus;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ConversionGoalType;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\DeleteCampaignConversionGoalsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\DurationGoal;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\EntityScope;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\EventGoal;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ExpressionOperator;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\GetConversionGoalsByIdsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\GetUetTagsByIdsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\PagesViewedPerVisitGoal;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\UetTag;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\UpdateConversionGoalsRequest;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\UrlGoal;
use Microsoft\MsAds\Rest\Model\CampaignManagementService\ValueOperator;
use Microsoft\MsAds\Rest\Test\RestApiTestBase;

class ConversionGoalsTest extends RestApiTestBase
{

    protected array $conversionGoalTypes = array(
        ConversionGoalType::APP_INSTALL,
        ConversionGoalType::DURATION,
        ConversionGoalType::EVENT,
        ConversionGoalType::PAGES_VIEWED_PER_VISIT,
        ConversionGoalType::URL
    );

    protected array $returnAdditionalFields = array(
        ConversionGoalAdditionalField::VIEW_THROUGH_CONVERSION_WINDOW_IN_MINUTES,
        ConversionGoalAdditionalField::IS_EXTERNALLY_ATTRIBUTED,
        ConversionGoalAdditionalField::GOAL_CATEGORY
    );

    /**
     * @throws ApiException
     */
    public function testAddUetTags()
    {
        // Before you can track conversions or target audiences using a remarketing list
        // you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
        // For more information, please see Universal Event Tracking at https://go.microsoft.com/fwlink/?linkid=829965.

        // First you should call the GetUetTagsByIds operation to check whether a tag has already been created.
        // You can leave the TagIds element null or empty to request all UET tags available for the customer.
        print("-----\r\nGetUetTagsByIds:\r\n");
        $request = new GetUetTagsByIdsRequest([
            'TagIds' => null
        ]);
        $response = self::$campaignManagementServiceApi->getUetTagsByIds($request);
        $uetTags = $response->getUetTags() ?? [];
        print("UetTags:\r\n");
        print_r($uetTags);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertEmpty($response->getPartialErrors());

        // If you do not already have a UET tag that can be used, or if you need another UET tag,
        // call the AddUetTags service operation to create a new UET tag. If the call is successful,
        // the tracking script that you should add to your website is included in a corresponding
        // UetTag within the response message.

        if (count($uetTags) == 0) {
            print("-----\r\nAdding UET Tags:\r\n");

            $uetTag = new UetTag();
            $uetTag->setName("New UET Tag".self::generateRandomAlphaNumeric());
            $uetTag->setDescription("My First UET Tag".self::generateRandomAlphaNumeric());

            $request = new AddUetTagsRequest([
                'UetTags' => [$uetTag]
            ]);

            $response = self::$campaignManagementServiceApi->addUetTags($request);
            $uetTags = $response->getUetTags() ?? [];
            print("UetTags:\r\n");
            print_r($uetTags);
            print("PartialErrors:\r\n");
            print_r($response->getPartialErrors());
            self::assertEmpty($response->getPartialErrors());
        } else {
            print("-----\r\nUET Tag already exists\r\n");
        }
        self::assertNotEmpty($uetTags);

        return $uetTags[0]->getId();
    }

    /**
     * @depends testAddUetTags
     * @throws ApiException
     */
    public function testAddConversionGoals($tagId)
    {
        // Add conversion goals that depend on the UET Tag Id retrieved above.
        // Please note that you cannot delete conversion goals. If you want to stop
        // tracking conversions for the goal, you can set the goal status to Paused.
        print("-----\r\nAdding Conversion Goals:\r\n");

        $durationGoal = new DurationGoal();
        $durationGoal->setName("My Duration Goal".self::generateRandomAlphaNumeric());
        $durationGoal->setConversionWindowInMinutes(30);
        $durationGoal->setCountType(ConversionGoalCountType::ALL);
        $durationGoal->setMinimumDurationInSeconds(60);
        $durationGoal->setScope(EntityScope::ACCOUNT);
        $durationGoal->setStatus(ConversionGoalStatus::ACTIVE);
        $durationGoal->setTagId($tagId);

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(5.00);
        $durationGoal->setRevenue($revenue);


        $eventGoal = new EventGoal();
        // The type of user interaction you want to track.
        $eventGoal->setActionExpression("play");
        $eventGoal->setActionOperator(ExpressionOperator::CONTAINS);
        // The category of event you want to track.
        $eventGoal->setCategoryExpression("video");
        $eventGoal->setCategoryOperator(ExpressionOperator::CONTAINS);
        $eventGoal->setConversionWindowInMinutes(30);
        $eventGoal->setCountType(ConversionGoalCountType::ALL);
        // The name of the element that caused the action.
        $eventGoal->setLabelExpression("trailer");
        $eventGoal->setLabelOperator(ExpressionOperator::CONTAINS);
        $eventGoal->setName("My Event Goal".self::generateRandomAlphaNumeric());
        $eventGoal->setScope(EntityScope::ACCOUNT);
        $eventGoal->setStatus(ConversionGoalStatus::ACTIVE);
        $eventGoal->setTagId($tagId);
        // A numerical value associated with that event.
        // Could be length of the video played etc.
        $eventGoal->setValue(5.00);
        $eventGoal->setValueOperator(ValueOperator::EQUALS);
        // Required as of June 2021. Previously if you left this element nil or empty, the default category was set to None.
        $eventGoal->setGoalCategory(ConversionGoalCategory::ADD_TO_CART);

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(5.00);
        $eventGoal->setRevenue($revenue);

        $pagesViewedPerVisitGoal = new PagesViewedPerVisitGoal();
        $pagesViewedPerVisitGoal->setConversionWindowInMinutes(30);
        $pagesViewedPerVisitGoal->setCountType(ConversionGoalCountType::ALL);
        $pagesViewedPerVisitGoal->setMinimumPagesViewed(5);
        $pagesViewedPerVisitGoal->setName("My Pages Viewed Per Visit Goal".self::generateRandomAlphaNumeric());
        $pagesViewedPerVisitGoal->setScope(EntityScope::ACCOUNT);
        $pagesViewedPerVisitGoal->setStatus(ConversionGoalStatus::ACTIVE);
        $pagesViewedPerVisitGoal->setTagId($tagId);

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(5.00);
        $pagesViewedPerVisitGoal->setRevenue($revenue);


        $urlGoal = new UrlGoal();
        $urlGoal->setConversionWindowInMinutes(30);
        $urlGoal->setCountType(ConversionGoalCountType::ALL);
        $urlGoal->setName("My URL Goal".self::generateRandomAlphaNumeric());
        $urlGoal->setUrlExpression("contoso");
        $urlGoal->setUrlOperator(ExpressionOperator::CONTAINS);
        $urlGoal->setScope(EntityScope::ACCOUNT);
        $urlGoal->setStatus(ConversionGoalStatus::ACTIVE);
        $urlGoal->setTagId($tagId);
        $urlGoal->setGoalCategory(ConversionGoalCategory::ADD_TO_CART);

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(5.00);
        $urlGoal->setRevenue($revenue);

        $appInstallGoal = new AppInstallGoal();
        // You must provide a valid app platform and app store identifier,
        // otherwise this goal will not be added successfully.
        $appInstallGoal->setAppPlatform("Windows");
        $appInstallGoal->setAppStoreId("AppStoreIdGoesHere");
        $appInstallGoal->setConversionWindowInMinutes(30);
        $appInstallGoal->setCountType(ConversionGoalCountType::ALL);
        $appInstallGoal->setName("My App Install Goal".self::generateRandomAlphaNumeric());
        // Account scope is not supported for app install goals. You can
        // set scope to Customer or don't set it for the same result.
        $appInstallGoal->setScope(EntityScope::CUSTOMER);
        $appInstallGoal->setStatus(ConversionGoalStatus::ACTIVE);
        // The TagId is inherited from the ConversionGoal base class,
        // however, App Install goals do not use a UET tag.

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(5.00);
        $appInstallGoal->setRevenue($revenue);

        $request = new AddConversionGoalsRequest([
            'ConversionGoals' => [$durationGoal, $eventGoal, $pagesViewedPerVisitGoal, $urlGoal, $appInstallGoal]
        ]);

        $response = self::$campaignManagementServiceApi->addConversionGoals($request);
        $goalIds = $response->getConversionGoalIds() ?? [];
        print("ConversionGoalIds:\r\n");
        print_r($goalIds);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertEmpty($response->getPartialErrors());
        self::assertNotEmpty($goalIds);

        return array_values(array_filter($goalIds));
    }

    /**
     * @depends testAddConversionGoals
     * @throws ApiException
     */
    public function testGetConversionGoalsByIds($goalIds)
    {
        print("-----\r\nFetching Conversion Goals:\r\n");

        $request = new GetConversionGoalsByIdsRequest([
            'ConversionGoalIds' => $goalIds,
            'ConversionGoalTypes' => $this->conversionGoalTypes,
            'ReturnAdditionalFields' => $this->returnAdditionalFields
        ]);

        $response = self::$campaignManagementServiceApi->getConversionGoalsByIds($request);
        $conversionGoals = $response->getConversionGoals() ?? [];
        print("ConversionGoals:\r\n");
        print_r($conversionGoals);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertEmpty($response->getPartialErrors());
        self::assertNotEmpty($conversionGoals);
    }

    /**
     * @depends testAddConversionGoals
     * @depends testGetConversionGoalsByIds
     * @throws ApiException
     */
    public function testUpdateConversionGoals($goalIds)
    {
        print("-----\r\nUpdating Conversion Goals:\r\n");

        $updateDurationGoal = new DurationGoal();
        // You can change the conversion goal type e.g. in this example an event goal
        // had been created above at index 1. Now we are using the returned identifier
        // at index 1 to update the type from EventGoal to DurationGoal.
        $updateDurationGoal->setId($goalIds[1]);
        $updateDurationGoal->setName("Updated Duration Goal".self::generateRandomAlphaNumeric());
        $updateDurationGoal->setConversionWindowInMinutes(60);
        $updateDurationGoal->setCountType(ConversionGoalCountType::UNIQUE);
        $updateDurationGoal->setMinimumDurationInSeconds(120);
        $updateDurationGoal->setStatus(ConversionGoalStatus::PAUSED);
        // The Scope cannot be updated, even if you update the goal type.
        // You can either send the same value or leave Scope empty.
        $updateDurationGoal->setScope(EntityScope::ACCOUNT);

        $revenue = new ConversionGoalRevenue();
        $revenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $revenue->setValue(10.00);
        $updateDurationGoal->setRevenue($revenue);
        // You can update the tag as needed. In this example we will explicitly use the same UET tag.
        // To keep the UET tag unchanged, you can also leave this element nil or empty.
        // Update Event Goal

        $updateEventGoal = new EventGoal();
        // For both add and update conversion goal operations, you must include one or more
        // of the following event operator pairs:
        // (ActionOperator and ActionExpression), (CategoryOperator and CategoryExpression),
        // (LabelOperator and LabelExpression), (ValueOperator and Value).
        // Each event pair (e.g. ActionOperator and ActionExpression) is optional if you include
        // one or more of the other events.

        // For example if you do not include ActionOperator and ActionExpression during update,
        // any existing ActionOperator and ActionExpression settings will be deleted.
        $updateEventGoal->setId($goalIds[0]);
        $updateEventGoal->setCategoryExpression("video");
        $updateEventGoal->setCategoryOperator(ExpressionOperator::EQUALS);
        $updateEventGoal->setConversionWindowInMinutes(30);
        $updateEventGoal->setCountType(ConversionGoalCountType::ALL);
        // You cannot update the expression unless you also include the expression.
        // Likewise, you cannot update the operator unless you also include the expression.
        // The following attempt to update LabelOperator will result in an error.
        $updateEventGoal->setLabelExpression(null);
        $updateEventGoal->setLabelOperator(ExpressionOperator::EQUALS);
        $updateEventGoal->setName("My Updated Event Goal".self::generateRandomAlphaNumeric());
        // You must specify the previous settings for Value and ValueOperator,
        // unless you want them deleted during the update conversion goal operation.
        $updateEventGoal->setValue(5.00);
        $updateEventGoal->setValueOperator(ValueOperator::EQUALS);

        $eventGoalRevenue = new ConversionGoalRevenue();
        $eventGoalRevenue->setType(ConversionGoalRevenueType::FIXED_VALUE);
        $eventGoalRevenue->setValue(5.00);
        $updateEventGoal->setRevenue($eventGoalRevenue);

        // Update Pages Viewed Per Visit Goal
        $updatePagesViewedPerVisitGoal = new PagesViewedPerVisitGoal();
        $updatePagesViewedPerVisitGoal->setId($goalIds[2]);
        $updatePagesViewedPerVisitGoal->setName("My Updated Pages Viewed Per Visit Goal".self::generateRandomAlphaNumeric());
        // When updating a conversion goal, if the Revenue element is nil or empty then none
        // of the nested properties will be updated. However, if this element is not nil or empty
        // then you are effectively replacing any existing revenue properties. For example to delete
        // any previous revenue settings, set the Revenue element to an empty ConversionGoalRevenue object.

        $pagesViewedRevenue = new ConversionGoalRevenue();
        $updatePagesViewedPerVisitGoal->setRevenue($pagesViewedRevenue);

        // Update URL Goal
        $updateUrlGoal = new UrlGoal();
        $updateUrlGoal->setId($goalIds[3]);
        $updateUrlGoal->setName("My Updated Url Goal".self::generateRandomAlphaNumeric());
        // If not specified during update, the previous Url settings are retained.
        // If the expression is set, then the operator must also be set, and vice versa.
        $updateUrlGoal->setUrlExpression("contoso");
        $updateUrlGoal->setUrlOperator(ExpressionOperator::BEGINS_WITH);

        $request = new UpdateConversionGoalsRequest([
            'ConversionGoals' => [$updateDurationGoal, $updateEventGoal, $updatePagesViewedPerVisitGoal, $updateUrlGoal]
        ]);

        print("-----\r\nUpdateConversionGoals:\r\n");
        $response = self::$campaignManagementServiceApi->updateConversionGoals($request);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertNotEmpty($response->getPartialErrors());
        self::assertEquals('InvalidEventGoalLabelExpression', $response->getPartialErrors()[0]->getErrorCode());

        print("-----\r\nGetConversionGoalsByIds:\r\n");
        $request = new GetConversionGoalsByIdsRequest([
            'ConversionGoalIds' => $goalIds,
            'ConversionGoalTypes' => $this->conversionGoalTypes,
            'ReturnAdditionalFields' => $this->returnAdditionalFields
        ]);
        $response = self::$campaignManagementServiceApi->getConversionGoalsByIds($request);
        $conversionGoals = $response->getConversionGoals() ?? [];
        print("ConversionGoals:\r\n");
        print_r($conversionGoals);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertEmpty($response->getPartialErrors());
        self::assertNotEmpty($conversionGoals);
        return $goalIds;
    }

    /**
     * @depends testUpdateConversionGoals
     * @throws ApiException
     */
    public function deleteConversionGoals($goalIds)
    {
        print("-----\r\nDeleting Conversion Goals:\r\n");
        $request = new DeleteCampaignConversionGoalsRequest([
            'ConversionGoals' => $goalIds
        ]);
        $response = self::$campaignManagementServiceApi->deleteCampaignConversionGoals($request);
        print("PartialErrors:\r\n");
        print_r($response->getPartialErrors());
        self::assertEmpty($response->getPartialErrors());
    }
}
import uuid

from auth_helper import *
from openapi_client.models.campaign import *

def main(authorization_data):
    try:
        # Before you can track conversions or target audiences using a remarketing list 
        # you need to create a UET tag, and then add the UET tag tracking code to every page of your website.
        
        # First check whether a tag has already been created
        get_uet_tags_by_ids_request = GetUetTagsByIdsRequest(
            tag_ids=None  # None to get all UET tags
        )
        
        get_uet_tags_response = campaign_service.get_uet_tags_by_ids(
            get_uet_tags_by_ids_request=get_uet_tags_by_ids_request
        )
        uet_tags = get_uet_tags_response.UetTags

        # Create a new UET tag if none exists
        if not uet_tags:
            uet_tag = UetTag(
                description="My First Uet Tag",
                name="New Uet Tag"
            )
            
            add_uet_tags_request = AddUetTagsRequest(
                uet_tags=[uet_tag]
            )
            
            add_uet_tags_response = campaign_service.add_uet_tags(
                add_uet_tags_request=add_uet_tags_request
            )
            uet_tags = add_uet_tags_response.UetTags

        if not uet_tags:
            print(f"You do not have any UET tags registered for CustomerId {authorization_data.customer_id}")
            sys.exit(0)
        
        # Use the first UET tag for conversion goals
        tag_id = uet_tags[0].Id

        # Create conversion goals
        conversion_goals = []

        # Duration Goal
        duration_goal = DurationGoal(
            conversion_window_in_minutes=30,
            count_type=ConversionGoalCountType.ALL,
            minimum_duration_in_seconds=60,
            name="My Duration Goal" + str(uuid.uuid4()),
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=5.00
            ),
            scope=EntityScope.ACCOUNT,
            status=ConversionGoalStatus.ACTIVE,
            tag_id=tag_id
        )
        conversion_goals.append(duration_goal)

        # Event Goal
        event_goal = EventGoal(
            goal_category=ConversionGoalCategory.PURCHASE,
            action_expression="play",
            action_operator=ExpressionOperator.CONTAINS,
            category_expression="video",
            category_operator=ExpressionOperator.CONTAINS,
            conversion_window_in_minutes=30,
            count_type=ConversionGoalCountType.ALL,
            label_expression="trailer",
            label_operator=ExpressionOperator.CONTAINS,
            name="My Event Goal" + str(uuid.uuid4()),
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=5.00
            ),
            scope=EntityScope.ACCOUNT,
            status=ConversionGoalStatus.ACTIVE,
            tag_id=tag_id,
            value=5.00,
            value_operator=ValueOperator.EQUALS
        )
        conversion_goals.append(event_goal)

        # Pages Viewed Per Visit Goal
        pages_viewed_goal = PagesViewedPerVisitGoal(
            conversion_window_in_minutes=30,
            count_type=ConversionGoalCountType.ALL,
            minimum_pages_viewed=5,
            name="My Pages Viewed Per Visit Goal" + str(uuid.uuid4()),
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=5.00
            ),
            scope=EntityScope.ACCOUNT,
            status=ConversionGoalStatus.ACTIVE,
            tag_id=tag_id
        )
        conversion_goals.append(pages_viewed_goal)

        # URL Goal
        url_goal = UrlGoal(
            goal_category=ConversionGoalCategory.PURCHASE,
            conversion_window_in_minutes=30,
            count_type=ConversionGoalCountType.ALL,
            name="My Url Goal" + str(uuid.uuid4()),
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=5.00
            ),
            scope=EntityScope.ACCOUNT,
            status=ConversionGoalStatus.ACTIVE,
            tag_id=tag_id,
            url_expression="contoso",
            url_operator=ExpressionOperator.CONTAINS
        )
        conversion_goals.append(url_goal)

        # App Install Goal
        app_install_goal = AppInstallGoal(
            app_platform="Windows",
            app_store_id="AppStoreIdGoesHere",
            conversion_window_in_minutes=30,
            count_type=ConversionGoalCountType.ALL,
            name="My App Install Goal" + str(uuid.uuid4()),
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=5.00
            ),
            scope=EntityScope.CUSTOMER,  # Account scope not supported for app install goals
            status=ConversionGoalStatus.ACTIVE,
            tag_id=None  # App Install goals do not use UET tag
        )
        conversion_goals.append(app_install_goal)

        # Add the conversion goals
        add_conversion_goals_request = AddConversionGoalsRequest(
            conversion_goals=conversion_goals
        )
        
        add_conversion_goals_response = campaign_service.add_conversion_goals(
            add_conversion_goals_request=add_conversion_goals_request
        )
        goal_ids = add_conversion_goals_response.ConversionGoalIds

        # Get the successful conversion goal IDs
        conversion_goal_ids = [goal_id for goal_id in goal_ids if goal_id is not None]
        
        # Get the created conversion goals
        conversion_goal_types = ConversionGoalType.APPINSTALL | ConversionGoalType.DURATION |  ConversionGoalType.EVENT | ConversionGoalType.PAGESVIEWEDPERVISIT | ConversionGoalType.URL
        
        get_goals_request = GetConversionGoalsByIdsRequest(
            conversion_goal_ids=conversion_goal_ids,
            conversion_goal_types=conversion_goal_types,
            return_additional_fields=ConversionGoalAdditionalField.VIEWTHROUGHCONVERSIONWINDOWINMINUTES
        )
        
        get_goals_response = campaign_service.get_conversion_goals_by_ids(
            get_conversion_goals_by_ids_request=get_goals_request
        )

        # Update conversion goals
        update_conversion_goals = []

        # Update Duration Goal (previously Event Goal)
        update_duration_goal = DurationGoal(
            conversion_window_in_minutes=60,
            count_type=ConversionGoalCountType.UNIQUE,
            id=conversion_goal_ids[1],  # Using Event Goal's ID to change type
            minimum_duration_in_seconds=120,
            name="My Updated Duration Goal",
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.FIXEDVALUE,
                value=10.00
            ),
            scope=EntityScope.ACCOUNT,
            status=ConversionGoalStatus.PAUSED,
            tag_id=tag_id
        )
        update_conversion_goals.append(update_duration_goal)

        # Update Event Goal
        update_event_goal = EventGoal(
            category_expression="video",
            category_operator=ExpressionOperator.EQUALS,
            id=conversion_goal_ids[0],
            name="My Updated Event Goal",
            revenue=ConversionGoalRevenue(
                type=ConversionGoalRevenueType.VARIABLEVALUE,
                value=5.00
            ),
            value=5.00,
            value_operator=ValueOperator.GREATERTHAN
        )
        update_conversion_goals.append(update_event_goal)

        # Update Pages Viewed Per Visit Goal
        update_pages_viewed_goal = PagesViewedPerVisitGoal(
            id=conversion_goal_ids[2],
            name="My Updated Pages Viewed Per Visit Goal"
        )
        update_conversion_goals.append(update_pages_viewed_goal)

        # Update URL Goal
        update_url_goal = UrlGoal(
            id=conversion_goal_ids[3],
            name="My Updated Url Goal",
            url_expression="Contoso",
            url_operator=ExpressionOperator.BEGINSWITH
        )
        update_conversion_goals.append(update_url_goal)

        # Update the conversion goals
        update_goals_request = UpdateConversionGoalsRequest(
            conversion_goals=update_conversion_goals
        )
        
        campaign_service.update_conversion_goals(
            update_conversion_goals_request=update_goals_request
        )

        # Get updated goals
        get_updated_goals_response = campaign_service.get_conversion_goals_by_ids(
            get_conversion_goals_by_ids_request=get_goals_request
        )

    except Exception as ex:
        print(f"Error occurred: {str(ex)}")

if __name__ == '__main__':
    print("Loading the web service client...")

    authorization_data = AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    authenticate(authorization_data)

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

    main(authorization_data)

Siehe auch

Erste Schritte mit der Bing Ads-API