# Наполнение рассылки сообщениями

## Наполнение рассылки

<mark style="color:green;">`POST`</mark> `https://direct.i-dgtl.ru/api/v1/dispatch/{dispatchId}/messages`

#### Path Parameters

| Name                                         | Type    | Description            |
| -------------------------------------------- | ------- | ---------------------- |
| dispatchId<mark style="color:red;">\*</mark> | integer | Идентификатор рассылки |

#### Headers

| Name                                            | Type   | Description        |
| ----------------------------------------------- | ------ | ------------------ |
| Authorization<mark style="color:red;">\*</mark> | string | `Basic {TOKEN_1}`  |
| Content-Type<mark style="color:red;">\*</mark>  | string | `application/json` |

#### Request Body

| Name                                          | Type   | Description                     |
| --------------------------------------------- | ------ | ------------------------------- |
| destination<mark style="color:red;">\*</mark> | string | Номер абонента                  |
| substitutions                                 | object | Подстановки для текста рассылки |

{% tabs %}
{% tab title="200" %}
Возвращаются идентификаторы успешно созданных, а также коды ошибок неуспешных сообщений.

```
[
  {
    "destination": "79818269375",
    "messageUuid": "uuid"
  },
  {
    "destination": "79818228228",
    "errorCode": 7401
  }
]
```

{% endtab %}

{% tab title="401" %}
Использование невалидного токена / отсутствие заголовка авторизации.

{% tabs %}
{% tab title="4012" %}

```
{
    "error": {
        "code": 4012,
        "msg": "Bad credentials"
    }
}
```

{% endtab %}

{% tab title="4010" %}

```
{
    "error": {
        "code": 4010,
        "msg": "Not Authenticated"
    }
}
```

{% endtab %}
{% endtabs %}
{% endtab %}

{% tab title="403" %}
Использование неподходящего токена.

```
{
    "error": {
        "code": 4030,
        "msg": "Access Denied"
    }
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Проверка уникальности `destination` в рамках одной рассылки **не** выполняется

В одном запросе можно передать не более 1000 сообщений
{% endhint %}

{% hint style="warning" %}
Рекомендуемое время ожидания ответа: 70 секунд.\
Как правило, ответ на запрос возвращается не более чем за несколько секунд, но таймаут величиной в 70 секунд позволяет гарантированно получить ответ на запрос, в том числе в ситуациях повышенной нагрузки.
{% endhint %}

### Подстановки <a href="#substitutions" id="substitutions"></a>

Ключи объекта `substitutions` должны соответствовать переменным в тексте рассылки.

#### Текст рассылки: <a href="#dispatch-text" id="dispatch-text"></a>

```
"Уважаемый {{A}}! Рады сообщить, что Вам одобрена кредитная карта на сумму {{B}}, можете забрать ее в ближайшем офисе по адресу {{C}}."
```

#### Объект подстановок: <a href="#substitutions-object" id="substitutions-object"></a>

```
"substitutions": {
    "A": "Сергей Алексеевич",
    "B": "100 тыс. руб.",
    "C": "Санкт-Петербург, Большой проспект П.С., 12"
    }
```

{% hint style="info" %}
При отсутствии подстановок в тексте рассылки, объект `substitutions` будет проигнорирован.
{% endhint %}

### Коды ошибок <a href="#error-codes" id="error-codes"></a>

* При отсутствии хотя бы одной подстановки для сообщения - **7401**
* При невалидном номере абонента - **7402**

### Пример запроса <a href="#example" id="example"></a>

{% tabs %}
{% tab title="JSON" %}

```
POST https://direct.i-dgtl.ru/api/v1/dispatch/10000000125/messages
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Content-Type: application/json
[
  {
    "destination": "79818269375",
    "substitutions": {
    "A": "Сергей Алексеевич",
    "B": "100 тыс. руб.",
    "C": "Санкт-Петербург, Большой проспект П.С., 12"
    }
  },
  {
    "destination": "79818228228",
    "substitutions": {
      "A": "Алексей Сергеевич",
      "B": "1000 рублей"
    }
  }
]
```

{% endtab %}

{% tab title="cURL" %}

```
curl -X POST 'https://direct.i-dgtl.ru/api/v1/dispatch/10000000125/messages' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==' \
-d '[{"destination":"79818269375","substitutions":{"A":"Сергей Алексеевич","B":"100 тыс. руб.","C":"Санкт-Петербург, Большой проспект П.С., 12"}},{"destination":"79818228228","substitutions":{"A":"Алексей Сергеевич","B":"1000 рублей"}}]'
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
Для запуска рассылки необходимо выполнить третий шаг, описанный [здесь](/dispatches/sending/start.md).
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://api.docs.direct.i-dgtl.ru/dispatches/sending/add-messages.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
