Get SOAP Header Elements in Ruby

The following example shows how to get your customer and account identifiers using the following Customer Management service operations.

This example has been developed and run within the environment described in Getting Started Using Ruby with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.



# Command line usage:
# ruby -W0 GetHeaders.rb
#
# Provide user credentials and a developer token below in the main control block
 
require 'soap/wsdlDriver'
require 'soap/header/simplehandler'

# This example WSDL is for the sandbox environment.
# Update the URL as needed when you use the production environment.
PROXY = "https://sharedservices.api.sandbox.bingads.microsoft.com/Api/CustomerManagement/V8/CustomerManagementService.svc?wsdl"
# This is the production WSDL
#PROXY = "https://sharedservices.adcenterapi.microsoft.com/Api/CustomerManagement/V8/CustomerManagementService.svc?wsdl"

# The namespace definitions.
NS_SHARED = "https://adcenter.microsoft.com/api/customermanagement"

# This is a helper class that is used
# to construct the request header.
class RequestHeader < SOAP::Header::SimpleHandler
    def initialize (element, value)
        super(XSD::QName.new(NS_SHARED, element))
            @element = element
            @value   = value
    end

    def on_simple_outbound
        @value
    end
end

def GetCustomers(
    username,
    password,
    developertoken,
    cNameFilter,
    topN,
    applicationScope)

    # Create the WSDL driver reference to access the Web service.
    wsdl = SOAP::WSDLDriverFactory.new(PROXY.to_s())
    
    service = wsdl.create_rpc_driver
    
    # For SOAP debugging information,
    # uncomment the following statement.
    #service.wiredump_dev = STDERR

    # Set the request header information.
    service.headerhandler << RequestHeader.new('DeveloperToken',
        "#{developertoken}")
    service.headerhandler << RequestHeader.new('UserName',
        "#{username}")
    service.headerhandler << RequestHeader.new('Password',
        "#{password}")

    # Create a string literal that contains the SOAP request body.
    getcustomersinforequest = %{
        <GetCustomersInfoRequest xmlns="https://adcenter.microsoft.com/api/customermanagement">
           <CustomerNameFilter>#{cNameFilter}</CustomerNameFilter>
           <TopN>#{topN}</TopN>
           <ApplicationScope>#{applicationScope}</ApplicationScope>
        </GetCustomersInfoRequest>
    }

    begin
        # Convert the string literal that contains
        # the SOAP request body to an XML document.
        request = REXML::Document.new(getcustomersinforequest)
        
        response = service.GetCustomersInfo(request)
      

    # Exception handling.
    rescue SOAP::FaultError => fault
        detail = fault.detail
        print "detail\n" + detail.to_s
        print "fault.detail\n" + fault.detail.to_s
        
        if detail.respond_to?('adApiFaultDetail')

            # Get the AdApiFaultDetail object.
            adApiErrors = detail.adApiFaultDetail.errors

            if !adApiErrors.respond_to?('each')
                adApiErrors = [adApiErrors]
            end

            adApiErrors.each do |error|
                print "Ad API error" \
                    " '#{error.message}' (#{error.code}) encountered.\n"
            end

        # Capture API exceptions.
        elsif detail.respond_to?('apiFault')
            operationErrors = detail.apiFault.operationErrors

            if !operationErrors.respond_to?('each')
                operationErrors = [operationErrors]
            end

            operationErrors.each do |opError|
                print "Operation error" \
                    " '#{opError.message}' (#{opError.code}) encountered.\n"
            end

        # Capture any generic SOAP exceptions.
        else
            print "Generic SOAP fault" \
                " '#{detail}' encountered.\n"
        end

    # Capture exceptions on the client that are unrelated to
    # the Bing Ads API. An example would be an 
    # out-of-memory condition on the client.
    rescue Exception => e
        puts "Error '#{e.exception.message}' encountered."
    end
    
    # Get the response list.
    customerList = (response == nil) ? nil : response.customersInfo.customerInfo

    # If only one object is returned,
    # convert the result to a list.
    if ! customerList.respond_to?('each')
        customerList = [customerList]
    end

    return customerList
end

