Create ads

PHP 5 using SOAP with the SoapClient class

This example shows a request using the Ads.add method, along with the result processing and output. To use the example, change the input data to specify the OAuth token and the ID of the group to create the new ad in. For a request on behalf of an agency, also specify the client login.

<?php
ini_set("soap.wsdl_cache_enabled", "0");

//--- Input data ----------------------------------------------------//
// Address of WSDL description of the Ads service for sending JSON requests (case-sensitive)
$wsdlUrl = 'https://api.direct.yandex.com/json/v5/ads?wsdl';
// OAuth token for the user that requests will be sent on behalf of
$token = 'TOKEN';
// Login of the advertising agency client
// Required parameter if requests are made on behalf of an advertising agency
$clientLogin = 'CLIENT_LOGIN';
// ID of the ad group to create the new ad in
$adGroupId = GROUP_ID;

//--- Preparing and executing the request -----------------------------------//
/// Creating the stream context: setting HTTP headers
 $streamOptions = stream_context_create(array(
  'http' => array(
      'header' => "Authorization: Bearer $token"."\r\n".    // OAuth token. The word Bearer must be used
                  "Client-Login: $clientLogin"."\r\n".      // Login of the advertising agency client
                  "Accept-Language: ru"                     // Response language
   ),
   /*
   // To fully conform to the HTTPS protocol, you can enable verification of the SSL certificate on the Yandex.Direct API server
   'ssl' => array(
      'verify_peer' => true,
      'cafile' => getcwd().DIRECTORY_SEPARATOR.'CA.pem' // Path to the local copy of the root SSL certificate
   )
   */
));

// Initializing the SOAP client
$client = new SoapClient($wsdlUrl,
   array(
      'trace'             => true,
      'exceptions'        => false,
      'features'          => SOAP_SINGLE_ELEMENT_ARRAYS,
      'cache_wsdl'        => WSDL_CACHE_NONE,
      'encoding'          => 'UTF-8',
      'stream_context'    => $streamOptions
    )
);

// Parameters of the request to the Yandex.Direct API server
$params = array(
   'Ads' => array(
      array(
         'AdGroupId' => $adGroupId,
         // Ad parameters
         'TextAd' => array(
            'Title' => 'Ad title',
            'Text' => 'Ad text',
            'Mobile' => 'NO',
            'Href' => 'http://www.yandex.ru'
         )
      )
   )
);

// Executing the request using the add method in the Ads service and receiving the response
$result = $client->add($params);

//--- Processing the request results ---------------------------//
if (is_soap_fault($result)) {
   $error = "SOAP Fault: faultcode: {$result->faultcode}, faultstring: {$result->faultstring}";
   if (isset($result->detail->FaultResponse)) { 
      $apiErr = $result->detail->FaultResponse;
      $error .= " detail: {$apiErr->errorCode} - {$apiErr->errorDetail} (RequestId: {$apiErr->requestId})";
   }
   echo $error;
}
else {
   // Extracting HTTP response headers: RequestId (the request ID) and Units (information about points)
   $headers = explode("\r\n", $client->__getLastResponseHeaders());
   foreach ($headers as $header) {
      if (preg_match('/(RequestId|Units):/', $header)) { echo "$header<br>"; }
   }

   // Outputting the result
   // Processing all items in the AddResults array, where each item corresponds to a single ad
   foreach ($result->AddResults as $item) {
      // Processing nested elements (either Errors or ID, or possibly Warnings)
      foreach ($item as $key => $value) {
         // If the Errors array is present, the ad was not created due to an error (there may be several errors)
         if ($key == 'Errors') {
            foreach ($value as $errItem) { echo "Error: {$errItem->Code} - {$errItem->Message} ({$errItem->Details})<br>"; }
         }
         else {
            // If the Warnings array is present, the ad was created, but there are warnings (there may be several warnings)
            if ($key == 'Warnings') {
               foreach ($value as $warItem) { echo "Warning: {$warItem->Code} - {$warItem->Message} ({$warItem->Details})<br>"; }
            }
            echo "Created ad №{$value}<br>";
         }
      }
   }
}

//--- Debugging information ---------------------------------------------//
//echo "<hr>Request header:<pre>".$client->__getLastRequestHeaders()."</pre>";
//echo "Request:<pre>".htmlspecialchars($client->__getLastRequest())."</pre>";
//echo "Response header:<pre>".$client->__getLastResponseHeaders()."</pre>";
//echo "Response:<pre>".htmlspecialchars($client->__getLastResponse())."</pre>";
?>