API setting

From Service Manual Kadam.net
Revision as of 13:46, 21 January 2019 by Admin (Talk | contribs) (Создание рекламных объявлений)

Jump to: navigation, search

Contents

API authorization

To access the API, you will need a user ID (app_id) and a signature (signature). Calling different methods is carried out using queries on this template:

        api.kadam.net?%action%.%method%?%params%
        % action% - what are we turning to
        % method% - type of treatment
get - get
put - write
post - update
delete - delete
        % params% - request parameters

        required parameters% params%

        app_id - user id
        signature - signature

Example:

       [GET] http://api.kadam.net/campaigns.get?app_id=%app_id%&signature=%signature%

or

       [GET] http://api.kadam.net/campaigns?app_id=%app_id%&signature=%signature%
       [GET] - http access method

Signature (signature) is created using a temporary token (access_token), which can be obtained using the app_id and secret key parameters.
Parameters app_id (user ID) and the key "secret key" are available on request to support.
Getting a token:

       [GET] http://api.kadam.net/auth.token?app_id=%app_id%&secret_key=%key%
       -> {“access_token”: “...”}

Generating signature for the [GET] method:

       md5 ( %sort_params% . %access_token% )
       %sort_params% - all parameters passed (except signature) are sorted by name

Example:

       app_id=1&campaign_id=3…
       [PUT] http://api.kadam.net/campaigns?signature=%signature%
       +post fields -> %params%

Example for php. Getting a list of campaigns:

       <?
        $your_secret_key = "jqhwekq8734quo37o498q3p498qp34";
       $your_app_id = 1;
       $auth_url = "http://api.kadam.net/auth.token?app_id={$your_app_id}&secret_key={$your_secret_key}";
       $auth = file_get_contents($auth_url);
       $auth = json_decode($auth, true);

       if ( !is_array( $auth ) || !isset( $auth['access_token'] ) ) {
           die( 'something wrong! ' . print_r( $res, true ) );
       }

       $token    = $auth['access_token'];
       $params = array(
	    'client_id' => $your_app_id,
        'app_id' => $your_app_id,
       );

       ksort( $params );

       $result = array ();
       foreach( $params as $key => $value ) {
           $result[] = $key . '=' . urlencode( $value );
       }
       $params = implode( '&', $result );
       $signature = md5( $params . $token );

       $campaign_url = 'http://api.kadam.net/ads.campaigns.get?' . $params . '&signature=' . $signature;

       $campaigns = file_get_contents($campaign_url);
       $campaigns = json_decode($campaigns, true);

       if ( !is_array( $campaigns ) || !isset( $campaigns['response'] ) ) {
           die( 'something wrong! ' . print_r( $campaigns, true ) );
       }
       
       print_r($campaigns);
       

Campaign Statistics

To get campaign statistics, use the method ads.analytic.campaign.get

Parameters Values Optional attributes
campaign_id campaign's id int (numeric value), required parameter
region_id region's id: data.geo.regions.get int (numeric value), required parameter
period The way data is grouped by date:

day — daily statistics;

month - monthly statistics

Temporary restrictions are set by parameters date_from and date_to

required parameter, string
date_from The starting date of the statistics to display. Different date format is used for different parameter period values:

day: YYYY-MM-DD, example: 2011-09-27;

month: YYYY-MM, example: 2011-09

required parameter, string
date_to The final date of the displayed statistics. Different date format is used for different parameter period values:

day: YYYY-MM-DD, example: 2011-09-27;

month: YYYY-MM, example: 2011-09

required parameter, string

Result:
Returns an object with data

{
	response: {
		count: %total items%
		items: {
			shows
			clicks
			ctr
			cpm
			money
                       }
                  }
}

Statistics on sites in the advertiser's office

Under the statistics on the sites in the office of the advertiser means statistics on impressions and clicks on the site in the context of each campaign.
To get statistics on sites, use the ads.campaigns.statblock.get method (GET request)

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
Parameters Value Additional attributes
date_from Start date of the statistics output. string, format YYYY-MM-DD (example: 2017-05-15), filter parameter
date_to The end date of the statistics output. string, format YYYY-MM-DD (example: 2017-05-15), filter parameter
campaign_id campaign id required parameter, int (numeric value), filter parameter
signature Signature (generated using a time token, see above) required parameter, string
app_id user id required parameter, int (numeric value)
macros site id int (numeric value), write parameter, filter option
leads Lida int (numeric value), write parameter, filter option
views Impressions int (numeric value), write parameter, filter option
clicks Clicks int (numeric value), write parameter, filter option
conversions Confirmed Conversions int (numeric value), write parameter, filter option
rejections Failed Conversions int (numeric value), write parameter, filter option
ctr CTR int (numeric value), write parameter, filter option
cpm CPM int (numeric value), write parameter, filter option
cpc CPC int (numeric value), write parameter, filter option
prelandvisit Prelend Visits int (numeric value), write parameter, filter option
prelanduseful Useful visits Prelend int (numeric value), write parameter, filter option
prelandscroll Prelend Scroll int (numeric value), write parameter, filter option

