Working with Yandex.Direct API
Rus
Eng
Работа с Яндекс.Direct API

All English-language materials have been translated fully automatically using the Google service

To work with the Yandex.Direct API, the first thing to do is register the application ... I will not describe the registration process, it is intuitive. I will only say that when creating an application, do not forget to check the box next to Using the Yandex.Direct API

Next creating a request to receive API access. I failed to fill in the first time. I was asked to describe a bunch of related information.

  Application rejected. Please describe in more detail how and which Direct API methods your program uses: method names; for what purposes the methods are used; scheme and sequence of method calls; how often each method is called (once a minute, once an hour, etc.) and for what purposes this particular frequency is selected. Also describe how the program handles errors that occur when working with the API and how the program takes into account the current limitations of the Direct API.  

In my case, the application only collected statistics on Yandex.Direct usage and I answered accordingly:

  1. The application will access the Reports service at https://api.direct.yandex.com/json/v5/reports and, using a filter in the parameters, receive statistics data for the required period.
2. Methods and objectives will be used to obtain statistics
3. In general terms: getting a token-> request to the service and getting statistics-> further work with data
4. Once an hour, day, week. At the request of the client
5. The goal is one - to satisfy the needs of the client
6. When an error is received, the script displays an error message and stops its work.
7. API limits should not be exceeded, their legal and rather rare use is assumed  

I also advise you to read the documentation and examples

Obtaining OAuth token

  // Application ID
$ client_id = 'Application ID';
// Application password
$ client_secret = 'Application Password';

/// If the script was called with the "code" parameter in the URL,
// then a request to get a token is executed
if (isset ($ _ GET ['code']))
{
    // Forming the parameters (body) of the POST request with the confirmation code
    $ query = array (
        'grant_type' => 'authorization_code',
        'code' => $ _GET ['code'],
        'client_id' => $ client_id,
        'client_secret' => $ client_secret
    );
    $ query = http_build_query ($ query);

    // Formation of POST request headers
    $ header = "Content-type: application / x-www-form-urlencoded";

    // Executing a POST request and displaying the result
    $ opts = array ('http' =>
        array (
            'method' => 'POST',
            'header' => $ header,
            'content' => $ query
        )
    );
    $ context = stream_context_create ($ opts);
    $ result = file_get_contents ('https://oauth.yandex.ru/token', false, $ context);
    $ result = json_decode ($ result);

    // The token must be saved for use in requests to the Direct API
    echo $ result-> access_token;
}
// If the script was called without specifying the "code" parameter,
// the user is shown a link to the access request page
else
{
    echo ' Access request page ';
}
// The token can be dropped into the database by associating it with the user, for example, and a couple of days before the end of the token, remind me to update  

Getting customer logins

  public function getLogins () {
        // --- Preparing and executing a request ----------------------------------- //
        // Set the HTTP request headers
        $ headers = array (
            "Authorization: Bearer $ this-> sToken", // OAuth token. The use of the word Bearer is required
            "Client-Login: $ this-> sGlobalClientLogin", // Advertising agency client login
            "Accept-Language: ru", // Language of response messages
            "Content-Type: application / json; charset = utf-8" // Data type and encoding of the request
        );

        // Parameters of the request to the API Direct server
        $ params = array (
            'method' => 'get', // The method used by the Campaigns service
            'params' => array (
                'SelectionCriteria' => (object) array (), // Campaign selection criterion. To receive all campaigns must be empty
                'FieldNames' => array ('Login') // Names of parameters that you want to get AccountQuality, Archived, ClientId, ClientInfo, CountryId, CreatedAt, Currency, Grants, Login, Notification, OverdraftSumAvailable, Phone, Representatives, Restrictions, Settings, Type , VatRate
            )
        );
        // Convert the input parameters of the request to JSON format
        $ body = json_encode ($ params, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // Initialize cURL
        $ curl = curl_init ();
        curl_setopt ($ curl, CURLOPT_URL, $ this-> sUrlClients);
        curl_setopt ($ curl, CURLOPT_POST, true);
        curl_setopt ($ curl, CURLOPT_POSTFIELDS, $ body);

        / *
        To make full use of the HTTPS protocol, you can enable verification of the SSL certificate of the Direct API server.
        To enable verification, set the CURLOPT_SSL_VERIFYPEER option to true, and also uncomment the line with the CURLOPT_CAINFO option and specify the path to the local copy of the SSL root 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);

        // Execute the request, get the result
        $ result = curl_exec ($ curl);

        // --- Processing the result of request execution --------------------------- //
        if (! $ result) {
            $ array = array (
                'response' => 'cURL error:' .curl_errno ($ curl). ' - '.curl_error ($ curl)
            );
        } else {
            // Separate HTTP headers and 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) {
                $ array = array (
                    'response' => "HTTP error:" .curl_getinfo ($ curl, CURLINFO_HTTP_CODE)
                );
            }
            else {
                // Convert response from JSON format
                $ responseBody = json_decode ($ responseBody);

                if (isset ($ responseBody-> error)) {
                    $ apiErr = $ responseBody-> error;
                    $ array = array (
                        'response' => "API error {$ apiErr-> error_code}: {$ apiErr-> error_string} - {$ apiErr-> error_detail} (RequestId: {$ apiErr-> request_id})"
                    );
                }
                else {

                    // Retrieve the HTTP response headers: RequestId (request Id) and Units (score information)
                    $ responseHeadersArr = explode ("\ r \ n", $ responseHeaders);
                    foreach ($ responseHeadersArr as $ header) {
                        if (preg_match ('/ (RequestId | Units): /', $ header)) {
                            $ array ['HEADERS'] [] = $ header;
                        }
                    }

                    // Display a list of advertising campaigns
                    foreach ($ responseBody-> result-> Clients as $ client) {
                        $ array ['LOGINS'] [] = $ client-> Login;
                    }
                }
            }
        }

        curl_close ($ curl);

        return $ array;
    }  

