Partilhar via


Exemplo de Código de Contas de Utilizador de Pesquisa

Este exemplo demonstra como procurar contas que podem ser geridas pelo utilizador autenticado atual.

Sugestão

Utilize o seletor de idiomas no cabeçalho da documentação para escolher C#, Java, Php ou Python.

Para obter tokens de acesso e atualização para o seu utilizador do Microsoft Advertising e fazer a sua primeira chamada de serviço com a API de Anúncios do Bing, veja o Guia de Introdução . Vai querer rever o guia de Introdução e instruções para o seu idioma preferido, por exemplo, C#, Java, Php e Python.

Os ficheiros de suporte para exemplos de C#, Java, Php e Python estão disponíveis no GitHub. Pode clonar cada repositório ou reutilizar fragmentos conforme necessário.

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CustomerManagement;
using Microsoft.BingAds;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to search for accounts that can be managed by the current authenticated user.
    /// </summary>
    public class SearchUserAccounts : ExampleBase
    {
        public override string Description
        {
            get { return "Search Accounts for Current User | Customer Management V13"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                CustomerManagementExampleHelper CustomerManagementExampleHelper = new CustomerManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);
                
                OutputStatusMessage("-----\nGetUser:");
                var getUserResponse = await CustomerManagementExampleHelper.GetUserAsync(
                    userId: null);
                var user = getUserResponse.User;
                OutputStatusMessage("User:");
                CustomerManagementExampleHelper.OutputUser(user);
                OutputStatusMessage("CustomerRoles:");
                CustomerManagementExampleHelper.OutputArrayOfCustomerRole(getUserResponse.CustomerRoles);

                // Search for the accounts that the user can access.
                // To retrieve more than 100 accounts, increase the page size up to 1,000.
                // To retrieve more than 1,000 accounts you'll need to add paging.

                var predicate = new Predicate
                {
                    Field = "UserId",
                    Operator = PredicateOperator.Equals,
                    Value = user.Id.ToString()
                };

                var paging = new Paging
                {
                    Index = 0,
                    Size = 100
                };
                
                OutputStatusMessage("-----\nSearchAccounts:");
                var accounts = (await CustomerManagementExampleHelper.SearchAccountsAsync(
                    predicates: new[] { predicate },
                    ordering: null,
                    pageInfo: paging,
                    null))?.Accounts.ToArray();
                OutputStatusMessage("Accounts:");
                CustomerManagementExampleHelper.OutputArrayOfAdvertiserAccount(accounts);

                HashSet<long> distinctCustomerIds = new HashSet<long>();
                foreach (var account in accounts)
                {
                    distinctCustomerIds.Add(account.ParentCustomerId);
                }

                foreach (var customerId in distinctCustomerIds)
                {
                    // You can find out which pilot features the customer is able to use. 
                    // Each account could belong to a different customer, so use the customer ID in each account.
                    OutputStatusMessage("-----\nGetCustomerPilotFeatures:");
                    OutputStatusMessage(string.Format("Requested by CustomerId: {0}", customerId));
                    var featurePilotFlags = (await CustomerManagementExampleHelper.GetCustomerPilotFeaturesAsync(
                        customerId: customerId)).FeaturePilotFlags;
                    OutputStatusMessage("Customer Pilot flags:");
                    OutputStatusMessage(string.Join("; ", featurePilotFlags.Select(flag => string.Format("{0}", flag))));
                }
            }
            // 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 Customer Management service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CustomerManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CustomerManagement.ApiFault> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
    }
}
package com.microsoft.bingads.examples.v13;

import java.util.Arrays;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.customermanagement.*;
import java.util.ArrayList;
import java.util.HashSet;

public class SearchUserAccounts extends ExampleBase {
        
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData();
                         
            CustomerManagementExampleHelper.CustomerManagementService = new ServiceClient<ICustomerManagementService>(
                    authorizationData, 
                    API_ENVIRONMENT,
                    ICustomerManagementService.class);
            
            outputStatusMessage("-----\nGetUser:");
            GetUserResponse getUserResponse = CustomerManagementExampleHelper.getUser(
                    null);
            User user = getUserResponse.getUser();
            outputStatusMessage("User:");
            CustomerManagementExampleHelper.outputUser(user);
            outputStatusMessage("CustomerRoles:");
            CustomerManagementExampleHelper.outputArrayOfCustomerRole(getUserResponse.getCustomerRoles());

            // Search for the accounts that the user can access.
            // To retrieve more than 100 accounts, increase the page size up to 1,000.
            // To retrieve more than 1,000 accounts you'll need to add paging.
            
            ArrayOfPredicate predicates = new ArrayOfPredicate();
            Predicate predicate = new Predicate();
            predicate.setField("UserId");
            predicate.setOperator(PredicateOperator.EQUALS);
            predicate.setValue("" + user.getId());
            predicates.getPredicates().add(predicate);

            Paging paging = new Paging();
            paging.setIndex(0);
            paging.setSize(100);

            final SearchAccountsRequest searchAccountsRequest = new SearchAccountsRequest();
            searchAccountsRequest.setPredicates(predicates);
            searchAccountsRequest.setPageInfo(paging);
        
            outputStatusMessage("-----\nSearchAccounts:");
            ArrayOfAdvertiserAccount accounts = CustomerManagementExampleHelper.searchAccounts(
                    predicates, 
                    null, 
                    paging,
                    null).getAccounts();
            outputStatusMessage("Accounts:");
            CustomerManagementExampleHelper.outputArrayOfAdvertiserAccount(accounts);
            