Result:
Returns an object with data, example:

{
  "response": {
    "count": 1,
    "items": [
      {
        "macros": "12345678901234",
        "block": "1234",
        "domain": "123456789",
        "leads": "0",
        "views": "123",
        "clicks": "0",
        "conversions": "0",
        "rejections": "0",
        "ctr": "0.0000",
        "cpm": "0.00",
        "cpc": null,
        "moneyOut": "0.000000",
        "moneyIn": null,
        "prelandvisit": "0",
        "prelanduseful": "0",
        "prelandscroll": "0",
        "landvisit": "0",
        "landuseful": "0",
        "landscroll": "0",
        "multiplier": null,
        "blackList": "0"
      }
    ],
    "request": {
      "campaignId": 123456,
      "limit": 10,
      "offset": 0
    }
  }
}

Sorting

Sort Ascending

sort = {parameter}
Example: api.kadam.net?sort=views

Sort descending

sort = - {parameter}
Example: api.kadam.net?sort=-views

Sort by several parameters

sort = {parameter1}, - {parameter2}, {parameter3}
Example: api.kadam.net?sort=views,-clicks,leads

Filtration

{parameter} = {value}
Examples:
api.kadam.net?attr=10
api.kadam.net?attr=string
api.kadam.net?attr=string&date_from=01.05.2016&date_to=01.07.2016

Change the multiplier for statistics on sites in the advertiser's office

To change the multiplier for site statistics, use the ads.campaigns.statblock method (PUT request)

Parameters (all are required):

  • app_id - user id, numeric value (int)
  • signature - signature, string (string)
  • campaign_id - campaign id, numeric value (int)
  • block - a numeric value (int)
  • domain - numeric value (int)
  • multiplier - new multiplier value, numeric value (float)
  • multiplierOld - old multiplier value, numeric value (float)
  • macros - pad id, numeric value (int)

The block and macros parameters in the account are not displayed, they can be obtained through the method described in the paragraph "Statistics by sites in the advertiser's office".

Statistics on all campaign materials

To get statistics on all campaign materials, use the ads.analytic.materials.get method

                                                                                                                                                               
Parameters Value Additional attributes
campaign_id campaign id int (numeric value), required parameter
period Method for grouping data by date:            

1. day - statistics by day;

           

2. month - statistics by months;

           

Temporary restrictions are set by date_from and date_to parameters

       
required parameter, string
date_from The starting date of the displayed statistics. Different date format is used for different values ​​of the period parameter:            

1. day: YYYY-MM-DD, Example: 2011-09-27

           

2. month: YYYY-MM, example: 2011-09

       
required parameter, string
date_to End date of output statistics. Different date format is used for different values ​​of the period parameter:            

1. day: YYYY-MM-DD, Example: 2011-09-27

           

2. month: YYYY-MM, example: 2011-09

       
required parameter, string

Result:
Returns an object with data

{
response: {
count:% total items%
items: {
teaser_id
date
shows
clicks
ctr
cpm
money
                       }
                  }
}

Статистика по материалу

Для получения статистики по материалу используется метод ads.analytic.material.get

Параметры Значение Дополнительные атрибуты
material_id id материала int (числовое значение), обязательный параметр
period Способ группировки данных по датам:

1. day — статистика по дням;

2. month — статистика по месяцам;

Временные ограничения задаются параметрами date_from и date_to

обязательный параметр, строка
date_from Начальная дата выводимой статистики. Используется разный формат дат для разного значения параметра period:

1. day: YYYY-MM-DD, пример: 2011-09-27

2. month: YYYY-MM, пример: 2011-09

обязательный параметр, строка
date_to Конечная дата выводимой статистики. Используется разный формат дат для разного значения параметра period:

1. day: YYYY-MM-DD, пример: 2011-09-27

2. month: YYYY-MM, пример: 2011-09

обязательный параметр, строка

Результат:
Возвращает объект с данными

{
	response: {
		count: %total items%
		items: {
			date
			shows
			clicks
			ctr
			cpm
			money
                       }
                  }
}

