Export (0) Print
Expand All

Manage Customers in PHP

The following example shows how to get and update customers using the following Customer Management service operations.

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

To download the PHP classes included in the sample, see PHP Production Classes for Bing Ads API.

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.


<?php

// Command line usage:
// php.exe ManageCustomers.php
//

// Include the BingAds\CustomerManagement namespaced class file available
// for download at http://go.microsoft.com/fwlink/?LinkId=296529
include 'bingads\CustomerManagementClasses.php';

// Specify the BingAds\CustomerManagement objects that will be used.
use BingAds\CustomerManagement\GetCustomersInfoRequest;
use BingAds\CustomerManagement\ApplicationType;
use BingAds\CustomerManagement\GetCustomerRequest;
use BingAds\CustomerManagement\UpdateCustomerRequest;

// Disable WSDL caching.

ini_set("soap.wsdl_cache_enabled", "0");
ini_set("soap.wsdl_cache_ttl", "0");

// Specify your credentials.

$username = "<usernamegoeshere>";
$password = "<passwordgoeshere>";
$token = "<devtokengoeshere>";


// Customer Management WSDL for Sandbox
// Replace with production WSDL below as needed
$wsdl = "https://sharedservices.api.sandbox.bingads.microsoft.com/Api/CustomerManagement/v8/CustomerManagementService.svc?wsdl";
//$wsdl = "https://sharedservices.adcenterapi.microsoft.com/Api/CustomerManagement/v8/CustomerManagementService.svc?wsdl";

try
{
    $proxy = new ClientProxy($username, $password, $token, $wsdl);
    
    // To filter the list of customers for a specific
    // customer or set of customers whose names begin
    // with the same specific sequence of characters,
    // replace string.empty with the customer’s
    // name or sequence of characters.
    
    $filter = "";
    $cInfos = GetCustomers($filter, $proxy);

    // Print a list of all customers managed and requested by the user
    printf("Printing all Customers with filter: %s.\n\n", $filter);
    foreach ($cInfos->CustomerInfo as $cInfo)
    {
        if (!is_null($cInfo))
        {
            $customer = GetCustomerData($cInfo->Id, $proxy);
            
            if (is_null($customer))
            {
                printf("Unable to access data for customer %s (%d)\n", $cInfo->Name, $cInfo->Id);
            }
            else
            {
                PrintCustomerData($customer);
            }
        }
        print "\n";
    }
    
    // Select one customer identifier to demonstrate customer update
    $id = $cInfos->CustomerInfo[0]->Id;
    if (!is_null($id))
    {
        $customerId = $id;
    
        printf("Printing Customer with identifier %d.\n\n", $customerId);
        PrintCustomerData(GetCustomerData($customerId, $proxy));
    
        UpdateCustomer($customerId, $proxy);
    
        printf("Printing Customer with identifier %d after update try.\n\n", $customerId);
        PrintCustomerData(GetCustomerData($customerId, $proxy));
    }
    
}
catch (SoapFault $e)
{
    print $e->getMessage()."\n\n";
}
catch (Exception $e)
{
    if ($e->getPrevious())
    {
        ; // Ignore fault exceptions that we already caught.
    }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}

// Gets the advertising customers that the user
// has access to and that match the filter criteria.

function GetCustomers($filter, $proxy)
{
    $request = new GetCustomersInfoRequest();
    $response = null; // GetCustomersInfoResponse
    
    try
    {
        // Specify the filter criteria.
        // If you do not specify the application scope filter,
        // the list will contain both advertising and publishing
        // customers (if you have customers of both types).
        
        // If the nameFilter parameter is not an empty string,
        // the operation returns customers
        // whose name begins with the specified filter string.
        
        // You must specify the number of customers that
        // the operation returns. For example, to get the first
        // 100 customers that match the filter, set TopN to 100.
        $request->ApplicationScope = ApplicationType::Advertiser;
        $request->CustomerNameFilter = $filter;
        $request->TopN = 100;
        
        $response = $proxy->GetService()->GetCustomersInfo($request);
   
        if (empty($response->CustomersInfo))
        {
            print "There are no customers that match the specified filter criteria.\n";
        }          
    }
    catch (SoapFault $e)
    {
        // Log this fault.

        print("GetCustomersInfo failed with the following faults:\n");

        if (isset($e->detail->AdApiFaultDetail))
        {
            print "AdApiFaultDetail exception encountered\n";
            print "Tracking ID: ".$e->detail->AdApiFaultDetail->TrackingId ."\n";

            // Process any system errors.

            $errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
                    ? $e->detail->AdApiFaultDetail->Errors->AdApiError
                    : array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);

            foreach ($errors as $error)
            {
                if (105 == $error->Code) //  InvalidCredentials
                {
                    print "The specified credentials are not valid or the account is inactive.\n";
                }
                else
                {
                    printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                        $error->ErrorCode, $error->Code, $error->Message, $error->Detail);
                }
            }
        }
        elseif (isset($e->detail->ApiFault))
        {
            print "ApiFault exception encountered\n";
            print "Tracking ID: ".$e->detail->ApiFault->TrackingId."\n";

            // Process any operation errors.

            if (!empty($e->detail->ApiFault->OperationErrors))
            {
                $errors = is_array($e->detail->ApiFault->OperationErrors->OperationError)
                        ? $e->detail->ApiFault->OperationErrors->OperationError
                        : array('OperationError' => $e->detail->ApiFault->OperationErrors->OperationError);

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        default:
                            printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                            break;
                    }
                }
            }
        }
        else
        {
            print $e->getCode()." ".$e->getMessage()."\n\n";

            // Output the last request/response.

            print "\nLast SOAP request/response:\n";
            print $proxy->GetWsdl()."\n";
            print $proxy->GetService()->__getLastRequest()."\n";
            print $proxy->GetService()->__getLastResponse()."\n";
        }

        throw new Exception("", 0, $e);
    }
    
    return $response->CustomersInfo;
}

