Export (0) Print
Expand All

Manage Users in PHP

The following example shows how to add, get, update, and delete a customer’s user with 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 ManageUsers.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\AddUserRequest;
use BingAds\CustomerManagement\GetUsersInfoRequest;
use BingAds\CustomerManagement\GetUserRequest;
use BingAds\CustomerManagement\UpdateUserRequest;
use BingAds\CustomerManagement\DeleteUserRequest;
use BingAds\CustomerManagement\User;
use BingAds\CustomerManagement\ContactInfo;
use BingAds\CustomerManagement\Address;
use BingAds\CustomerManagement\PersonName;
use BingAds\CustomerManagement\ApplicationType;
use BingAds\CustomerManagement\EmailFormat;
use BingAds\CustomerManagement\Email;
use BingAds\CustomerManagement\SecretQuestion;
use BingAds\CustomerManagement\UserRole;
use BingAds\CustomerManagement\UserLifeCycleStatus;

// 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>";


$customerId = <CustomerIdGoesHere>;


// 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);
    
    // Create a new user data object and add it to specified customer
    printf("Adding new User within CustomerId %d.\n\n", $customerId);
    $user = CreateUserData();
    $user->CustomerId = $customerId;
    $userId = AddUser($user, $proxy);
    
    // Get and print all active users managed by the specified customer
    printf("Printing all active users within CustomerId %d.\n\n", $customerId);
    $uInfos = GetUsers($customerId, $proxy);
    foreach ($uInfos->UserInfo as $uInfo)
    {
        $user = GetUserData($uInfo->Id, $proxy);
    
        if (is_null($user))
        {
            printf("Unable to access data for user %s (%d).\n\n", $uInfo->UserName, $uInfo->Id);
        }
        else
        {
            // Filter out the users
            // who have been deleted or are inactive.
    
            if ($user->UserLifeCycleStatus != UserLifeCycleStatus::Deleted && 
                    $user->UserLifeCycleStatus != UserLifeCycleStatus::Inactive)
                PrintUserData($user);
        }
    }
    
    // Ensure AddUser succeeded before updating and deleting the same user
    if ($userId > 0)
    {
        // Update the user and print updated details
        UpdateUser($userId, $proxy);
        $user = GetUserData($userId, $proxy);
        PrintUserData($user);
    
        // Delete the recently added and updated user
        DeleteUser($userId, $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";
    }
}

// Add a user to the specified customer.

function AddUser($user, $proxy)
{
    $request = new AddUserRequest();
    $response = null; // AddUserResponse
    
    try
    {
        // If you do not specify Role, the default is the
        // AdvertiserCampaignManager user role. If you do
        // not specify a list of account identifiers, the user
        // will have AdvertiserCampaignManager permission to
        // all accounts that the customer manages.
        
        $request->User = $user;
        $request->AccountIds = null;
        $request->Role = UserRole::AdvertiserCampaignManager;
        
        $response = $proxy->GetService()->AddUser($request);         
    }
    catch (SoapFault $e)
    {
        // Log this fault.

        print("AddUser 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 1339: // Username exists
                            printf("A user with username $s already exists.\n", $user->UserName);
                            
                        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)) ? $response->Id : -1;
}

// Get a list of the users
// who belong to the specified customer.