Создание рекламной кампании

Для для создания новой рекламной кампании используется метод ads.campaigns.put
Допустимое количество кампаний, создаваемых с помощью одного запроса — 50.

Параметры Значение Дополнительные атрибуты
data сериализованный JSON-массив объектов, описывающих создаваемые кампании. Описание объектов client_specification см. ниже. обязательный параметр, строка
client_specification
app_id id пользователя обязательный параметр, int (числовое значение)
client_id id клиента, в рекламном кабинете которого будет создаваться кампания. Так же может принимать значение app_id (самого себя) обязательный параметр, int (числовое значение)
ad_format Формат объявления:

10 - Тизерная;

20 - Баннерная;

30 - Push-уведомления;

40 - Clickunder;

60 - Контекстная

обязательный параметр, int (числовое значение)
cost_type Способ оплаты:

0 - СРС;

1 - СРА;

2 - СРМ

обязательный параметр, int (числовое значение)
name название кампании обязательный параметр, строка
Link_url ссылка на рекламируемый объект в формате: http://yoursite.cоm обязательный параметр, строка
real_url ссылка на реальный домен рекламируемого объекта в формате: http://yoursite.cоm обязательный параметр, строка
sex Пол:

3 - любой;

2 - мужской;

1 - женский

обязательный параметр, int (числовое значение)
age Возраст целевой аудитории. Номер возрастной категории от 1 до 6 (до 17, 18-25, 26-34, 35-49, 50-60, старше 61) обязательный параметр, последовательность чисел, разделенных запятой
regions Регионы, от 1 до 10 (1 - Россия, 2 - Украина и т.д.) обязательный параметр, последовательность чисел, разделенных запятой
cpa_mode Тип уведомлений о конверсий для CPA: /ads.targeting.modes.get int (числовое значение), обязательное для CPA кампании
categories

идентификаторы категорий:

/data.categories.get?ad_format=%

масив [category_id => cost]

tags таргетинг по ключевым словам

обязательный параметр, последовательность ключевых слов, разделенных запятой: [“key1”, “key2”, .., “keyN”]

Ключевые слова с ценой. Только для оплаты - за клики или за показы: {“key1”: “cost”, “key2”: “cost”, .., “keyN”: “cost”}

cost - float

пример: "data[tags][qwerty]: 1" - ключевое слово qwerty со ставкой 1руб.

day_limit Дневной лимит в рублях. Для всех типов кроме clickunder положительное число
all_limit Общий лимит в рублях. Для всех типов кроме clickunder положительное число
click_limit Максимальное кол. переходов в день. Для всех типов кроме clickunder. За показы и за клики. положительное число
conversion_limit Максимальное кол. конверсий в день. Для всех типов кроме clickunder. Только для CPA положительное число
adult_content присутсвие контента для взрослых в рекламной кампании:

0 - Нет;

1 - Да

необязательный параметр, int (числовое значение), по умолчанию 0
adult_site Отображать объявления кампании на сайтах с контентом для взрослых:

0 - Нет;

1 - Да

необязательный параметр, int (числовое значение), по умолчанию 0
time_show Временной таргетинг:

   * - отображение в любые часы и дни недели

   {} - массив, где ключ имя дня недели ["Sn","Mn","Tu","Wd","Th","Fr","Sa"]:

             {} - ‘mn’: ‘*’ - все часы понендельника

             {} - ‘mn’: [0, .., 23] - часы через запятую

необязательный параметр, * по умолчанию
platforms таргетинг по платформам: /data.platforms последовательность чисел, разделенных запятой
browsers таргетинг по браузерам: /data.browsers последовательность чисел, разделенных запятой
black_list черный список площадок на которых не будет показана реклама последовательность чисел ID площадок, разделенных запятой
white_list белый список площадок на которых не будет показана реклама последовательность чисел ID площадок, разделенных запятой
black_list_ip блокировка по ip последовательность ip адресов, разделенных запятой или массивом
unique_day_count частота показов материала одному пользователю (разы) положительное число
unique_days частота показов рекламного материала одному пользователю (дни) положительное число

Результат:
Возвращает массив ответов на запросы в массиве data. Соответствующий объект в выходном массиве содержит id созданной кампании, и поля error_code и error_desc в случае возникновения ошибки.

Errors:

   102 - unknown client
   103 - overlimit campaigns

Редактирование рекламных кампаний

Для редактирования рекламных кампаний используется метод ads.campaigns.update
Максимальное допустимое количество кампаний, редактируемых с помощью одного запроса — 50.
Version log: 1.0.1 - добавлен параметр status

