S
S
stainer2018-10-02 15:53:29
PHP
stainer, 2018-10-02 15:53:29

How to get yadirect api balance?

Good afternoon, tell me how to get the balance of the general account?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://api.direct.yandex.com/json/v5/campaigns');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'{"method":"get","params":{"SelectionCriteria":{},"FieldNames":["Name"]}}');  //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
    'POST /json/v5/ads/ HTTP/1.1',
    'Host: api.direct.yandex.com',
    'Authorization: Bearer AQAAAAAW-WvQ*****************************',
    'Accept-Language: ru',
    'Client-Login:  ********[email protected]',
    'Content-Type: application/json; charset=utf-8',
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$server_output = curl_exec ($ch);
curl_close ($ch);
 
print  $server_output;

As I understand it, you need to edit CURLOPT_POSTFIELDS, but it didn’t work with the help of the Yandex documentation ..

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
stainer, 2018-10-02
@stainer

Understood. Maybe someone needs..

$ch = curl_init();
  curl_setopt($ch, CURLOPT_URL,'https://api.direct.yandex.ru/live/v4/json/');
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS,'{
     "method": "AccountManagement",
     "token": "AQAAAAAW-*******************************",
     "param": {"SelectionCriteria": {}, "Action": "Get"}}');  //Post Fields
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $headers = [
    'POST /json/v5/ads/ HTTP/1.1',
    'Host: api.direct.yandex.com',
    'Authorization: Bearer AQAAAAAW-**********************************',
    'Accept-Language: ru',
    'Client-Login:  *************@yandex.ru',
    'Content-Type: application/json; charset=utf-8',
  ];
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  $server_output = curl_exec ($ch);
  curl_close ($ch);
  $balance_direct_miramall = json_decode($server_output,true);

E
Edward Pashchenko, 2020-01-29
@edwardjeanx

For those who did not work with the previous method :)

function direct__GetReports($token, $login) {
    $params = array(
        'method' => "AccountManagement",
        'param'  => array(
            'Action'            => "Get",
            'SelectionCriteria' => array(
                'Logins' => array($login),
            ),
        ),
        'locale' => "ru",
        'token'  => $token,
    );
    $headers = array(
        'POST /json/v5/ads/ HTTP/1.1',
        'Host: api.direct.yandex.com',
        'Authorization: Bearer ' . $token,
        'Accept-Language: ru',
        'Client-Login:  ' . $login,
        'Content-Type: application/json; charset=utf-8',
    );
    $url = 'https://api.direct.yandex.ru/live/v4/json/';
    $ch  = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $server_output = curl_exec($ch);
    curl_close($ch);
    return json_decode($server_output, true);
}

Y
Yuri, 2021-06-18
@yuretzgt

Who cares, made on python 3rd

import requests
from requests.exceptions import ConnectionError
from time import sleep
import json
import sys
# Метод для корректной обработки строк в кодировке UTF-8 как в Python 3, так и в Python 2
if sys.version_info < (3,):
    def u(x):
        try:
            return x.encode("utf8")
        except UnicodeDecodeError:
            return x
else:
    def u(x):
        if type(x) == type(b''):
            return x.decode('utf8')
        else:
            return x

ReportsURL = 'https://api.direct.yandex.ru/live/v4/json/'
token = 'ВАШ СУПЕР ТОКЕН'
clientLogin = 'ЛОГИН ДО СОБАКИ'

headers = {
    "Authorization": "Bearer " + token,
    "Client-Login": clientLogin,
    "Accept-Language": "ru",
    # 'processingMode': 'auto'
}
body = {
    "method": "AccountManagement",
    "token": token,
    "param": {
        "Action": "Get",
        "SelectionCriteria": {
            'Logins': [
                clientLogin,
            ],
        },
    },
    'locale' : "ru",
}

json_body = json.dumps(body, indent=4)
try:
    req = requests.post(ReportsURL, json_body, headers=headers)
    req.encoding = 'utf-8'
    if req.status_code == 200:
        print("Отчет создан успешно")
        print("RequestId: {}".format(req.headers.get("RequestId", False)))
        print("Содержание отчета: \n{}".format(u(req.text)))
        print("JSON-код запроса: {}".format(u(body)))
        print("JSON-код ответа сервера: \n{}".format(u(req.json())))
    else:
        print("Произошла непредвиденная ошибка")
        print("RequestId:  {}".format(req.headers.get("RequestId", False)))
        print("JSON-код запроса: {}".format(body))
        print("JSON-код ответа сервера: \n{}".format(u(req.json())))
    amount = json_response["data"]["Accounts"][0]["Amount"]
    print("Balans: " + amount)
except ConnectionError:
        # В данном случае мы рекомендуем повторить запрос позднее
        print("Произошла ошибка соединения с сервером API")
        # Принудительный выход из цикла
        
# Если возникла какая-либо другая ошибка
except Exception as e: 
    # В данном случае мы рекомендуем проанализировать действия приложения
    print("Произошла непредвиденная ошибка - 1")
    print(e)
    # Принудительный выход из цикла

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question