// Get the customer data associated with
// the specified customer identifier.

function GetCustomerData($customerId, $proxy)
{
    $request = new GetCustomerRequest();
    $response = null; // GetCustomerResponse
    
    try
    {
        $request->CustomerId = $customerId;
        
        $response = $proxy->GetService()->GetCustomer($request);  
    }
    catch (SoapFault $e)
    {
        // Log this fault.

        print("GetCustomer failed with the following faults:\n");

        if (isset($e->detail->AdApiFaultDetail))
        {
            print "AdApiFaultDetail exception encountered\n";
            print "Tracking ID: ".$e->detail->AdApiFaultDetail->TrackingId ."\n";

            // Process any system errors.

            $errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
                    ? $e->detail->AdApiFaultDetail->Errors->AdApiError
                    : array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);

            foreach ($errors as $error)
            {
                printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                        $error->ErrorCode, $error->Code, $error->Message, $error->Detail);
            }
        }
        elseif (isset($e->detail->ApiFault))
        {
            print "ApiFault exception encountered\n";
            print "Tracking ID: ".$e->detail->ApiFault->TrackingId."\n";

            // Process any operation errors.

            if (!empty($e->detail->ApiFault->OperationErrors))
            {
                $errors = is_array($e->detail->ApiFault->OperationErrors->OperationError)
                        ? $e->detail->ApiFault->OperationErrors->OperationError
                        : array('OperationError' => $e->detail->ApiFault->OperationErrors->OperationError);

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        default:
                            printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                            break;
                    }
                }
            }
        }
        else
        {
            print $e->getCode()." ".$e->getMessage()."\n\n";

            // Output the last request/response.

            print "\nLast SOAP request/response:\n";
            print $proxy->GetWsdl()."\n";
            print $proxy->GetService()->__getLastRequest()."\n";
            print $proxy->GetService()->__getLastResponse()."\n";
        }

        throw new Exception("", 0, $e);
    }

    return (is_null($response)) ? null : $response->Customer;
}

// Update the customer's data.
// The update will fail if another user updated the
// customer data between the time you retrieved the customer
// object and the time you called the UpdateCustomer operation.

function UpdateCustomer($customerId, $proxy)
{
    $request = new UpdateCustomerRequest();
    $response = null; // UpdateCustomerResponse

    $customer = GetCustomerData($customerId, $proxy);
    
    if(!is_null($customer))
    {
        // You can update all elements
        // that are not marked as read-only on MSDN.
        // Update the fields as appropriate.
        // This example updates the customer’s address.
        
        $customer->CustomerAddress->Line1 = "6789 Rollingstone";
        $customer->CustomerAddress->City = "Redmond";
        $customer->CustomerAddress->PostalCode = "98444";
        
        try
        {
            $request->Customer = $customer;
             
            $response = $proxy->GetService()->UpdateCustomer($request);
            printf("Customer %s (%d) was successfully updated.\n\n", $customer->Name, $customerId);
        }
        catch (SoapFault $e)
        {
            // Log this fault.
        
            print("UpdateCustomer failed with the following faults:\n");
        
            if (isset($e->detail->AdApiFaultDetail))
            {
                print "AdApiFaultDetail exception encountered\n";
                print "Tracking ID: ".$e->detail->AdApiFaultDetail->TrackingId ."\n";
        
                // Process any system errors.
        
                $errors = is_array($e->detail->AdApiFaultDetail->Errors->AdApiError)
                ? $e->detail->AdApiFaultDetail->Errors->AdApiError
                : array('AdApiError' => $e->detail->AdApiFaultDetail->Errors->AdApiError);
        
                foreach ($errors as $error)
                {
                    printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                    $error->ErrorCode, $error->Code, $error->Message, $error->Detail);
                }
            }
            elseif (isset($e->detail->ApiFault))
            {
                print "ApiFault exception encountered\n";
                print "Tracking ID: ".$e->detail->ApiFault->TrackingId."\n";
        
                // Process any operation errors.
        
                if (!empty($e->detail->ApiFault->OperationErrors))
                {
                    $errors = is_array($e->detail->ApiFault->OperationErrors->OperationError)
                    ? $e->detail->ApiFault->OperationErrors->OperationError
                    : array('OperationError' => $e->detail->ApiFault->OperationErrors->OperationError);
        
                    foreach ($errors as $error)
                    {
                        switch ($error->Code)
                        {
                            case 1001: // You cannot update the read-only
                                       // fields, such as the status fields.
                                print "You do not have permissions to update one or more of the fields.\n";
                            
                            case 510:  // You should consider retrieving
                                       // the customer object again to get 
                                       // the new time stamp and data.
                                       // You can then show the latest
                                       // updates to the user and confirm
                                       // that they want to continue with
                                       // their update. If so, update the
                                       // elements as appropriate, and call
                                       // the UpdateCustomer operation.
                                print "Another user updated the customer.\n";
                            
                            default:
                                printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                                break;
                        }
                    }
                }
            }
            else
            {
                print $e->getCode()." ".$e->getMessage()."\n\n";
        
                // Output the last request/response.
        
                print "\nLast SOAP request/response:\n";
                print $proxy->GetWsdl()."\n";
                print $proxy->GetService()->__getLastRequest()."\n";
                print $proxy->GetService()->__getLastResponse()."\n";
            }
        
            throw new Exception("", 0, $e);
        }
    }
}