Параметры Значение Дополнительные атрибуты
data сериализованный JSON-массив объектов, описывающих изменения в кампаниях. Описание объектов client_mod_specification см. ниже. обязательный параметр, строка
client_specification
campaign_id id редактируемой кампании обязательный параметр, положительное число
name название кампании необязательный параметр, строка длиной от 3 до 60 символов
link_url ссылка на рекламируемый объект в формате http://yoursite.cоm необязательный параметр, строка
real_url ссылка на реальный домен рекламируемого объекта в формате: http://yoursite.cоm необязательный параметр, строка
sex Пол:

3 - любой;

2 - мужской;

1 - женский

необязательный параметр, int (числовое значение)
age возраст: /data.ages необязательный параметр, int (числовое значение)
categories идентификаторы категорий:

/data.categories.get?ad_format=%

category_id: {region_id: cost}

необязательный параметр
tags таргетинг по ключевым словам необязательный параметр, последовательность ключевых слов, разделенных запятой
day_limit дневной лимит в рублях. для всех типов кроме clickunder необязательный параметр, положительное число
adult_content присутсвие контента для взрослых в рекламной кампании:

0 - Нет;

1 - Да

необязательный параметр, int (числовое значение), по умолчанию 0
adult_site отображать объявления кампании на сайтах с контентом для взрослых:

0 - Нет;

1 - Да

необязательный параметр, int (числовое значение), по умолчанию 0
time_show Временной таргетинг:

   * - отображение в любые часы и дни недели

   {} - массив, где ключ имя дня недели ["Sn","Mn","Tu","Wd","Th","Fr","Sa"]:

           {} - ‘mn’: ‘*’ - все часы понендельника

           {} - ‘mn’: [0, .., 23] - часы через запятую

необязательный параметр, * по умолчанию
platforms таргетинг по платформам: /data.platforms последовательность чисел, разделенных запятой
browsers таргетинг по браузерам: /data.browsers последовательность чисел, разделенных запятой
black_list черный список площадок на которых не будет показана реклама последовательность чисел ID площадок, разделенных запятой
white_list белый список площадок на которых не будет показана реклама последовательность чисел ID площадок, разделенных запятой
black_list_ip блокировка по ip последовательность ip адресов, разделенных запятой или массивом
status запуск/приостановка кампании:

0 - приостановлена;

1 - запущена

необязательный параметр, int (числовое значение), по умолчанию 1

Результат:
Возвращает массив ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве содержит id изменяемого клиента и, в случае возникновения ошибки, поля error_code и error_desc.

Errors:

   100 - unknown campaign
   102 - unknown client

Список кампаний рекламного кабинета

Для получения списка кампаний рекламного кабинета используется метод ads.campaigns.get

Параметры Значение Дополнительные атрибуты
client_id Идентификатор клиента, у которого запрашиваются рекламные кампании int (числовое значение)
include_archive Флаг, задающий необходимость вывода архивных объявлений:

0 - выводить только активные кампании;

1 - выводить все кампании

Флаг, может принимать значения 1 или 0
campaign_ids Фильтр выводимых рекламных кампаний.

Сериализованный JSON-массив, содержащий id кампаний. Выводиться будут только кампании, присутствующие в campaign_ids и являющиеся кампаниями указанного рекламного кабинета. Если параметр равен null, то выводиться будут все кампании.

Строка
with_bwlist Флаг передачи блек- и вайт-листов любое значение (например 1)
with_tags Флаг передачи ключевых слов любое значение (например 1)
limit ограничение на количество возвращаемых кампаний. Используется, только если параметр campaign_ids равен null int (числовое значение)
offset смещение. Используется в тех же случаях, что и параметр limit int (числовое значение)

Результат:
Возвращает массив объектов campaign, каждый из которых содержит следующие поля:

response: {
       count: %total%,
       items: [{
	   id — идентификатор кампании
	   name — название кампании
	   status — статус кампании (0 — кампания остановлена, 1 — кампания запущена, 2 — кампания удалена)
	   day_limit — дневной лимит кампании в рублях (0 — лимит не задан)
	   all_limit — общий лимит кампании в рублях (0 — лимит не задан)
	   ad_format — формат объявления
	   cost_type — тип оплаты
	   link_url - ссылка на рекламируемый объект
	   sex - пол
	   age - возраст
	   regions - идентификаторы регионов
	   categories - идентификаторы категорий.
	   adult_content - присутсвие контент для взрослых
	   adult_site - отображение объявлений кампании на сайтах с контентом для взрослых
           tags - ключевые слова
           bw_list - блек- и вайт-лист 
      },..]
}

