Get statistics for a selection of rows

PHP 5 using JSON with the cURL library

This example shows a request to the Reports service, along with the result processing and output. The mode for generating the report is selected automatically. If the report is added to the queue in offline mode, repeated requests are made.

The report contains statistics on impressions, clicks, and expenditures for all the advertiser's campaigns for the past month, with grouping by date, campaign name, and ad ID. The report filters out rows with the most expensive clicks, where the number of clicks is less than the set value and the CPC is higher than the set value.

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. In the request message body, specify the thresholds for the number of clicks and the CPC, as well as a report name that is unique among the advertiser's reports.

<?php

// Settings for outputting the buffer contents, which allow you to print to the screen
// when using the sleep function
ob_implicit_flush();

//--- Input data ---------------------------------------------------//
// Address of the Reports service for sending JSON requests (case-sensitive)
$url = 'https://api.direct.yandex.com/json/v5/reports';
// OAuth token of the user that requests will be executed on behalf of
$token = 'TOKEN';
// Login of the advertising agency client
// Required if requests are sent for an advertising agency
$clientLogin = 'CLIENT_LOGIN';

//--- Preparing the request -----------------------------------------------//
// Creating the request body
$params = [
    "params" => [
        "SelectionCriteria" => [
            "Filter" => [
                [
                    "Field" => "Clicks",
                    "Operator" => "LESS_THAN",
                    "Values" => ["CLICK_THRESHOLD"]
                ],
                [
                    "Field" => "Cost",
                    "Operator" => "GREATER_THAN",
                    "Values" => ["COST_THRESHOLD"]
                ]
            ]],
        "FieldNames" => ["Date", "CampaignName", "AdId", "Impressions", "Clicks", "Cost"],
        "ReportName" => "REPORT_NAME",
        "ReportType" => "AD_PERFORMANCE_REPORT",
        "DateRangeType" => "LAST_MONTH",
        "Format" => "TSV",
        "IncludeVAT" => "NO",
        "IncludeDiscount" => "NO"
    ]
];

// Transforming request input parameters to JSON
$body = json_encode($params);

// Creating request HTTP headers
$headers = array(
    // OAuth-токен. The word Bearer must be used
    "Authorization: Bearer $token",
    // Login of the advertising agency client
    "Client-Login: $clientLogin",
    // Language for response messages
    "Accept-Language: ru", 
    // Mode for report generation
    "processingMode: auto",
    //Format for monetary values in the report
    // "returnMoneyInMicros: false",
    // Don't include the row with the report name and date range in the report
    // "skipReportHeader: true",
    // Don't include the row with column names in the report
    // "skipColumnHeader: true",
    // Don't include the row with the number of statistics rows in the report
    // "skipReportSummary: true" 

);

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

/*
To make full use of the HTTPS protocol, you can verify the SSL certificate for 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);

// --- Starting the request execution loop ---
// If HTTP code 200 is returned, output the report contents
// If HTTP code 201 or 202 is returned, send repeated requests
while (true) {

    $result = curl_exec($curl);

    if (!$result) {

        echo ('cURL error: '.curl_errno($curl).' - '.curl_error($curl));

        break;

    } else {

        // Separating HTTP headers and the response body
        $responseHeadersSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
        $responseHeaders = substr($result, 0, $responseHeadersSize);
        $responseBody = substr($result, $responseHeadersSize);

        // Getting the HTTP status code
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        // Extracting HTTP response headers
        // Request ID
        $requestId = preg_match('/RequestId: (\d+)/', $responseHeaders, $arr) ? $arr[1] : false;
        // Recommended number of seconds to wait before rechecking report readiness
        $retryIn = preg_match('/retryIn: (\d+)/', $responseHeaders, $arr) ? $arr[1] : 60;

        if ($httpCode == 400) {

            echo "Invalid request parameters, or the report queue is full<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code for the request:<br>{$body}<br>";
            echo "JSON code for the server response:<br>{$responseBody}<br>";

            break;

        } elseif ($httpCode == 200) {

            echo "Request created successfully<br>";
            echo "RequestId: {$requestId}<br>";
            echo $responseBody;

            break;

        } elseif ($httpCode == 201) {

            echo "Request successfully added to the offline queue<br>";
            echo "Request will be resent in {$retryIn} seconds<br>";
            echo "RequestId: {$requestId}<br>";

            sleep($retryIn);

        } elseif ($httpCode == 202) {

            echo "Report is being generated in offline mode.<br>";
            echo "Request will be resent in {$retryIn} seconds<br>";
            echo "RequestId: {$requestId}<br>";

            sleep($retryIn);

        } elseif ($httpCode == 500) {

            echo "Error occurred when creating the report. Please repeat the request again later<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code for the server's response:<br>{$responseBody}<br>";

            break;

        } elseif ($httpCode == 502) {

            echo "Exceeded the server limit on report creation time.<br>";
            echo "Please try changing the request parameters: reduce the time period and the amount of data requested.<br>";
            echo "RequestId: {$requestId}<br>";

            break;

        } else {

            echo "Unexpected error<br>";
            echo "RequestId: {$requestId}<br>";
            echo "JSON code for the request:<br>{$body}<br>";
            echo "JSON code for the server's response:<br>{$responseBody}<br>";

            break;

        }
    }
}

curl_close($curl);
?>