// Print the contents of the Customer object.

function PrintCustomerData($customer)
{
    printf("Customer: %s (%d)\n", $customer->Name, $customer->Id);
    printf("Address: %s %s, %s %s\n", $customer->CustomerAddress->Line1,
    $customer->CustomerAddress->City,
    $customer->CustomerAddress->StateOrProvince,
    $customer->CustomerAddress->PostalCode);
    print "Status: " . $customer->CustomerLifeCycleStatus . "\n";
    print "Financial status: " . $customer->CustomerFinancialStatus . "\n";
    print "Service level: " . $customer->ServiceLevel . "\n";
    print "Industry: " . $customer->Industry . "\n";
    print "MarketCountry: " . $customer->MarketCountry . "\n";
    print "MarketLanguage: " . $customer->MarketLanguage . "\n";
    print "Last modified by: " . $customer->LastModifiedByUserId . "\n";
    print "\n\n";
}

// Define the proxy class for the Customer Management service.

Class ClientProxy
{
    private $username;
    private $password;
    private $developerToken;
    private $wsdlUrl;
    private $service;
    private $namespace;

    public function __construct($username, $password, $token, $wsdl)
    {
        $this->username = $username;
        $this->password = $password;
        $this->developerToken = $token;
        $this->wsdlUrl = $wsdl;
        $this->service = $this->GetProxy($wsdl);
    }

    public function GetService() { return $this->service; }
    public function GetNamespace() { return $this->namespace; }
    public function GetWsdl() { return $this->wsdlUrl; }

    // This function gets the namespace from the WSDL, so you do
    // not have to hardcode it in the client.

    private function GetServiceNamespace($url)
    {
        $doc = new DOMDocument;
        $doc->Load($url);

        $xpath = new DOMXPath($doc);
        $query = "/*/@targetNamespace";

        $attrs = $xpath->query($query);

        // The query will return only one node in the node list.

        foreach($attrs as $attr)
        {
            $namespace = $attr->value;
        }

        return $namespace;
    }

    private function GetProxy($wsdl)
    {
        $this->namespace = $this->GetServiceNamespace($wsdl);

        // Define the SOAP headers. Customer ID is required
        // to get editorial reasons.

        $headers = array();

        $headers[] = new SoapHeader(
                $this->namespace,
                'DeveloperToken',
                $this->developerToken
        );

        $headers[] = new SoapHeader(
                $this->namespace,
                'UserName',
                $this->username
        );

        $headers[] = new SoapHeader(
                $this->namespace,
                'Password',
                $this->password
        );

        // By default, PHP does not return single item arrays as an array type.
        // To force PHP to always return an array for an array type in the
        // response, specify the SOAP_SINGLE_ELEMENT_ARRAYS feature.

        $options = array(
                'trace' => TRUE,
                'exceptions' => TRUE,
                'features' => SOAP_SINGLE_ELEMENT_ARRAYS,

                // Map long type to string type. For details, see
                // from_long_xml and to_long_xml callbacks.

                'typemap' => array(
                        array(
                                'type_ns' => 'http://www.w3.org/2001/XMLSchema',
                                'type_name' => 'long',
                                'to_xml' => 'to_long_xml',
                                'from_xml' => 'from_long_xml'
                        ),
                )
        );

        $proxy = @new SOAPClient($this->wsdlUrl, $options);

        $proxy->__setSoapHeaders($headers);

        return $proxy;
    }
}

// Converts long types found in SOAP responses to string types in PHP.

function from_long_xml($xmlFragmentString)
{
    return (string)strip_tags($xmlFragmentString);
}

// Converts PHP string types to long types in SOAP requests.

function to_long_xml($longVal)
{
    return '<long>' . $longVal . '</long>';
}

?>




Community Additions

Show:
© 2015 Microsoft