Errors:

   102 - unknown client

Архивирование рекламной кампании

Для архивирования рекламной кампании используется метод ads.campaigns.delete
Максимальное допустимое количество клиентов, редактируемых с помощью одного запроса — 10.

Параметры Значение Дополнительные атрибуты
ids Список id кампаний через запятую или массив с id кампаниями.

Например:

“id1, id2, …, idn“ или [id1, id2, …, idn]

обязательный параметр, строка

Результат:
Возвращает массив ответов на каждый запрос. Каждый ответ является либо 0, что означает успешное удаление, либо массив error.

Errors:

   100 - unknown campaign
   101 - campaign already archive
   102 - unknown client

Получение кодов для СРА кампаний

Для получения кодов по СРА кампаниям используется метод ads.campaigns.cpa.mode.get

Параметры Значение Дополнительные атрибуты
campaign_id id кампании int (числовое значение), обязательный параметр

Результат:
Возвращает объект с данными.

{
	response: {
		url: %url%
                  }
}

Получение списка категорий по заданому фильтру

Для возврата списка категорий по заданому фильтру используется метод ads.campaigns.categories.get

Параметры Значение Дополнительные атрибуты
ad_format формат объявления:

ads.campaigns.foarmats.get

обязательный параметр, int (числовое значение)
category_id id категории. ограничивает отображение только по id категории необязательный параметр, int (числовое значение)

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
            count: %total%,
            items: [{
                       %category_id%: {
                            %region_id%: {
	                         min: %min_cost%,
	                         max: %max_cost%
                             }
                       }
                  },..]
}

Получение списка форматов объявлений

Для получения списка форматов объявлений используется метод ads.campaigns.formats.get

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
       count: %total%,
       items: [{
             id: %format_id%,
             title: ‘%format title%’
       },..]
}

Получение списка платформ

Для получения списка платформ используется метод ads.targeting.platforms.get

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
       count: %,
       items: [{
           id: %platform_id%,
           title: %platform_name%,
           mobile: %is mobile%
       },..]
}

Получение списка браузеров

Для получения списка браузеров используется метод ads.targeting.browsers.get

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
       count: %,
       items: [{
           id: %browser_id%,
           title: %browser_name%,
       },..]
}

Получение списка уведомлений о конверсиях для СРА

Для получения списка уведомлений о конверсиях для СРА используется метод ads.targeting.cpa.modes.get

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
       count: %total%,
       items: [{
           id: %mode_id%,
           title: ‘%mode title%’
       },..]
}

Получение списка возрастов

Для получения списка возврастов используется метод ads.targeting.ages.get

Результат:
Возвращает массив ответов на запросы в массиве response.

response: {
       count: %,
       items: [{
           id: %age_id%,
           title: %age_name%
       },..]
}

Создание клиентов рекламного агенства

Для создания клиентов рекламного агенства используется метод ads.clients.put
Допустимое количество создаваемых клиентов с помощью одного запроса — 50.

Параметры Значение Дополнительные атрибуты
data сериализованный JSON-массив объектов, описывающих создаваемые кампании. Описание объектов client_specification см. ниже. обязательный параметр, строка
client_specification
name название клиента строка от 3 до 60 символов, обязательный параметр
day_limit дневной лимит в рублях int (числовое значение)

Результат:
Возвращает массив ответов на запросы в массиве data. Соответствующий объект в выходном массиве содержит информацию клиента или массив error в случае возникновения ошибки (для каждого клиента отдельно).

{
    client_id — идентификатор клиента;
    name — название клиента;
    day_limit — дневной лимит клиента в рублях;
}

Редактирование клиентов рекламного агенства

Для редактирования клиентов рекламного агенства используется метод ads.clients.update
Максимальное допустимое количество клиентов, редактируемых с помощью одного запроса — 50.

Параметры Значение Дополнительные атрибуты
data сериализованный JSON-массив объектов, описывающих изменения в клиентах. Описание объектов client_mod_specification см. ниже. обязательный параметр, строка
client_mod_specification
client_id идентификатор редактируемого клиента обязательный параметр, положительное число
name название клиента строка длиной от 3 до 60 символов
day_limit дневной лимит в рублях положительное число

Результат:
Возвращает массив ответов на каждый запрос в массиве data. Соответствующий объект в выходном массиве содержит id изменяемого клиента и, в случае возникновения ошибки, поля error_code иerror_desc.

Получение списка клиентов рекламного агенства

Для возврата списка клиентов рекламного агенства используется метод ads.clients.get