Getting statistics with custom fields and date

List fields available to receive < / a>

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

function getStats ($ login) {
    //--- Input data ------------------------------------------- -------- //
    // The 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 on whose behalf requests will be executed
    $ token = 'Token';
    // Login of the client of the advertising agency
    // Required parameter if requests are made on behalf of an advertising agency
    $ clientLogin = $ login;

    // --- Preparing a request ------------------------------------------- ---- //
    // Create request body
    $ params = [
        "params" => [
            "SelectionCriteria" => [
                "DateFrom" => "2019-07-16",
                "DateTo" => "2020-03-12"
            ],
            "FieldNames" => ["Date", "CampaignName", "LocationOfPresenceName", "Impressions", "Clicks", "Cost"],
            "ReportName" => "New report:". $ Login,
            "ReportType" => "CAMPAIGN_PERFORMANCE_REPORT",
            "DateRangeType" => "CUSTOM_DATE",
            "Format" => "TSV",
            "IncludeVAT" => "NO",
            "IncludeDiscount" => "NO"
        ]
    ];

    // Convert the input parameters of the request to JSON format
    $ body = json_encode ($ params);

    // Create HTTP request headers
    $ headers = array (
        // OAuth token. The use of the word Bearer is required
        "Authorization: Bearer $ token",
        // Login of the client of the advertising agency
        "Client-Login: $ clientLogin",
        // Language of response messages
        "Accept-Language: ru",
        // Report generation mode
        "processingMode: auto",
        // Format of monetary values ​​in the report
        // "returnMoneyInMicros: false",
        // Do not display a line with the report name and date range in the report
        // "skipReportHeader: true",
        // Do not display a line with field names in the report
        // "skipColumnHeader: true",
        // Do not display a line with the number of statistics lines in the report
        // "skipReportSummary: true"
    );

    // Initialize cURL
    $ 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 enable verification of the SSL certificate of the Direct API server.
    To enable verification, set the CURLOPT_SSL_VERIFYPEER option to true, and also uncomment the line with the CURLOPT_CAINFO option and specify the path to the local copy of the SSL root 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);

    // --- Start a loop for executing requests ---
    // If HTTP code 200 is received, then the content of the report is displayed
    // If HTTP code 201 or 202 is received, repeated requests are made
    while (true) {

        $ result = curl_exec ($ curl);

        if (! $ result) {

            $ array = array (
                'response' => 'cURL error:' .curl_errno ($ curl). ' - '.curl_error ($ curl)
            );

            break;

        } else {
// Separate HTTP headers and response body
            $ responseHeadersSize = curl_getinfo ($ curl, CURLINFO_HEADER_SIZE);
            $ responseHeaders = substr ($ result, 0, $ responseHeadersSize);
            $ responseBody = substr ($ result, $ responseHeadersSize);

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

            // Extract HTTP response headers
            // Request ID
            $ requestId = preg_match ('/ RequestId: (\ d +) /', $ responseHeaders, $ arr)? $ arr [1]: false;
            // Recommended interval in seconds for checking report readiness
            $ retryIn = preg_match ('/ retryIn: (\ d +) /', $ responseHeaders, $ arr)? $ arr [1]: 60;

            if ($ httpCode == 400) {

                $ array = array (
                    'response' => array ('400')
                );

                $ array ['response'] [] = "Request parameters were specified incorrectly or the limit of reports in the queue has been reached";
                $ array ['response'] [] = "RequestId: {$ requestId}";
                $ array ['response'] [] = "JSON request code: {$ body}";
                $ array ['response'] [] = "JSON server response code: {$ responseBody}";

                break;

            } elseif ($ httpCode == 200) {
                $ array = array (
                    'response' => array ('200')
                );

                $ array ['response'] [] = "The report was created successfully";
                $ array ['response'] [] = "RequestId: {$ requestId}";
                $ array ['BODY'] = $ responseBody;

                break;

            } elseif ($ httpCode == 201) {

                $ array = array (
                    'response' => array ('201')
                );

                $ array ['response'] [] = "The report was successfully queued in offline mode";
                $ array ['response'] [] = "Retry request in {$ retryIn} seconds";
                $ array ['response'] [] = "RequestId: {$ requestId}";

                sleep ($ retryIn);

            } elseif ($ httpCode == 202) {

                $ array = array (
                    'response' => array ('202')
                );

                $ array ['response'] [] = "The report is being generated offline.";
                $ array ['response'] [] = "Retry request in {$ retryIn} seconds";
                $ array ['response'] [] = "RequestId: {$ requestId}";

                sleep ($ retryIn);

            } elseif ($ httpCode == 500) {

                $ array = array (
                    'response' => array ('500')
                );

                $ array ['response'] [] = "An error occurred while generating the report. Please try to repeat the request later";
                $ array ['response'] [] = "RequestId: {$ requestId}";
                $ array ['response'] [] = "JSON code of server response: 
{$ responseBody}"; break; } elseif ($ httpCode == 502) { $ array = array ( 'response' => array ('502') ); $ array ['response'] [] = "The report generation time has exceeded the server limit."; $ array ['response'] [] = "Please try changing the request parameters - to reduce the period and the amount of requested data."; $ array ['response'] [] = "RequestId: {$ requestId}"; break; } else { $ array = array ( 'response' => array ('UnkwownError') ); $ array ['response'] [] = "An unexpected error occurred."; $ array ['response'] [] = "RequestId: {$ requestId}"; $ array ['response'] [] = "JSON request code: {$ body}"; $ array ['response'] [] = "JSON code of server response:
{$ responseBody}"; break; } } } curl_close ($ curl); return $ array; }

Parse report with statistics in tsv format to php

The response comes in this format

  2019-09-23 vital queries / rsya Voronezh 28 0 0
2019-09-23 vital inquiries / rsya Voronezh region 1 0 0
2019-09-23 vital inquiries / rsya Rossosh 1 0 0
2019-09-23 vital inquiries / rsia South 1 0 0
2019-09-23 buy vb / search Voronezh 14 1 24860000
2019-09-23 buy vb / search Voronezh region 4 0 0
2019-09-23 vital queries / search Voronezh 22 0 0
2019-09-23 vital queries / search Voronezh region 3 0 0
2019-09-23 vital queries / search Moscow 7 0 0
2019-09-23 vital queries / search Naryan-Mar 1 0 0  

It is very problematic to work with it, but the function explode

comes to our rescue
  $ delimiter = "\ n";
$ splitcontents = explode ($ delimiter, $ contentReport);
foreach ($ splitcontents as $ line)
{
    $ bits = explode ("\ t", $ line);
}
 

As a result, at each iteration we get

  Array
(
    [0] => 2019-09-23
    [1] => vital queries / rsya
    [2] => Voronezh region
    [3] => 1
    [4] => 0
    [5] => 0
)  

Automatic loading of data from Yandex.Direct to Google Analitics

Create a service account to access GA via API.

After registering an account, add it to the administrators of the Google Analitics project and save the file service-account-credentials.json

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number