Export (0) Print
Expand All

Ad Rotation in PHP

The following example shows how to get and set the ad rotation of an ad group using the following Campaign 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

// You must pass the URL of the Campaign Management WSDL.

// Command line usage:
// php.exe SetAdRotation wsdl
//

// This program requires the following PHP extensions:
//    php_soap.dll
//    php_openssl.dll


// Disable WSDL caching.

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

// API credentials.

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

// Advertiser's account ID and customer ID.

$accountId = <accountidgoeshere>;
$customerId = <customeridgoeshere>;

// Ad group to apply the rotation policy to.
// Specify the campaign and ad group ID as a string.

$campaignId = "<campaignidgoeshere>";
$adGroupId = "<adgroupidgoeshere>";

// Campaign Management WSDL passed as argument

$wsdl = $argv[1];

$adRotations = null;


try
{
    $proxy = new ClientProxy($username, $password, $token, $accountId, $customerId, $wsdl);

    SetAdRotation($campaignId, $adGroupId, AdRotationType::RotateAdsEvenly, $proxy);

    $adRotations = GetAdRotation($campaignId, $adGroupId, $proxy);

    foreach ($adRotations->AdRotation as $adRotation)
    {
        printf("Ad group %s rotates %s.\n",
            $adGroupId,
            (AdRotationType::OptimizeForClicks == $adRotation->Type) ? "best performing ads" : "ads evenly");
    }
}
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";
    }
}

// Set the type of ad rotation to use for the specified ad group.