Параметры Значение Дополнительные атрибуты
client_ids Список id клиентов через запятую. Например: “id1, id2, …, idn“ необязательный параметр, строка

Результат:
Возвращает массив объектов client — клиентов агентства, каждый из которых содержит следующие поля:

response: {
      count: %total%,
      items: [{
           client_id — идентификатор клиента;
           name — название клиента;
           day_limit — дневной лимит клиента в рублях;
           balance - баланс клиента
      },..]
}

Архивирование клиентов рекламного агенства

Для архивирования клиентов рекламного агенства используется метод ads.clients.delete

Параметры Значение Дополнительные атрибуты
ids Список id клиентов через запятую или массив с id клиентами.

Например: “id1, id2, …, idn“ или [id1, id2, …, idn]

обязательный параметр, строка

Результат:
Возвращает массив ответов на каждый запрос. Каждый ответ является либо 0, что означает успешное удаление, либо массив error.

Подвязывание клиента к рекламному агенству

Для подвязывания клиента к рекламному агенству используется метод ads.clients.bind.put

Параметры Значение Дополнительные атрибуты
email email адрес клиента строка от 3 до 60 символов, обязательный параметр
password пароль клиента (от кабинета) строка от 3 до 60 символов, обязательный параметр

Результат:
Возвращает:

{
	“bind”: true
}

в случае успеха. Или error в случае возникновения ошибки.

Открепление клиента от рекламного агенства

Для открепления клиента от рекламного агенства используется метод ads.clients.unbind.put

Параметры Значение Дополнительные атрибуты
client_id id клиента int (числовое значение)

Результат:
Возвращает:

{
	“unbind”: true
}

в случае успеха. Или error в случае возникновения ошибки.

Пополнение счета клиента

Для пополнения счета клиента используется метод ads.clients.balance.put

Параметры Значение Дополнительные атрибуты
client_id id клиента для пополнения int (числовое значение), обязательный параметр
sum сума в рублях int (числовое значение)
back_url url куда переадресует клиента система пополнения string (строка)
system_id id системы пополнения:

data.balance.systems.get

int (числовое значение), обязательный параметр

Результат:
Возвращает url для оплаты:

{
	response: {
		url: %url%
                  }
}

Creating advertisements

To create ads using the method ads.materials.put </ b>
The maximum allowable number of ads generated by a single request is 20.

                                                                                           
Parameters </ th>         Value </ th>         Additional attributes </ th>

   </ tr>

   
data </ ​​td>         is a serialized JSON array of objects describing the created ads. The description of ad_specification objects is given below. </ td>         required parameter, string </ td>

   </ tr>

   
ad_specification </ td>

   </ tr>

   
campaign_id </ td>         id of the campaign in which the ad will be created </ td>         required parameter, int (numeric value) </ td>

   </ tr>

   
title </ td>         ad title </ td>         required parameter </ td>

   </ tr>

   
text </ td>         ad description </ td>         Required </ td>

   </ tr>

   
link_url </ td>         link of the advertised object in the format: http: //yoursite.com </ td>

   </ tr>

   
link_media </ td>         previously loaded media object (jpg, gif):               

data.upload.media </ p>        </ td>    </ tr>    

pause_after_moderate </ td>         pause posting moderation </ td>

   </ tr>

   
size </ td>         for banners only:

              <p> ads.materials.banner.sizes </ p>        </ td>    </ tr>

   
categories </ td>         Stacks by category, similar to campaigns:

         <p> array [category_id => cost] </ p>        </ td>

Not required if you do not set bids from campaign categories </ td>

   </ tr> </ table>

Update ad data

Use the ads.materials.update </ b>
method to update ad data. The maximum allowable number of ads generated by a single request is 20.

                                           
Parameters </ th>         Value </ th>         Additional attributes </ th>

   </ tr>

   
data </ ​​td>         is a serialized JSON array of objects describing the created ads. The ad_specification object description is below. </ Td>         required parameter, string </ td>

   </ tr>

   
ad_specification </ td>

   </ tr>

   
material_id </ td>         ad id </ td>         required parameter, int (numeric value) </ td>

   </ tr>

   
status </ td>         start / pause material:            

0 - suspended; </ p>            <p> 1 - running </ p>        </ td>        

optional parameter, int (numeric value), default 1 </ td>

   </ tr> </ table>

Archiving advertisements

For advertising ads using the method ads.materials.delete </ b>
The maximum number of clients edited with a single query is 50.

                           
Parameters </ th>         Value </ th>         Additional attributes </ th>

   </ tr>

   