function GetUsers($customerId, $proxy)
{
    $request = new GetUsersInfoRequest();
    $response = null; // GetUsersInfoResponse
    
    try
    {
        $request->CustomerId = $customerId;
        
        $response = $proxy->GetService()->GetUsersInfo($request);     
    }
    catch (SoapFault $e)
    {
        // Log this fault.

        print("GetUsersInfo 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 $response->UsersInfo;
}

// Gets the user data object

function GetUserData($userId, $proxy)
{
    $request = new GetUserRequest();
    $response = null; // GetUserResponse

    try
    {
        $request->UserId = $userId;
      
        $response = $proxy->GetService()->GetUser($request);
    }
    catch (SoapFault $e)
    {
        // Log this fault.

        print("GetUser 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:
                            printf("You do not have permissions to access user %d.\n", $userId);
                            
                        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->User;
}

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

function UpdateUser($userId, $proxy)
{
    $request = new UpdateUserRequest();
    $response = null; // UpdateUserResponse

    $user = GetUserData($userId, $proxy);

    if(!is_null($user))
    {
        // You can update all elements that are not marked as
        // read-only on MSDN. Update the fields as appropriate.
        // This example updates
        // the user's secret question and answer.
        
        $user->SecretAnswer = "Bainbridge HS";
        $user->SecretQuestion = SecretQuestion::HighSchoolName;
        
        try
        {
            $request->User = $user;
                
            $response = $proxy->GetService()->UpdateUser($request);
                    
            printf("User %s (%d) was successfully updated.\n", $user->UserName, $userId);
        }
        catch (SoapFault $e)
        {
            // Log this fault.

            print("UpdateUser 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
                                        // user object again to get the new
                                        // time stamp and data. You can then show
                                        // the latest updates to the user to
                                        // confirm that they want to continue with
                                        // their update.
                                        // If so, update the elements as appropriate
                                        // and call the UpdateUser operation.

                                print "Another user updated the user.\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);
        }
    }
}

// Delete the specified user.
// The delete will fail if another user updates the user data
// between the time that you retrieved the user object and the
// time that you called the DeleteUser operation.

function DeleteUser($userId, $proxy)
{
    $request = new UpdateUserRequest();
    $response = null; // UpdateUserResponse

    $user = GetUserData($userId, $proxy);

    if(!is_null($user))
    {
        try
        {
            $request->UserId = $userId;
            $request->TimeStamp = $user->TimeStamp;

            $response = $proxy->GetService()->DeleteUser($request);
                
            printf("User %s (%d) was successfully deleted.\n", $user->UserName, $userId);
        }
        catch (SoapFault $e)
        {
            // Log this fault.

            print("DeleteUser 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:  
                                printf("You do not have permissions to delete user %s (%d).\n", $user->UserName, $userId);
                                    
                            case 510:   // You should consider retrieving the
                                        // user object again to get the new
                                        // time stamp and data, show the latest
                                        // updates to the user, and confirm that
                                        // they want to continue with their delete.
                                        // If so, call DeleteUser with the new time stamp.
                                printf("Another user updated user %s (%d) before you could delete it.\n", $user->Name, $userId);

                            case 1341:  // You cannot delete a user who is the
                                        // primary user of an account.
                                        // Before you can delete users, you must
                                        // remove them as the primary user of the
                                        // accounts. See the PrimaryUserId element
                                        // of the Account object.
                                printf("User %s (%d) has already been deleted.\n", $user->Name, $userId);
                                
                            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);
        }
    }
}

// Get the information of the user to add.

function CreateUserData()
{
    $user = new User();
    $contact = new ContactInfo();
    $address = new Address();
    $name = new PersonName();

    $address->Line1 = "1234 Washington Place";
    $address->Line2 = "Suite 1210";
    $address->City = "Woodinville";
    $address->StateOrProvince = "WA";
    $address->PostalCode = "98068";
    $address->CountryCode = "US";
    $contact->Address = $address;

    $contact->ContactByPhone = true;
    $contact->Phone1 = "(206) 555-0100 ext. 1234";
    $contact->Email = "kim@alpineskihouse.com";
    $contact->EmailFormat = EmailFormat::Text;

    $user->ContactInfo = $contact;
    $user->CustomerAppScope = ApplicationType::Advertiser;

    $name->FirstName = "Kim";
    $name->LastName = "Abercrombie";
    $user->Name = $name;

    $user->Password = "<NewPasswordGoesHere>";
    $user->SecretAnswer = "Michael";
    $user->SecretQuestion = SecretQuestion::FatherMiddleName;
    $user->UserName = "kaberc";
    
    return $user;
}

// Print some of the user data.

function PrintUserData($user)
{
    print "Name: " . GetUserName($user->Name) . "\n";
    print "ID: " . $user->Id . "\n";
    printf("Address: %s %s, %s %s\n", $user->ContactInfo->Address->Line1,
    $user->ContactInfo->Address->City,
    $user->ContactInfo->Address->StateOrProvince,
    $user->ContactInfo->Address->PostalCode);

    print "Contact by:"  . "\n";
    print "\tEmail at " . $user->ContactInfo->Email . "\n";

    if (!is_null($user->ContactInfo->ContactByPhone))
    {
        print "\tPhone at " . $user->ContactInfo->Phone1 . "\n";
    }
    if (!is_null($user->ContactInfo->ContactByPostalMail))
    {
        print "\tPostal mail sent to the above address\n";
    }

    print "Logon user name: " . $user->UserName  . "\n";
}

// Get the user's full name and return it as a string.

function GetUserName($person)
{
    $name = $person->FirstName;

    if (!is_null($person->MiddleInitial) && !empty($person->MiddleInitial))
    {
        $name = $name . " " . $person->MiddleInitial . ".";
    }

    $name = $name . " " . $person->LastName;

    return $name;
}

// 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:
© 2014 Microsoft