function SetAdRotation($campaignId, $adGroupId, $rotationType, $proxy)
{
    $request = new SetAdRotationToAdGroupsRequest();
    $response = null; // SetAdRotationToAdGroupsResponse

    // Set the request information.

    $request->CampaignId = $campaignId;
    $request->AdGroupAdRotations = array();

    $rotation = new AdGroupAdRotation();
    $rotation->AdGroupId = $adGroupId;
    $rotation->AdRotation = new AdRotation();
    $rotation->AdRotation->Type = $rotationType;
    $rotation->AdRotation->StartDate = null;
    $rotation->AdRotation->EndDate = null;

    $request->AdGroupAdRotations[] = $rotation;

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

        print "SetAdRotationToAdGroups 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->ApiFaultDetail))
        {
            print "ApiFaultDetail exception encountered\n";
            print "Tracking ID: ".$e->detail->ApiFaultDetail->TrackingId."\n";

            // Process any operation errors.

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

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            print("The user is not authorized to call this operation.\n");
                            break;

                        case 1100: //  CampaignServiceInvalidCampaignId
                            printf("The campaign ID %s is not valid.\n",
                                $campaignId);
                            break;

                        case 1201: //  CampaignServiceInvalidAdGroupId
                            print("All AdGroupAdRotation objects must specify an ad group ID.\n");
                            break;

                        case 1261: //  CampaignServiceAdGroupAdRotationArrayShouldNotBeNullOrEmpty
                            print("The list of AdGroupAdRotations cannot be null or emtpy.\n");
                            break;

                        case 1263: //  CampaignServiceCannotSetStartOrEndDateForAdRotation
                            print("The start and end dates must be null.\n");
                            break;

                        default:
                            printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                            break;
                    }
                }
            }

            if (!empty($e->detail->ApiFaultDetail->BatchErrors))
            {
                $errors = is_array($e->detail->ApiFaultDetail->BatchErrors->BatchError)
                        ? $e->detail->ApiFaultDetail->BatchErrors->BatchError
                        : array('BatchError' => $e->detail->ApiFaultDetail->BatchErrors->BatchError);

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        case 1201: //  CampaignServiceInvalidAdGroupId
                            printf("The ad group ID %s specified in AdGroupAdRotations[%d] is not valid.\n\n",
                                $request->AdGroupAdRotations[$error->Index]->AdGroupId,
                                $error->Index);
                            break;
                     
                        case 1214: //  CampaignServiceCannotCreateDuplicateAdGroup
                            printf("The list of AdGroupRotations must contain unique ad group IDs; " .
                                "ad group ID %s specified in AdGroupAdRotations[%d] already exists in the list.\n\n",
                                $request->AdGroupAdRotations[$error->Index]->AdGroupId,
                                $error->Index);
                            break;

                        default:
                            printf("Error code: %s (%d)\nIndex: %d\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Index, $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 type of ad rotation used by the specified ad group.

function GetAdRotation($campaignId, $adGroupoId, $proxy)
{
    $request = new GetAdRotationByAdGroupIdsRequest();
    $response = null; // GetAdRotationByAdGroupIdsResponse

    // Set the request information.

    $request->CampaignId = $campaignId;
    $request->AdGroupIds = array($adGroupoId);

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

        print("GetAdRotationByAdGroupIds 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->ApiFaultDetail))
        {
            print "ApiFaultDetail exception encountered\n";
            print "Tracking ID: ".$e->detail->ApiFaultDetail->TrackingId."\n";

            // Process any operation errors.

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

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        case 106: //  UserIsNotAuthorized
                            print("The user is not authorized to call this operation.\n");
                            break;

                        case 1218: //  CampaignServiceAdGroupIdsArrayShouldNotBeNullOrEmpty
                            print("The list of ad group IDs cannot be null or empty.\n");
                            break;

                        default:
                            printf("Error code: %s (%d)\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Message, $error->Details);
                            break;
                    }
                }
            }

            // Process any batch errors.

            if (!empty($e->detail->ApiFaultDetail->BatchErrors))
            {
                $errors = is_array($e->detail->ApiFaultDetail->BatchErrors->BatchError)
                        ? $e->detail->ApiFaultDetail->BatchErrors->BatchError
                        : array('BatchError' => $e->detail->ApiFaultDetail->BatchErrors->BatchError);

                foreach ($errors as $error)
                {
                    switch ($error->Code)
                    {
                        case 1201: //  CampaignServiceInvalidAdGroupId
                            printf("The ad group ID %s is not valid.\n\n",
                                $request->AdGroupIds[$error->Index]);
                            break;

                        case 1203: //  CampaignServiceDuplicateInAdGroupIds
                            printf("The list of ad group IDs must be unique; " .
                                "ad group ID %s already exists in the list.\n\n",
                                $request->AdGroupIds[$error->Index]);
                            break;

                        default:
                            printf("Error code: %s (%d)\nIndex: %d\nMessage: %s\nDetail: %s\n\n",
                                $error->ErrorCode, $error->Code, $error->Index, $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->AdRotationByAdGroupIds;
}


// Callbacks referenced in the SoapClient options.

// 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>';
}


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

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

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

    public function GetAccountId() { return $this->accountId; }
    public function GetCustomerId() { return $this->customerId; }
    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,
            'CustomerAccountId',
            $this->accountId
            );

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

        $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;
    }
}

// Defines the Campaign Management value sets used in ad rotation operations.

final class AdRotationType
{
    const OptimizeForClicks = 'OptimizeForClicks';
    const RotateAdsEvenly = 'RotateAdsEvenly';
}


// Defines the Campaign Management error objects that the operations can return.

final class AdApiError
{
    public $Code;
    public $Detail;
    public $ErrorCode;
    public $Message;
}

final class BatchError
{
    public $Code;
    public $Details;
    public $ErrorCode;
    public $Index;
    public $Message;
}

final class EditorialError
{
    public $Appealable;
    public $Code;
    public $DisapprovedText;
    public $ErrorCode;
    public $Index;
    public $Message;
    public $PublisherCountry;
}

final class OperationError
{
    public $Code;
    public $Details;
    public $ErrorCode;
    public $Message;
}

class ApplicationFault
{
    public $TrackingId;
}

final class ApiFaultDetail extends ApplicationFault
{
    public $BatchErrors;
    public $OperationErrors;
}

final class AdApiFaultDetail extends ApplicationFault
{
    public $Errors;
}

final class EditorialApiFaultDetail extends ApplicationFault
{
    public $BatchErrors;
    public $EditorialErrors;
    public $OperationErrors;
}


// Defines the Campaign Management data objects used in ad rotation operations.

final class AdRotation
{
    public $EndDate;
    public $StartDate;
    public $Type;
}

final class AdGroupAdRotation
{
    public $AdGroupId;
    public $AdRotation;
}


// Defines the Campaign Management operations used to get and set
// an ad group's ad roation policy.

final class GetAdRotationByAdGroupIdsRequest
{
    public $AdGroupIds;
    public $CampaignId;
}

final class GetAdRotationByAdGroupIdsResponse
{
    public $AdRotationByAdGroupIds;
}

final class SetAdRotationToAdGroupsRequest
{
    public $AdGroupAdRotations;
    public $CampaignId;
}

final class SetAdRotationToAdGroupsResponse
{
}

?>

Community Additions

Show:
© 2014 Microsoft