account_id </ td>         advertising account ID </ td>         required parameter, int (numeric value) </ td>

   </ tr>

   
ids </ td>         serialized JSON array containing ad IDs </ td>         required parameter, string </ td>

   </ tr> </ table>

Result: </ b>
Returns an array of responses to each request. Each answer is either 0, which means successful deletion, or an error array.

Getting a list of advertisements

Use the <b> ads.materials.get </ b> method to get the list of ads.

                                                                           
Parameters </ th>         Value </ th>         Additional attributes </ th>

   </ tr>

   
account_id </ td>         advertising account ID </ td>         required parameter, int (numeric value) </ td>

   </ tr>

   
client_id </ td>         For advertising agencies. Client ID from which advertisements are requested. </ Td>         int (numeric value) </ td>

   </ tr>

   
archive </ td>         A flag that specifies whether to display archived ads:            

0 - display only active ads; </ p>            <p> 1 - display all ads </ p>        </ td>        

Flag, can be 1 or 0 </ td>

   </ tr>

   
campaign_ids </ td>         ad campaign filter.

             <p> Serialized JSON array containing campaign id. If the parameter is null, advertisements of all campaigns will be displayed. </ P>        </ td>

       
string </ td>

   </ tr>

   
material_ids </ td>         ad campaign filter.

             <p> Serialized JSON array containing ad id. If the parameter is null, all advertisements will be displayed. </ P>        </ td>

       
string </ td>

   </ tr>

   
limit </ td>         limit on the number of ads returned. Used only if the ad_ids parameter is null, and the campaign_ids parameter contains the id of only one campaign.

       </ td>

       
int (numeric value) </ td>

   </ tr>

   
offset </ td>         offset. Used in the same cases as the limit parameter </ td>         int (numeric value) </ td>

   </ tr>

   
ad_format </ td>         ad format: ads.campaigns.formats.get </ td>         required parameter, int (numeric value) </ td>

   </ tr> </ table>