            ArrayOflong customerIds = new ArrayOflong();
            for (AdvertiserAccount account : accounts.getAdvertiserAccounts())
            {
                customerIds.getLongs().add(account.getParentCustomerId());
            }            
            ArrayList<java.lang.Long> distinctCustomerIds = new ArrayList<java.lang.Long>(new HashSet<Long>(customerIds.getLongs()));
                        
            for (java.lang.Long customerId : distinctCustomerIds)
            {
                // You can find out which pilot features the customer is able to use. 
                // Each account could belong to a different customer, so use the customer ID in each account.
                outputStatusMessage("-----\nGetCustomerPilotFeatures:");
                outputStatusMessage(String.format("Requested by CustomerId: %s", customerId));
                ArrayOfint featurePilotFlags = CustomerManagementExampleHelper.getCustomerPilotFeatures(customerId).getFeaturePilotFlags();
                outputStatusMessage("Customer Pilot flags:");
                outputStatusMessage(Arrays.toString(featurePilotFlags.getInts().toArray()));
            }      
        } 
        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";

require_once __DIR__ . "/CustomerManagementExampleHelper.php";

include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";

use SoapVar;
use SoapFault;
use Exception;

// Specify the Microsoft\BingAds\V13\CustomerManagement classes that will be used.
use Microsoft\BingAds\V13\CustomerManagement\Paging;
use Microsoft\BingAds\V13\CustomerManagement\Predicate;
use Microsoft\BingAds\V13\CustomerManagement\PredicateOperator;

// 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\CustomerManagementExampleHelper;

try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();

    print("-----\r\nGetUser:\r\n");
    $getUserResponse = CustomerManagementExampleHelper::GetUser(
        null, 
        true
    );
    $user = $getUserResponse->User;
    print("User:");
    CustomerManagementExampleHelper::OutputUser($user);
    print("CustomerRoles:");
    CustomerManagementExampleHelper::OutputArrayOfCustomerRole($getUserResponse->CustomerRoles);
    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";
    // Search for the accounts that the user can access.
    // To retrieve more than 100 accounts, increase the page size up to 1,000.
    // To retrieve more than 1,000 accounts you'll need to add paging.

    $pageInfo = new Paging();
    $pageInfo->Index = 0;    // The first page
    $pageInfo->Size = 100;   // The first 100 accounts for this page of results    

    $predicate = new Predicate();
    $predicate->Field = "UserId";
    $predicate->Operator = PredicateOperator::Equals;
    $predicate->Value = $user->Id; 

    print("-----\r\nSearchAccounts:\r\n");
    $accounts = CustomerManagementExampleHelper::SearchAccounts(
        array($predicate),
        null,
        $pageInfo
    )->Accounts;
    print("Accounts:\r\n");
    CustomerManagementExampleHelper::OutputArrayOfAdvertiserAccount($accounts);

    $customerIds = array();
    foreach ($accounts->AdvertiserAccount as $account)
    {
        $customerIds[] = $account->ParentCustomerId;
    }
    $distinctCustomerIds = array_unique($customerIds, SORT_REGULAR);
    
    foreach ($distinctCustomerIds as $customerId)
    {
        // You can find out which pilot features the customer is able to use. 
        // Each account could belong to a different customer, so use the customer ID in each account.
        print("-----\r\nGetCustomerPilotFeatures:\r\n");
        printf("Requested by CustomerId: %s\r\n", $customerId);
        $featurePilotFlags = CustomerManagementExampleHelper::GetCustomerPilotFeatures(
            $customerId
        )->FeaturePilotFlags;
        print("Customer Pilot Flags:\r\n");
        print join('; ', $featurePilotFlags->int);
    }
}
catch (SoapFault $e)
{
    printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
    var_dump($e->detail);
    print "-----\r\nLast SOAP request/response:\r\n";
    print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
    // Ignore fault exceptions that we already caught.
    if ($e->getPrevious())
    { ; }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}
from auth_helper import *
from customermanagement_example_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):
    
    try:
        output_status_message("-----\nGetUser:")
        get_user_response=customer_service.GetUser(
            UserId=None
        )
        user = get_user_response.User
        customer_roles=get_user_response.CustomerRoles
        output_status_message("User:")
        output_user(user)
        output_status_message("CustomerRoles:")
        output_array_of_customerrole(customer_roles)

        # Search for the accounts that the user can access.
        # To retrieve more than 100 accounts, increase the page size up to 1,000.
        # To retrieve more than 1,000 accounts you'll need to add paging.

        accounts=search_accounts_by_user_id(customer_service, user.Id)

        customer_ids=[]
        for account in accounts['AdvertiserAccount']:
            customer_ids.append(account.ParentCustomerId)
        distinct_customer_ids = {'long': list(set(customer_ids))[:100]}

        for customer_id in distinct_customer_ids['long']:
            # You can find out which pilot features the customer is able to use. 
            # Each account could belong to a different customer, so use the customer ID in each account.
            output_status_message("-----\nGetCustomerPilotFeatures:")
            output_status_message("Requested by CustomerId: {0}".format(customer_id))
            feature_pilot_flags=customer_service.GetCustomerPilotFeatures(
                CustomerId=customer_id
            )
            output_status_message("Customer Pilot flags:")
            output_status_message("; ".join(str(flag) for flag in feature_pilot_flags['int']))
    
    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,
    )

    customer_service=ServiceClient(
        service='CustomerManagementService', 
        version=13,
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
    )
        
    authenticate(authorization_data)
        
    main(authorization_data)

See Also

Introdução à API de Anúncios do Bing