Get campaigns

PHP 5 using JSON with the file_get_contents function

This example shows a request using the Campaigns.get method, along with the result processing and output. To use the example, specify the OAuth access token in the input data. For a request on behalf of an agency, also specify the client login.

<?php
//--- Input data -------------------------------------------------------------------------//
// Address of the Campaigns service for sending JSON requests (case-sensitive)
$url = 'https://api.direct.yandex.com/json/v5/campaigns';
// OAuth token of the user to execute requests 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';

//--- 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' => 'get',                                 // Method of the Campaigns service
   'params' => array(
      'SelectionCriteria' => (object) array(),        // Criteria for filtering campaigns. To get all campaigns, leave it empty
      'FieldNames' => array('Id', 'Name')             // Names of parameters to get
   )
);
// Transforming input parameters to JSON
$body = json_encode($params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// Creating the stream context: setting HTTP headers and the request body
$streamOptions = stream_context_create(array(
   'http' => array(
      'method' => 'POST',
      'header' => $headers,
      'content' => $body
   ),
   /*
   // 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.
   )
   */ 
));

// Executing the request and getting the result.
$result = file_get_contents($url, 0, $streamOptions);

//--- Processing request results ---------------------------//
if ($result === false) { echo "Request execution error."; }
else {
 // Converting input parameters to JSON
   $result = json_decode($result);

   if (isset($result->error)) {
      $apiErr = $result->error;
      echo "API Error {$apiErr->error_code}: {$apiErr->error_string} - {$apiErr->error_detail} (RequestId: {$apiErr->request_id})";
   }
   else {
      // Extracting HTTP response headers: RequestId (ID of the request) and Units (information about points)
      foreach ($http_response_header as $header) {
         if (preg_match('/(RequestId|Units):/', $header)) { echo "$header <br>"; }
      }

      // Outputting the list of ad campaigns
      foreach ($result->result->Campaigns as $campaign) {
         echo "Ad campaign: {$campaign->Name} ({$campaign->Id})<br>";
      }
   } 
}

//--- Debugging information ---------------------------------------------//
//echo "hr>Request headers: <pre>".implode($headers, '<br>')."</pre>";
// echo "Request: <pre>".json_encode($params, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";
// echo "Response headers: <pre>".implode($http_response_header, '<br>')."</pre>";
// echo  "Response: <pre>".json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."</pre>";
?>