Result: </ b>
Returns an array of ad objects, each of which contains the following fields:

  
           
  • <b> id </ b> - ad id </ li>        
  • <b> name </ b> - the name of the ad </ li>        
  • <b> campaign_id </ b> - Campaign ID </ li>        
  • <b> link_url </ b> </ li>        
  • <b> arhive </ b> </ li>        
  • <b> ad_format </ b> - ad format </ li>        
  • <b> cost_type </ b> - payment type </ li>        
  • <b> all_limit </ b> - total ad limit in rubles </ li>             
                             
    • 0 - no limit is set </ li>             </ ul>        
    • <b> status </ b> - ad status: </ li>             
                               
      • 0 - ad stopped; </ li>                        
      • 1 - the ad is running; </ li>                        
      • 2 - ad deleted </ li>             </ ul>        
      • <b> approved </ b> - ad moderation status: </ li>             
                                 
        • 0 - the ad is awaiting moderation; </ li>                        
        • 10 - Ad has been approved. </ li>                        
        • 20 - ad disapproved </ li>             </ ul>   </ ul>

          Getting a list of banner sizes

          For a list of banner sizes, use the <b> ads.materials.banner.sizes.get </ b>
          method

          <b> Result: </ b>
          Returns an array of responses to requests in the response array:

          response: {
                  count:% total%
                  items: [{
                       id:% banner_id%,
                       title: ‘% banner title%’
                  }, ..]
          }
          </ pre>
          </ code>
          
          == Getting the list of countries ==
          To get the list of countries, use the <b> data.geo.countries.get </ b> <br/> method
          
          <b> Result: </ b> <br/>
          Returns an array of responses to requests in the response array:
          <code>
          <pre>
          response: {
              count:%
              items: [{
                  id:% country_id%,
                  title:% country_name%
              }, ..]
          }
          </ pre>
          </ code>
          
          == Getting a list of regions for a given filter ==
          To get a list of regions for a given filter, use the <b> data.geo.regions.get </ b> <br/> method
          
          <table>
             <tr bgcolor = #DCDCDC>
                 <th width = 130 align = left> Parameters </ th>
                 <th width = 300 align = left> Value </ th>
                 <th width = 350 align = left> Additional attributes </ th>
             </ tr>
             <tr bgcolor = # F5F5F5>
                 <td> country_id </ td>
                 <td> country identifier obtained in the ads.geo.countries method </ td>
                 <td> positive number, required parameter </ td>
             </ tr>
          </ table>
          
          <b> Result: </ b> <br/>
          Returns an array of responses to requests in the response array:
          <code>
          <pre>
          response: {
                  count:%
                  items: [{
                         id:% region_id%
                         title:% region_name%
                  }, ..]
          }
          </ pre>
          </ code>
          
          == Get a list of available payment systems ==
          To get a list of available payment systems, use the <b> data.balance.systems.get </ b> <br/> method
          
          <b> Result: </ b> <br/>
          Returns an array of responses to requests in the response array:
          <code>
          <pre>
          response: {
                   count:% total%
                   items: [{
                          id:% pay_system_id%,
                          title: pay% pay system title% ’
                   }, ..]
          }
          </ pre>
          </ code>
          
          == Download media files ==
          To upload media files (jpg, png, gif), use the <b> data.upload.media.update </b> <br/> method
          
          <table>
             <tr bgcolor = #DCDCDC>
                 <th width = 130 align = left> Parameters </th>
                 <th width = 300 align = left> Value </th>
                 <th width = 350 align = left> Additional attributes </th>
             </tr>
             <tr bgcolor = # F5F5F5>
                 <td> ad_format </td>
                 <td> ad format: /ads.formats.get </td>
                 <td> int (numeric value) </td>
             </tr>
             <tr bgcolor = # F5F5F5>
                 <td> file </td>
                 <td> CURLFile object </td>
             </tr>
          </table>
          
          <b> Result: </b> <br/>
          Returns an array with a reference to the target object or error in case of an error.
          <code>
          <pre>
          response: {
                  image: “% link%”
          }
          

          An example of sending a file using curl in php:

                 $ token = ‘received token’;
                 $ ad_format = объявления ad format ’;
                 $ app_id = ‘your app id’;
                 $ file = '@ /full path to file';
          
                 $ finfo = finfo_open (FILEINFO_MIME_TYPE);
                 $ finfo = finfo_file ($ finfo, $ link);
                 $ cFile = new \ CURLFile ($ link, $ finfo, basename ($ link));
          
                 $ post = array ('file' => $ cFile, 'ad_format' => $ ad_format, 'app_id' => $ app_id);
                 $ ignoreParams = array ('file'); //file field is not involved in the construction of the signature
          
                 ksort ($ post);
          
                 $ result = array ();
                 foreach ($ post as $ key => $ value) {
                   if (false == in_array ($ key, $ ignoreParams)) {
          $ result [] = $ key. '='. urlencode ($ value);
          }
                 }
          
                 $ result = implode ('&', $ result);
                 $ signature = md5 ($ result. $ token);
          
                 $ target_url = 'http://api.kadam.net/data.upload.media?signature='. $ signature;
          
                 $ ch = curl_init ();
                 curl_setopt ($ ch, CURLOPT_URL, $ target_url);
                 curl_setopt ($ ch, CURLOPT_POST, true);
                 curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ post);
                 curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1);
          
                 $ result = curl_exec ($ ch); //server response
          

          Get the current server time

          To get the current server time in ISO 8601 format, use the <b> server.time.get </b>
          method

          <b> Result: </b>
          Returns an array of responses to requests in the response array:

                  {
                      iso8601:% time%
                  }
          

          Statistics for Webmasters

          For statistics on webmasters use the method <b> webmaster.reports.report.get </b>

                                                                                                                                         
          Parameters Value Additional attributes
          secret Access key for webmasters (mandatory) Available on demand
          date_from Start of Period a string of the form "YYYY-MM-DD" is an optional parameter; if absent, the current date will be taken
          date_to End of Period a string of the form "YYYY-MM-DD" is an optional parameter; if absent, the current date will be taken

          <b> Maximum unloading period 1 month </b>
          <b> Result:

            
                   
          • blockviews - Block Views
          •        
          • moneyin - Earned money

          Returns data as

          Array
          (
              [responce] => Array
                  (
                      [2017-11-10] => Array
                          (
                              [blockviews] => 300
                              [moneyin] => 100.00
                          )
          
                  )
          
          )
          

          Money transfer for subsidiary accounts of the agency

          To transfer money, use the ads.clients.balance.update method

                                                                                                                                                                     
          Parameters Value Additional attributes
          client_id Customer ID, money will be transferred to it. Required
          sum transfer amount Required
          type Operation Type Required - always type = "transfer"
          comment Comment Required - null value allowed

          The operation can be performed only if there are sufficient funds on the account
          Money will be withdrawn from the user specified in the app_id
          Result:
          The result of the operation will be the withdrawal of funds from the primary user - an output transaction. And the transfer of money to the agency account is an input transaction.

          Returns data as

          Array
          (
              [status] => "success"
          
          )
          

          In case of error - error code