def GetAccounts(
    username,
    password,
    developertoken,
    customerId,
    onlyParentAccounts)

    # Create the WSDL driver reference to access the Web service.
    wsdl = SOAP::WSDLDriverFactory.new(PROXY.to_s())
    
    service = wsdl.create_rpc_driver
    
    # For SOAP debugging information,
    # uncomment the following statement.
    #service.wiredump_dev = STDERR

    # Set the request header information.
    service.headerhandler << RequestHeader.new('DeveloperToken',
        "#{developertoken}")
    service.headerhandler << RequestHeader.new('UserName',
        "#{username}")
    service.headerhandler << RequestHeader.new('Password',
        "#{password}")

    # Create a string literal that contains the SOAP request body.
    getaccountsinforequest = %{
        <GetAccountsInfoRequest xmlns="https://adcenter.microsoft.com/api/customermanagement">
           <CustomerId>#{customerId}</CustomerId>
           <OnlyParentAccounts>#{onlyParentAccounts}</OnlyParentAccounts>
        </GetAccountsInfoRequest>
    }

    begin
        # Convert the string literal that contains
        # the SOAP request body to an XML document.
        request = REXML::Document.new(getaccountsinforequest)
        
        response = service.GetAccountsInfo(request)
        
    # Exception handling.
    rescue SOAP::FaultError => fault
        detail = fault.detail
        print "detail\n" + detail.to_s
        print "fault.detail\n" + fault.detail.to_s
        
        if detail.respond_to?('adApiFaultDetail')

            # Get the AdApiFaultDetail object.
            adApiErrors = detail.adApiFaultDetail.errors

            if !adApiErrors.respond_to?('each')
                adApiErrors = [adApiErrors]
            end

            adApiErrors.each do |error|
                print "Ad API error" \
                    " '#{error.message}' (#{error.code}) encountered.\n"
            end

        # Capture API exceptions.
        elsif detail.respond_to?('apiFault')
            operationErrors = detail.apiFault.operationErrors

            if !operationErrors.respond_to?('each')
                operationErrors = [operationErrors]
            end

            operationErrors.each do |opError|
                print "Operation error" \
                    " '#{opError.message}' (#{opError.code}) encountered.\n"
            end

        # Capture any generic SOAP exceptions.
        else
            print "Generic SOAP fault" \
                " '#{detail}' encountered.\n"
        end

    # Capture exceptions on the client that are unrelated to
    # the Bing Ads API. An example would be an 
    # out-of-memory condition on the client.
    rescue Exception => e
        puts "Error '#{e.exception.message}' encountered."
    end
    
    # Get the response list.
    accountList = (response == nil) ? nil : response.accountsInfo.accountInfo

    # If only one object is returned,
    # convert the result to a list.
    if ! accountList.respond_to?('each')
        accountList = [accountList]
    end

    return accountList
end


begin
    # Provide user credentials and a developer token
    username = "<UserNameGoesHere>"
    password = "<PasswordGoesHere>"
    developertoken = "<DeveloperTokenGoesHere>"

    print "Bing Ads API Header Elements for Current User\n\n"
    
    print "--------------------\n"
    print "Required Elements\n"
    print "--------------------\n"
    printf("UserName: %s\n", username)
    printf("Password: %s\n", password)
    printf("DeveloperToken: %s\n\n", developertoken)
        
    print "--------------------\n"
    print "Elements Required for Some Service Operations\n"
    print "--------------------\n"
    
    cInfos = GetCustomers(username, password, developertoken, "", 100, "Advertiser")
    
    if !(cInfos == nil) then
        cInfos.each do |cInfo|
            cId = cInfo['Id']
            printf("CustomerId: %d\n", cId)
            aInfos = GetAccounts(username, password, developertoken, cId, "true")
            
            if !(aInfos == nil) then
                aInfos.each do |aInfo|
                    aId = aInfo['Id']
                    printf("CustomerAccountId: %d\n", aId)
                end
                print "\n" # blank line between customers
            end
        end
    end
        
    print "--------------------\n"
    print "Elements Not Required and Reserved for Future Use\n"
    print "--------------------\n"
    print "ApplicationToken\n\n"
end


Community Additions

Show: