Create ads

PHP 5 using JSON with the cURL library

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
//--- Input data ----------------------------------------------------//
// Address of the Ads service for sending JSON requests (case-sensitive)
$url = 'https://api.direct.yandex.com/json/v5/ads';
// 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 -----------------------------------//
// Setting the request HTTP headers
$headers = array(
   "Authorization: Bearer $token"                   // OAuth token. The word Bearer must be used
   "Client-Login: $clientLogin",                      // Login of the advertising agency client
   "Accept-Language: en",                             // Language for response messages
   "Content-Type: application/json; charset=utf-8"    // Data type and request encoding
);

// Parameters for the request to the Yandex.Direct API server
$params = array(
   'method' => 'add',                                 // Method to use
   'params' => array(
      'Ads' => array(
         array(
            'AdGroupId' => $adGroupId,
            'TextAd' => array(                        // Ad parameters
               'Title' => 'Ad title',
               'Text' => 'Ad text',
               'Mobile' => 'NO',
               'Href' => 'http://www.yandex.ru'
            )
         )
      )
   )
);
// Converting input parameters to JSON
$body = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// Initializing cURL
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);

/*
To fully conform to the HTTPS protocol, you can enable verification of the SSL certificate on the Yandex.Direct API server.
To enable verification, set the CURLOPT_SSL_VERIFYPEER option to true. Also comment out the line with the CURLOPT_CAINFO option and specify the path to the local copy of the root SSL certificate.
*/
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CURLOPT_CAINFO, getcwd().'\CA.pem');

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

// Executing the request and getting the result
$result = curl_exec($curl);

//--- Processing the request results ---------------------------//
if(!$result) { echo ('cURL error: '.curl_errno($curl).' - '.curl_error($curl)); }
else {
   // Separating the HTTP headers and the response body
   $responseHeadersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
   $responseHeaders = substr($result, 0, $responseHeadersSize);
   $responseBody = substr($result, $responseHeadersSize);

   if (curl_getinfo($curl, CURLINFO_HTTP_CODE) != 200) { echo "HTTP error: ".curl_getinfo($curl, CURLINFO_HTTP_CODE); }
   else {
      // Transforming the response from JSON
      $responseBody = json_decode($responseBody);
  
      if (isset($responseBody->error)) {
         $apiErr = $responseBody->error;
         echo "API error {$apiErr->error_code}: {$apiErr->error_string} - {$apiErr->error_detail} (RequestId: {$apiErr->request_id})";
      }
      else {
         // Extracting HTTP response headers: RequestId (request Id) and Units (information about points)
         $responseHeadersArr = explode("\r\n", $responseHeaders);
         foreach ($responseHeadersArr 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 ($responseBody->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 isn't 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 is created with a warning (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 headers: <pre>".curl_getinfo($curl, CURLINFO_HEADER_OUT)."</pre>";
//echo "Request: <pre>".json_encode($params, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";
//echo "Response headers: <pre>".$responseHeaders."</pre>";
//echo "Response: <pre>".json_encode($responseBody, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";

curl_close($curl);
?>