# Описание DecisionTelecom API

**Описание DecisionTelecom API**

Ознакомьтесь с полной справочной документацией по API и легко интегрируйте функции SMS, Viber, WhatsApp, чата и голосовой связи на свой веб-сайт или в приложение с помощью API DecisionTelecom.

В качестве транспортного уровня DecisionTelecom API для описываемого протокола выбран HTTPS.

Ключ доступа используется в качестве основы авторизации API. Полезные данные запросов и ответов форматируются как JSON (также мы предоставляем альтернативу GET для запросов), используя кодировку UTF-8 и значения в кодировке URL.

**SDK**

Официальные библиотеки SDK для API DecisionTelecom доступны на нескольких языках: <https://github.com/IT-DecisionTelecom>

**Конечная точка API**

Чтобы использовать API-интерфейсы DecisionTelecom, вам необходимо сначала бесплатно зарегистрироваться на сайте [www.decisiontele.com](http://www.decisiontele.com/)


# SMS API

SMS API DecisionTelecom позволяет отправлять SMS-сообщения в любую страну мира через API. Каждое сообщение идентифицируется уникальным случайным идентификатором, поэтому пользователи всегда могут проверить статус сообщения, используя заданную конечную точку.

SMS API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8 и значений в кодировке URL.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

&#x20;

## Отправить смс

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

```
https://web.it-decision.com/v1/api/send-sms
```

```json
{
    "phone":380632132121,
    "sender":"InfoItd",
    "text":"This is messages DecisionTelecom",
    "validity_period":120
}
```

{% endtab %}
{% endtabs %}

#### Response:

```json
{
    "message_data": [
        {
            "message_id": 26348338,
            "phone": 380632132122,
            "part_count": 1,
            "concat_part": 1,
            "status": "ACCEPTD"
        }
    ]
}
```

## **Статус смс**

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

```
https://web.it-decision.com/v1/api/status?message_id=234234234
```

{% endtab %}
{% endtabs %}

#### **Response:**

```json
{
    "message_id": 26348265,
    "status": "DELIVRD"
}
```

#### **Параметры:**

**message\_id**: <mark style="color:red;">int</mark> - Уникальный случайный идентификатор, созданный на платформе DecisionTelecom.

**Phone:** <mark style="color:red;">int</mark> - Номер телефона, по которому вы хотите выполнить сетевой запрос. Обязательный

**Text:** <mark style="color:red;">string</mark> – текст смс сообщения

**validity\_period:** <mark style="color:red;">int</mark> - Время жизни SMS в минутах (мин. 1 мин., макс. 4320)

**sender:** <mark style="color:red;">string</mark> - Отправитель сообщения, максимальная длина 11 символов

**part\_count:** <mark style="color:red;">int</mark> - количество сообщений

**concat\_part**: <mark style="color:red;">int</mark> - Количество частей сообщения

**status**: <mark style="color:red;">string</mark> - возможный статус смс

#### **Возможные значения status:**

DELIVRD, UNDELIV, ACCEPTD, EXPIRED, REJECTD, ENROUTE, DELETED, UNKNOWN

DELIVERED (DELIVRD) - Сообщение успешно доставлено к конечному пользователю.

EXPIRED (EXPIRED) - Сообщение не было доставлено из-за того, что истекло время ожидания на доставку.

DELETED (DELETED) - Сообщение было удалено и не может быть доставлено.

UNDELIVERABLE (UNDELIV) - Сообщение не может быть доставлено из-за постоянной ошибки (например, неправильный номер или другие проблемы с абонентом).

ACCEPTED (ACCEPTD) - Сообщение было принято системой оператора, но еще не доставлено.

UNKNOWN (UNKNOWN) - Статус сообщения неизвестен, возможно из-за временной проблемы или неидентифицированной причины.

REJECTED (REJECTD) - Сообщение было отклонено системой и не будет доставлено (возможно из-за политики оператора или других технических причин).

ENROUTE (ENROUTE) - Сообщение было передано в сеть, но еще не доставлено конечному пользователю.

## Пример отправки смс

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

```
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/send-sms',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"phone":380632132121,"sender":"InfoItd","text":"This is messages DecisionTelecom","validity_period":300}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api_key',
    'Content-Type: application/json',
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

{% endtab %}

{% tab title="GO" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "web.it-decision.com/v1/api/send-sms"
  method := "POST"

  payload := strings.NewReader(`{"phone":380632132121,"sender":"InfoItd","text":"This is messages DecisionTelecom","validity_period":300}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api_key")
  req.Header.Add("Content-Type", "application/json")
  
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}

{% tab title="Java" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"phone\":380632132121,\"sender\":\"InfoItd\",\"text\":\"This is messages DecisionTelecom\",\"validity_period\":300}");
Request request = new Request.Builder()
  .url("web.it-decision.com/v1/api/send-sms")
  .method("POST", body)
  .addHeader("Authorization", "Basic api_key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();
```

{% endtab %}

{% tab title="С#" %}

```
var client = new RestClient("web.it-decision.com/v1/api/send-sms");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api_key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""phone"":380632132121,""sender"":""InfoItd"",""text"":""This is messages DecisionTelecom"",""validity_period"":300}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api_key");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "phone": 380632132121,
  "sender": "InfoItd",
  "text": "This is messages DecisionTelecom",
  "validity_period": 300
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("web.it-decision.com/v1/api/send-sms", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
```

{% endtab %}

{% tab title="NODE" %}

```
var axios = require('axios');
var data = JSON.stringify({
  "phone": 380632132121,
  "sender": "InfoItd",
  "text": "This is messages DecisionTelecom",
  "validity_period": 300
});

var config = {
  method: 'post',
  url: 'web.it-decision.com/v1/api/send-sms',
  headers: { 
    'Authorization': 'Basic api_key', 
    'Content-Type': 'application/json'  
},
  data : data
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
})
```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "phone": 380632132121,
  "sender": "InfoItd",
  "text": "This is messages DecisionTelecom",
  "validity_period": 300
})
headers = {
  'Authorization': 'Basic api_key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/send-sms", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
```

{% endtab %}

{% tab title="RUBY" %}

```
require "uri"
require "json"
require "net/http"

url = URI("web.it-decision.com/v1/api/send-sms")

http = Net::HTTP.new(url.host, url.port);
request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic api_key"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "phone": 380632132121,
  "sender": "InfoItd",
  "text": "This is messages DecisionTelecom",
  "validity_period": 300
})

response = http.request(request)
puts response.read_body
```

{% endtab %}
{% endtabs %}

## Отчет о доставке смс&#x20;

SMS Callbacks

You can create analytics on your SMS traffic by using event-based webhooks — user-defined HTTP callbacks — to track the delivery status of outgoing messages.

For every SMS message you send, IT-Decision Telecom sends a status update to a URL you configure as a callback. You can store the information on your server for delivery status analysis. Upon one of these events, IT-Decision Telecom makes an HTTP request (POST) to an endpoint URL you’ve configured for the webhook. To handle a webhook, you must create a listener (web app) that can accept these HTTP requests from IT-Decision Telecom. IT-Decision Telecom automatically retries webhooks three times if an HTTP 200 status code is not returned:

Interval - 15 minutes, 12 hours ,  1 day, If your URL is not available for the whole retry period, the data will be lost (Delivery Reports).

{% tabs %}
{% tab title="1. Send method Post client Url callback" %}

```
http://client.com/callback
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Json:" %}

```
[
    {
        "message_id": "26381482",
        "time_delivery": "2022-05-27 12:31:25",
        "phone": "380632132122",
        "status": "2",
        "part_count": "1",
        "concat_part": "1"
    },
    {
        "message_id": "26381475",
        "time_delivery": "2022-05-27 07:17:44",
        "phone": "380631211121",
        "status": "2",
        "part_count": "1",
        "concat_part": "1"
    },
    {
        "message_id": "26381473",
        "time_delivery": "2022-05-27 07:04:15",
        "phone": "380631111111",
        "status": "2",
        "part_count": "1",
        "concat_part": "1"
    }
]

```

{% endtab %}
{% endtabs %}

#### Possible values of **status**:

**Params:**

**phone**:  - The telephone number that you want to do a network query on. - Required.

**Time\_delivery** - SMS delivery time  format DATETIME (utc + 0)

**part\_count**:  - amount of messages

**concat\_par**t:  - Number of pieces of the message

**status**:  - possible sms status

ENROUTE = 1;

DELIVERED = 2;

EXPIRED = 3;

DELETED = 4;

UNDELIVERABLE = 5;

ACCEPTED = 6;

UNKNOWN = 7;

REJECTED = 8;

## Массовая отправка смс

HTTP Authorization - Basic access key Base64

## Отправка сообщений

{% tabs %}
{% tab title="1. POST REQUEST json string" %}

```
https://web.it-decision.com/v1/api/multiple-message
```

```
{
	"phones": [380631111112, 380636151111],
	"sender": "info",
	"text": "when the text is more than 160 characters, the SMS is divided into several parts",
	"validity_period": 300
}
```

{% endtab %}
{% endtabs %}

#### **Response :**

```
[
    [
        {
            "message_id": 26381268,
            "phone": 380631111112,
            "part_count": 2,
            "concat_part": 1,
            "status": "ACCEPTD"
        },
        {
            "message_id": 26381269,
            "phone": 380631111112,
            "part_count": 2,
            "concat_part": 2,
            "status": "ACCEPTD"
        }
    ],
    [
        {
            "message_id": 26381270,
            "phone": 380636151111,
            "part_count": 2,
            "concat_part": 1,
            "status": "ACCEPTD"
        },
        {
            "message_id": 26381271,
            "phone": 380636151111,
            "part_count": 2,
            "concat_part": 2,
            "status": "ACCEPTD"
        }
    ]
]

```

#### Params:

<mark style="color:red;">message\_id</mark> **int** A unique random ID which is created on the DecisionTelecom platform.

**Phones** array The telephone number that you want to do a network query on.

**sende**r string The sender of the message. This can be a mobile phone number (including a country code) or an alphanumeric string. The maximum length of alphanumeric strings is 11 characters. &#x20;

**text**    string  Each multi-part text message is limited to 153 characters rather than 160 due to the need for user-data headers (UDHs) information.(  306 (2x153 characters) ,459 characters (3 x 153)…)

Mobile phones use UDH information to enable them to link long messages together so that they appear as single SMS messages in recipient’s phone inbox. Using Unicode, for languages such as Hindi, restricts your message to a maximum of 70 characters per SMS .

The maximum lengths of two-part and three-part multi-part Unicode text messages are 134 (2 x 67) and 201 (3 x 67) characters, respectively.

**part\_count** int  Count of parts

**concat\_part** int Part number

**validity\_period** int SMS lifetime  min 2 minute max 4320

## Примеры массовой отправки смс

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

```
curl --location --request POST 'https://web.it-decision.com/v1/api/multiple-message' \
--header 'Authorization: api key base64' \
--header 'Content-Type: application/json' \
--data-raw '{"phones":[380631111112,380636151111],"sender":"info","text":"when the text is more than 160 characters, the SMS is divided into several parts","validity_period":300}'

```

{% endtab %}

{% tab title="Golang" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://web.it-decision.com/v1/api/multiple-message"
  method := "POST"

  payload := strings.NewReader(`{"phones":[380631111112,380636151111],"sender":"info","text":"when the text is more than 160 characters, the SMS is divided into several parts","validity_period":300}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key base64")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

```

{% endtab %}

{% tab title=" C#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/multiple-message");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""phones"":[380631111112,380636151111],""sender"":""info"",""text"":""when the text is more than 160 characters, the SMS is divided into several parts"",""validity_period"":300}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

```

{% endtab %}

{% tab title=" JAVA" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"phones\":[380631111112,380636151111],\"sender\":\"info\",\"text\":\"when the text is more than 160 characters, the SMS is divided into several parts\",\"validity_period\":300}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/multiple-message")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();

```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api key");
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
  "phones": [
    380631111112,
    380636151111
  ],
  "sender": "info",
  "text": "when the text is more than 160 characters, the SMS is divided into several parts",
  "validity_period": 300
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://web.it-decision.com/v1/api/multiple-message", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

```

{% endtab %}

{% tab title="C lib CURL" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/multiple-message");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  const char *data = "{\"phones\":[380631111112,380636151111],\"sender\":\"info\",\"text\":\"when the text is more than 160 characters, the SMS is divided into several parts\",\"validity_period\":300}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);

```

{% endtab %}

{% tab title="NodJs" %}

```
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/multiple-message',
  'headers': {
    'Authorization': 'Basic api key,
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "phones": [
    380631111112,
    380636151111
  ],
  "sender": "info",
  "text": "when the text is more than 160 characters, the SMS is divided into several parts",
  "validity_period": 300
});

req.write(postData);

req.end();

```

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/multiple-message',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"phones":[380631111112,380636151111],"sender":"info","text":"when the text is more than 160 characters, the SMS is divided into several parts","validity_period":300}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "phones": [
    380631111112,
    380636151111
  ],
  "sender": "info",
  "text": "when the text is more than 160 characters, the SMS is divided into several parts",
  "validity_period": 300
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json',
 
}
conn.request("POST", "/v1/api/multiple-message", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))


```

{% endtab %}
{% endtabs %}

## Проверка баланса

#### Method GET

HTTP Authorization - Basic access key Base64

#### Request: header ‘Authorization basic api key’

{% tabs %}
{% tab title="Response json:" %}

```
{
    "balance": "6123.9500000",
    "currency": "UAH",
    "credit": 0
}

```

{% endtab %}
{% endtabs %}

## Примеры Проверки баланса

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

```
curl --location --request GET 'https://web.it-decision.com/v1/api/balance' \
--header 'Authorization: Basic api key' \

JAVA:
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/balance")
  .method("GET", body)
  .addHeader("Authorization", "Basic api key")
  
Response response = client.newCall(request).execute();

```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api key");
var urlencoded = new URLSearchParams();

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  body: urlencoded,
  redirect: 'follow'
};

fetch("https://web.it-decision.com/v1/api/balance", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

C lib curl

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/balance");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");

  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
```

{% endtab %}

{% tab title="NodeJS" %}

```
var https = require('follow-redirects').https;
var fs = require('fs');

var qs = require('querystring');

var options = {
  'method': 'GET',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/balance',
  'headers': {
    'Authorization': 'Basic api key'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = qs.stringify({

});

req.write(postData);

req.end();
```

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/balance',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key'
    ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

{% endtab %}

{% tab title="C#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/balance");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Basic api key");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
```

{% endtab %}

{% tab title="Python" %}

```
import http.client

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = ''
headers = {
  'Authorization': 'Basic api key'
}
conn.request("GET", "/v1/api/balance", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

```

{% endtab %}
{% endtabs %}

## **SMPP SMS API**

Short Message Peer-to-Peer (SMPP protocol)

Используется для отправки и получения больших объемов SMS-трафика. Протокол SMPP особенно популярен среди SMS-провайдеров и операторов связи.

Пожалуйста, свяжитесь с одним из наших консультантов, чтобы получить данные для подключения по SMPP протоколу.

## Сервер для подключения

Ниже указаны данные для подключения к SMPP-серверу DecisionTelecom:

Имя хоста Порт TLS порт

web.it-decision.com 2888 2999

## **Имя пользователя и пароль**

Менеджер вашего аккаунта в DecisionTelecom предоставит вам имя пользователя (system\_id) и пароль. Если вы еще не получили их или вам все еще нужно сделать запрос, просто отправьте нам электронное письмо по адресу <support@it-decision.com>; мы будем рады помочь вам.

## **Подключение и пропускная способность**

Всякий раз, когда для вас будет настроена учетная запись SMPP, вы получите нужное количество подключений (биндов) и пропускную способность. В большинстве случаев эти значения будут 1 бинд и 50 сообщений в секунду.

Интересно отметить, что эти значения могут быть выше по требованию клиента.

## **Безопасность**

Если вы подключаетесь к какому-либо серверу через TLS-соединение, обязательно выберите TCP-порт 2999. Также имейте в виду, что серверы принимают методы SSLv1, SSLv2, SSLv3.

## **Bind PDU**

Запрос PDU SMPP bind\_receiver, bind\_transceiver или bind\_transmitter имеет фиксированный набор полей. Большинство полей для нас не имеют значения; на самом деле мы читаем только поля system\_id, password и interface\_version, а остальное игнорируем.

## **Версия интерфейса**

SMPP-сервер DecisionTelecom поддерживает версии протокола SMPP 3.4. Имейте в виду, что если вы настроите свой SMPP-клиент для версии 3.3, вы упустите некоторые функции, в первую очередь информацию TLV в получаемых вами PDU Deliver\_sm.

## **Submit\_sm PDU**

Вы можете использовать PDU submit\_sm для отправки нам ваших сообщений. Запрос PDU submit\_sm также имеет пару полей, которые не используются нашей платформой и могут быть спокойно проигнорированы.

## **Data\_coding**

Значения поля data\_coding не объявлены четко в спецификации SMPP, поэтому каждый SMPP-сервер более или менее обязан давать свое собственное определение. Ниже приведен список кодировок данных, которые мы принимаем в качестве входных данных.

| Value | Encoding                                      |
| ----- | --------------------------------------------- |
| 0     | GSM7                                          |
| 1     | ASCII                                         |
| 2     | 8BIT                                          |
| 3     | ISO-8859-15 West European languages (Latin-9) |
| 6     | ISO-8859-5 Latin/Cyrillic                     |
| 7     | ISO-8859-8 Latin/Hebrew                       |
| 8     | UTF-16BE (UCS2)                               |


# VIBER API

DecisionTelecom Viber API позволяет отправлять и получать деловые сообщения Viber в любую страну мира и из нее через API. Каждое сообщение идентифицируется уникальным случайным идентификатором, поэтому пользователи всегда могут проверить статус сообщения, используя заданную конечную точку.

Viber API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## **Авторизация**&#x20;

## Basic Auth

#### Пример:

```
$userHashKey = 'User Hash Key provided by your account manager';
$ch = curl_init('https://web.it-decision.com/v1/api/send-viber');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$userHashKey");
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestParams)); // 
$requestParams - raquest array with correct data 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
$result = curl_exec($ch); 
curl_close($ch);
```

## **Отправить Вайбер сообщение**

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

```
https://web.it-decision.com/v1/api/send-viber
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
Example for text-image-button messages:
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,							
	"message_type":108, 									
	"text":"Message content", 										
	"image":"https://yourdomain.com/images/image.jpg", 		
	"button_caption":"Join Us", 							
	"button_action":"https://yourdomain.com/join-us",   	
	"source_type":1, 										
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":3600
}

Example for promotional text messages:
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,	
	"message_type":225, 								
	"text":"Message content",
	"source_type":1, 	
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":3600
}

Example for send file:
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,						
	"message_type":222, 
	"file_url":" https://yourdomain.com/files/custom.pdf ",	
	"source_type":1, 								
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":180
}

Example for transactional template messages:
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,	
	"message_type":304, 
	"text":"Message content",							
	"source_type":2,
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":180
}

Example for carousel messages:
{
	"source_addr": "Custom Company",
	"destination_addr": 8882222200,
	"message_type":901,
	"source_type":1,
	"validity_period":6800,
	"text":"Message content",
	"carousel": {
	    "items": [
	      {
	        "title": "50% Off on All Shoes!50%",
	        "imageUrl": "https://example.com/images/sale.jpg",
	        "primaryButton": {
	          "label": "Shop Now",
	          "actionUrl": "https://example.com/shoes-sale"
	        },
	        "secondaryButton": {
	          "label": "View Details",
	          "actionUrl": "https://example.com/shoes-sale"
	        }
	      },
	      {
	        "title": "New Arrivals: Summer Collection",
	        "imageUrl": "https://example.com/images/sum.jpg",
	        "primaryButton": {
	          "label": "Explore",
	          "actionUrl": "https://example.com/summer"
	        },
	        "secondaryButton": {
	          "label": "Learn More",
	          "actionUrl": "https://example.com/summer-info"
	        }
	      }
	    ]
	  }
}
```

{% endtab %}
{% endtabs %}

### **Параметры**

**source\_addr:**

от 3 до 20 символов - от кого сообщение

**destination\_addr:**

от 11 до 20 цифр – кому сообщение

**message\_type (тип отправленного сообщения):**

6 - только текст (для основного устройства)&#x20;

225 - только текст (для всех устройств)&#x20;

8 - текст+изображение+кнопка (для основного устройства)

108 - текст+изображение+кнопка (для всех устройств)&#x20;

9 - текст+кнопка (для основного устройства)&#x20;

109 - текст+кнопка (для всех устройств)&#x20;

222 - отправить файл (для всех устройств), поддерживаемые форматы: .doc, .docx, .rtf, .dot, .dotx, .odt ,odf, .fodt, .txt, .info, .pdf, .xps, .pdax, .eps, xls, .xlsx, .ods, .fods, .csv, .xlsm, .xltx&#x20;

301 - транзакционный шаблонный текст (для основного устройства)&#x20;

304 - транзакционный шаблонный текст (для всех устройств)

901 - карусель (для всех устройств)

**text:**

до 1000 символов - текст Viber сообщения

**image (Правильный URL-адрес с изображением для рекламного сообщения с заголовком кнопки и действием кнопки):**

jpg or jpeg (тип mime — изображение/jpeg), максимальное разрешение 800x800 пикселей

png (тип mime — image/png), максимальное разрешение 800x800 пикселей

**button\_caption:**

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

**button\_action:**

Правильный URL для перехода при нажатии кнопки

**source\_type (Процедура отправки сообщения):**

promotion message (сообщение может быть с текстом, изображением, кнопкой) - 1

transactional message (текстовое шаблонное сообщение) – 2

**callback\_url:**

Правильный URL для обратного вызова статуса сообщения

**validity\_period:**

TTL (время жизни) позволяет отправителю ограничить время жизни сообщения. В случае, если сообщение не получило статус «доставлено» до истечения времени, сообщение не будет списано и не будет доставлено пользователю. В случае, если TTL не был указан (нет параметра «ttl»), Viber будет пытаться доставить сообщение в течение 1 дня.

promotion message - мин. TTL 60 секунд макс. TTL 43200 секунд (12 часов)

transactional message - мин. TTL 60 секунд макс. TTL 43200 секунд(12 часов)

**file\_url:**

Параметр только для типа сообщений 222, должен содержать корректный URL документа.\
Расширения файлов, разрешённые к отправке: .doc, .docx, .rtf, .dot, .dotx, .odt ,odf, .fodt, .txt, .info, .pdf, .xps, .pdax, .eps, xls, .xlsx, .ods, .fods, .csv, .xlsm, .xltx\
Файл должен содержать расширение и его название не может превышать 25 символов.\
Размер файла не должен превышать 200 MB.

**carousel:**&#x20;

Тип сообщения позволяет компаниям отправлять одно сообщение с текстом и несколькими\
настраиваемыми лементами, каждый из которых может демонстрировать различные продукты или услуги. \
Тип сообщения позволяет представлять от 2 до 5 отдельных элементов. Каждый элемент карусели включает изображение, краткое описание и до 2-х настраиваемых кнопок. Все элементы в карусели могут иметь разные наборы кнопок.

**items:** от 2 до 5 карусельных элементов.

* title (Mandatory) - Текст заголовка элемента. От 2 до 38 символов UTF-8.
* imageUrl (Mandatory) - Ожидаемые форматы - PNG, JPEG, jpg. Рекомендуемый размер: 215x185
* primaryButton (Mandatory) - Содержит набор основных параметров кнопки.
* secondaryButton (Optional) - Содержит набор параметров вторичной кнопки.
* label (Mandatory) - Параметр кнопки. Текст, который будет отображаться на кнопке действия. До 10 символов UTF-8 внутри primaryButton. До 12 символов UTF-8 внутри secondaryButton.
* actionUrl (Mandatory) - Параметр кнопки. URL-адрес, на который перенаправляются пользователи, или действие, выполняемое при нажатии кнопки действия\или касании изображения.

### Response:

{% tabs %}
{% tab title="JSON (POST)" %}

```json
{
     "message_id":4291235
}
```

{% endtab %}
{% endtabs %}

### **Значения**:

**message\_id:**

Идентификатор отправленного сообщения

## **Получить Вайбер сообщение**

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

```
 https://web.it-decision.com/v1/api/receive-viber
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
{
     "message_id":4291235
}
```

{% endtab %}
{% endtabs %}

### **Параметры**

**message\_id:**

ID сообщения, статус которого вы хотите получить (за последние 30 дней)

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

```json
{
     "message_id":4291235, 			
     "status":1, 					
}
```

{% endtab %}
{% endtabs %}

### **Значения**

**message\_id:**

ID сообщения, статус которого вы хотите получить (за последние 30 дней)

**status:**

Текущий статус сообщения Viber

## **Получить Вайбер сообщения массово**

Количество проверяемых сообщений — не более 200 в одном запросе.

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

```
 https://web.it-decision.com/v1/api/receive-bulk-viber
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
[
     {"message_id":11017894},
     {"message_id":11017879},
     {"message_id":11017865},
     {"message_id": ... n}
]
```

{% endtab %}
{% endtabs %}

### **Параметры**

**message\_id:**

ID сообщения, статус которых вы хотите получить (за последние 30 дней)

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

```json
{
    "11017894": {
        "message_id": 11017894,
        "status": 1
    },
    "11017879": {
        "message_id": 11017879,
        "status": 1
    },
    "11017865": {
        "name": "Empty parameter or parameter validation error",
        "message": "Invalid Parameter: message_id 11017865 is not accepted for you",
        "code": 1,
        "status": 400
    }
}
```

{% endtab %}
{% endtabs %}

### **Значения**

**message\_id:**

ID сообщения, статус которого вы хотите получить (за последние 30 дней)

**status:**

Текущий статус сообщения Viber

## **Получение Callback**

Обратный вызов будет возвращен на URL, указанный при отправке сообщения в параметре callback\_url

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

```json
{
    "message_id":4291235,                                 
    "status":1                                                                       
}

If the status is 3 (Rejected) then the additional parameter reject_code will be returned:
{
    "message_id":4291235,                                 
    "status":1,         
    "reject_code":9                                              
}

If the message type being sent is 301 or 304 (template transactional text) then the additional parameter matching_template_id will be returned
{
    "message_id":4291235,                                 
    "status":1,         
    "matching_template_id":11079289                                                            
}
```

{% endtab %}
{% endtabs %}

### Значения:

**message\_id:**

&#x20;ID сообщения

**status:**

Текущий статус сообщения

**reject\_code:**

код, возвращаемый Viber при отклонении сообщения:

1 - Внутренняя ошибка сервера.&#x20;

2 - Идентификатор не использовался более года/Идентификатор был недавно создан и еще не загружен на сервер.&#x20;

3 - Ошибка в структуре запроса. Возможно, пропущена запятая, скобки, текст длиной более 1000 символов и т. д.&#x20;

5 - Неверный тип сообщения. Либо неподдерживаемый тип, либо неверное значение.&#x20;

6 - Отсутствуют обязательные параметры.&#x20;

7 - Указывает на тайм-аут сервера на стороне Viber.&#x20;

8 - Идентификатор был заблокирован пользователем/Пользователь полностью заблокировал деловые сообщения на своем устройстве.&#x20;

9 - Номер назначения не зарегистрирован как пользователь Viber.&#x20;

10 - Устройство не Android или iOS с версией Viber, поддерживающей деловые сообщения.&#x20;

11 - Запрос был отправлен с IP-адреса, не входящего в белый список для этого идентификатора/В запросе использован неверный идентификатор, не принадлежащий партнеру.&#x20;

13 - Ошибка в процессе выставления счета&#x20;

18 - Отсутствует значение/Неверное значение в запросе параметра «label».&#x20;

28 - Файл, который пытаются отправить, не имеет поддерживаемого формата для этой функции.&#x20;

29 - Имя файла превышает максимально допустимые 25 символов.

30 - Если URL-адрес миниатюры состоит из более чем 1000 символов.

40 - Один из параметров сообщений списка не прошел проверку.

41 - Один из параметров сообщений карусели не прошел проверку.

**matching\_template\_id:**

ID, выданный Viber при регистрации шаблона. Если параметр присутствует и значение параметра пустое, это означает, что сообщение не соответствует ни одному из зарегистрированных шаблонов и было перетарифицировано с транзакционного на рекламное сообщение на стороне Viber.

## **Статусы сообщений Viber:**

| Name        | Status code |
| ----------- | ----------- |
| sent        | 0           |
| delivered   | 1           |
| error       | 2           |
| rejected    | 3           |
| undelivered | 4           |
| pending     | 5           |
| seen        | 6           |
| unknown     | 20          |

## **Ошибки:**

| Name    | Too Many Requests   |
| ------- | ------------------- |
| message | Rate limit exceeded |
| code    | 0                   |
| status  | 429                 |

| Name    | Empty parameter or parameter validation error |
| ------- | --------------------------------------------- |
| message | Invalid Parameter: \<param>                   |
| code    | 1                                             |
| status  | 400                                           |

#### param:

destination\_addrr more than 20 chars

wrong viber user account

source\_type is wrong

source\_type or message\_type is wrong

source\_type is wrong, because the account is another type

message\_type is wrong

empty text

text more than 1000 chars

transaction message error - not empty image, button\_caption or button\_action

message\_type is wrong - not empty image, button\_caption or button\_action

message\_type is wrong - empty image, button\_caption or button\_action

message\_type is wrong - empty button\_caption or button\_action

image is not url

image url wrong scheme

image not valid type

image is not valid

image size is more than 800x800

button\_action is empty

button\_caption is empty

button\_caption or button\_action is empty

image or button\_action is empty

image or button\_caption is empty

callback\_url is not url

callback\_url url wrong scheme

button\_action is not url

button\_action url wrong scheme

button\_action more than 30 chars

message\_id \<message\_id> is not accepted for you

file\_url is not url

file\_url wrong scheme

file\_url contains an invalid file type or extension, possible file extensions to send: .doc, .docx, .rtf, .dot, .dotx, .odt ,odf, .fodt, .txt, .info, .pdf, .xps, .pdax, .eps, xls, .xlsx, .ods, .fods, .csv, .xlsm, .xltx

button\_caption is not applicable with file\_url

button\_action is not applicable with file\_url

image is not applicable with file\_url

wrong message type for file\_url

file\_url is not applicable in this context

| Name    | Internal server error                                                                         |
| ------- | --------------------------------------------------------------------------------------------- |
| message | The server encountered an unexpected condition which prevented it from fulfilling the request |
| code    | 2                                                                                             |
| status  | 500                                                                                           |

| Name    | Topup balance is required |
| ------- | ------------------------- |
| message | Sender balance is empty   |
| code    | 3                         |
| status  | 402                       |

| Name    | Duplicate error                  |
| ------- | -------------------------------- |
| message | Duplicate Viber message detected |
| code    | 4                                |
| status  | 400                              |

| Name    | Message Template error                  |
| ------- | --------------------------------------- |
| message | The message does not match any template |
| code    | 5                                       |
| status  | 400                                     |

| Name    | Authorization error |
| ------- | ------------------- |
| message | Unauthorized        |
| code    | 6                   |
| status  | 401                 |

## Примеры:

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

```
curl --location --request POST 'https://web.it-decision.com/v1/api/send-viber' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data-raw '{"source_addr": "Custom Company", "destination_addr": 8882222200,"message_type":106,"text":"Message content","image":"https://yourdomain.com/images/image.jpg","button_caption":"Join Us","button_action":"https://yourdomain.com/join-us","source_type":1,"callback_url":"https://yourdomain.com/viber-callback","validity_period":3600}'

```

{% endtab %}

{% tab title="С#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/send-viber");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""source_addr"": ""Custom Company"", ""destination_addr"": 8882222200,""message_type"":106,""text"":""Message content"",""image"":""https://yourdomain.com/images/image.jpg"",""button_caption"":""Join Us"",""button_action"":""https://yourdomain.com/join-us"",""source_type"":1,""callback_url"":""https://yourdomain.com/viber-callback"",""validity_period"":3600}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

```

{% endtab %}

{% tab title="Golang" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://web.it-decision.com/v1/api/send-viber"
  method := "POST"

  payload := strings.NewReader(`{"source_addr": "Custom Company", "destination_addr": 8882222200,"message_type":106,"text":"Message content","image":"https://yourdomain.com/images/image.jpg","button_caption":"Join Us","button_action":"https://yourdomain.com/join-us","source_type":1,"callback_url":"https://yourdomain.com/viber-callback","validity_period":3600}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

```

{% endtab %}

{% tab title="Java" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"source_addr\": \"Custom Company\", \"destination_addr\": 8882222200,\"message_type\":106,\"text\":\"Message content\",\"image\":\"https://yourdomain.com/images/image.jpg\",\"button_caption\":\"Join Us\",\"button_action\":\"https://yourdomain.com/join-us\",\"source_type\":1,\"callback_url\":\"https://yourdomain.com/viber-callback\",\"validity_period\":3600}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/send-viber")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();

```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api key");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "source_addr": "Custom Company",
  "destination_addr": 8882222200,
  "message_type": 106,
  "text": "Message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 1,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://web.it-decision.com/v1/api/send-viber", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

```

{% endtab %}

{% tab title="C – lib cUrl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/send-viber");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"source_addr\": \"Custom Company\", \"destination_addr\": 8882222200,\"message_type\":106,\"text\":\"Message content\",\"image\":\"https://yourdomain.com/images/image.jpg\",\"button_caption\":\"Join Us\",\"button_action\":\"https://yourdomain.com/join-us\",\"source_type\":1,\"callback_url\":\"https://yourdomain.com/viber-callback\",\"validity_period\":3600}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);

```

{% endtab %}

{% tab title="NodeJs" %}

```
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/send-viber',
  'headers': {
    'Authorization': 'Basic api key',
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "source_addr": "Custom Company",
  "destination_addr": 8882222200,
  "message_type": 106,
  "text": "Message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 1,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
});

req.write(postData);

req.end();

```

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/send-viber',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"source_addr": "Custom Company", "destination_addr": 8882222200,"message_type":106,"text":"Message content","image":"https://yourdomain.com/images/image.jpg","button_caption":"Join Us","button_action":"https://yourdomain.com/join-us","source_type":1,"callback_url":"https://yourdomain.com/viber-callback","validity_period":3600}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "source_addr": "Custom Company",
  "destination_addr": 8882222200,
  "message_type": 106,
  "text": "Message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 1,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/send-viber", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

```

{% endtab %}

{% tab title="Ruby" %}

```
require "uri"
require "json"
require "net/http"

url = URI("https://web.it-decision.com/v1/api/send-viber")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic api key"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "source_addr": "Custom Company",
  "destination_addr": 8882222200,
  "message_type": 106,
  "text": "Message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 1,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
})

response = https.request(request)
puts response.read_body
```

{% endtab %}
{% endtabs %}


# WhatsApp Business API

DecisionTelecom WhatsApp API позволяет отправлять и получать деловые сообщения WhatsApp в любую страну мира и из нее через API. Каждое сообщение идентифицируется уникальным случайным идентификатором, поэтому пользователи всегда могут проверить статус сообщения, используя заданную конечную точку.

WhatsApp API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## Auth

## Basic Auth

{% tabs %}
{% tab title="Example PHP:" %}

```
$userHashKey = 'User Hash Key provided by your account manager';
	$ch = curl_init('https://web.it-decision.com/v1/api/send-whatsapp');
	curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
	curl_setopt($ch, CURLOPT_USERPWD, "$userHashKey");
	curl_setopt($ch, CURLOPT_TIMEOUT, 30);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestParams)); // $requestParams - raquest array with correct data
	curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
	$result = curl_exec($ch);
	curl_close($ch);
```

{% endtab %}
{% endtabs %}

## API Send WhatsApp message

{% tabs %}
{% tab title="POST:" %}

```
https://web.it-decision.com/v1/api/send-whatsapp
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
{
    "source_addr": "Custom Company",             
    "destination_addr": 8882222200,              
    "message_type":1,                   
    "text":"Message content",                     
    "file_url":"https://yourdomain.com/images/image.jpg", // file extension is a mandatory attribute
    "callback_url":"https://yourdomain.com/whatsapp-callback",
    "template_name":"image_tmp_en",               
    "template_params":"{
        "to": "recipient_wa_id",
        "type": "template",
        "template": {
        "namespace": "your-namespace",
        "language": {
          "policy": "deterministic",
          "code": "your-language-and-locale-code"
        },
        "name": "your-template-name",
        "components": [
        {
          "type" : "header",
          "parameters": [
          // The following parameters code example includes several different possible header types, 
          // not all are required for a media message template API call.

          {
          "type": "text",
          "text": "replacement_text"
          }

          // OR

          {
          "type": "image",
          "image": {
            "link": "http(s)://the-url",
            # provider is an optional parameter
            "provider": {
            "name" : "provider-name"
            },
          }
          }
        ]
        // end header
        },
        {
          "type" : "body",
          "parameters": [
          {
            "type": "text",
            "text": "replacement_text"
          },
          {
            // Any additional template parameters
          }
          ] 
          // end body
          },
        ]
        }
    }"
  }
```

{% endtab %}
{% endtabs %}

**source\_addr:**

&#x20;           <= 20 chars - from whom the message

**destination\_addr:**

&#x20;           <= 20 chars - to whom the message

**message\_type:**

&#x20;           Type of message to be sent:

&#x20;           1 text message

&#x20;           2 message with media data (jpg, jpeg or png images)

&#x20;           4 message based on registered template

**text:**

&#x20;           <= 4096 chars - text of WhatsApp message

**file\_url:**

&#x20;           Correct URL with image for media message. Correct file extensions:

&#x20;           jpg or jpeg (mime type is image/jpeg)

&#x20;           png (mime type is image/png)

**callback\_url:**

&#x20;           Correct URL  for message status callback    &#x20;

**template\_name:**

&#x20;           Registered template name (only for template message)

**template\_params:**

&#x20;           JSON data of all the necessary parameters to send a template message.&#x20;

{% tabs %}
{% tab title="See details at:" %}

```
 https://developers.facebook.com/docs/whatsapp/api/messages/message-templates/media-message-templates
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Responce JSON (POST):" %}

```json
{
   "message_id":554	
}
```

{% endtab %}
{% endtabs %}

**message\_id:**

Sent message ID

## API Receive WhatsApp message:

{% tabs %}
{% tab title="POST: " %}

```
https://web.it-decision.com/v1/api/receive-whatsapp
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
{
   "message_id":554	
}
```

{% endtab %}
{% endtabs %}

**message\_id:**

The ID of the message whose status you want to get

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

<pre class="language-json"><code class="lang-json">{
   "message_id":554, 			
<strong>   "status":1, 					
</strong>}
</code></pre>

{% endtab %}
{% endtabs %}

**message\_id:**

The ID of the message whose status you want to get         &#x20;

**status:**

Current WhatsApp message status

## WhatsApp messages statuses

| sent      | 0 |
| --------- | - |
| delivered | 1 |
| rejected  | 2 |
| error     | 3 |
| failed    | 4 |
| deleted   | 5 |
| pending   | 6 |
| seen      | 7 |

## &#x20;Errors

| name    | Too Many Requests   |
| ------- | ------------------- |
| message | Rate limit exceeded |
| code    | 0                   |
| status  | 429                 |

| name    | Invalid Parameter: \[param\_name]             |
| ------- | --------------------------------------------- |
| message | Empty parameter or parameter validation error |
| code    | 1                                             |
| status  | 4                                             |

| name    | Internal server error                                                                         |
| ------- | --------------------------------------------------------------------------------------------- |
| message | The server encountered an unexpected condition which prevented it from fulfilling the request |
| code    | 2                                                                                             |
| status  | 500                                                                                           |

| name    | Topup balance is required |
| ------- | ------------------------- |
| message | User balance is empty     |
| code    | 3                         |
| status  | 402                       |

| name    | Internal server error                                                                         |
| ------- | --------------------------------------------------------------------------------------------- |
| message | The server encountered an unexpected condition which prevented it from fulfilling the request |
| code    | 4, // 5 and 6                                                                                 |
| status  | 500                                                                                           |

| name    | Service Unavailable                                                                                                                                              |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| message | Message failed to send because more than 24 hours have passed since the customer last replied to this number. In this case, you can only send a template message |
| code    | 7                                                                                                                                                                |
| status  | 503                                                                                                                                                              |

| name    | Invalid credintals for file\_url |
| ------- | -------------------------------- |
| message | Invalid MIME type file\_url      |
| code    | 8                                |
| status  | 401                              |

| name    | Invalid credintals for file\_url |
| ------- | -------------------------------- |
| message | Invalid file extension           |
| code    | 9                                |
| status  | 401                              |

## Примеры Отправки WhatsApp сообщений:

{% tabs %}
{% tab title="сURL" %}

```
curl --location 'https://web.it-decision.com/v1/api/send-whatsapp' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data ' {"to":"38063xxxxxxx","type":"template","template":{"namespace":"xxxxx_xxxx_xxx_
```

{% endtab %}

{% tab title=" C#  HttpClient" %}

```
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://web.it-decision.com/v1/api/send-whatsapp");
request.Headers.Add("Authorization", "Basic api key");
var content = new StringContent(" {\"to\":\"38063xxxxxxx\",\"type\":\"template\",\"template\":{\"namespace\":\"xxxxx_xxxx_xxx_xxx_xxxxx\",\"language\":{\"policy\":\"deterministic\",\"code\":\"en_US\"},\"name\":\"media_2_english\",\"components\":[{\"type\":\"header\",\"parameters\":[{\"type\":\"image\",\"image\":{\"link\":\"url image.jpg\"}}]}]}}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```

{% endtab %}

{% tab title="GO" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://web.it-decision.com/v1/api/send-whatsapp"
  method := "POST"

  payload := strings.NewReader(` {"to":"38063xxxxxxx","type":"template","template":{"namespace":"xxxxx_xxxx_xxx_xxx_xxxxx","language":{"policy":"deterministic","code":"en_US"},"name":"media_2_english","components":[{"type":"header","parameters":[{"type":"image","image":{"link":"url image.jpg"}}]}]}}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}

{% tab title="Java OkHttp" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, " {\"to\":\"38063xxxxxxx\",\"type\":\"template\",\"template\":{\"namespace\":\"xxxxx_xxxx_xxx_xxx_xxxxx\",\"language\":{\"policy\":\"deterministic\",\"code\":\"en_US\"},\"name\":\"media_2_english\",\"components\":[{\"type\":\"header\",\"parameters\":[{\"type\":\"image\",\"image\":{\"link\":\"url image.jpg\"}}]}]}}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/send-whatsapp")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();
```

{% endtab %}

{% tab title="C -libcurl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/send-whatsapp";
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = " {\"to\":\"38063xxxxxxx\",\"type\":\"template\",\"template\":{\"namespace\":\"xxxxx_xxxx_xxx_xxx_xxxxx\",\"language\":{\"policy\":\"deterministic\",\"code\":\"en_US\"},\"name\":\"media_2_english\",\"components\":[{\"type\":\"header\",\"parameters\":[{\"type\":\"image\",\"image\":{\"link\":\"url image.jpg\"}}]}]}}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
```

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/send-whatsapp',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>' {"to":"38063xxxxxxx","type":"template","template":{"namespace":"xxxxx_xxxx_xxx_xxx_xxxxx","language":{"policy":"deterministic","code":"en_US"},"name":"media_2_english","components":[{"type":"header","parameters":[{"type":"image","image":{"link":"url image.jpg"}}]}]}}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
```

{% endtab %}

{% tab title="NodJs" %}

```
var request = require('request');
var options = {
  'method': 'POST',
  'url': 'https://web.it-decision.com/v1/api/send-whatsapp',
  'headers': {
    'Authorization': 'Basic api key',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "to": "38063xxxxxxx",
    "type": "template",
    "template": {
      "namespace": "xxxxx_xxxx_xxx_xxx_xxxxx",
      "language": {
        "policy": "deterministic",
        "code": "en_US"
      },
      "name": "media_2_english",
      "components": [
        {
          "type": "header",
          "parameters": [
            {
              "type": "image",
              "image": {
                "link": "url image.jpg"
              }
            }
          ]
        }
      ]
    }
  })

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});
```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "to": "38063xxxxxxx",
  "type": "template",
  "template": {
    "namespace": "xxxxx_xxxx_xxx_xxx_xxxxx",
    "language": {
      "policy": "deterministic",
      "code": "en_US"
    },
    "name": "media_2_english",
    "components": [
      {
        "type": "header",
        "parameters": [
          {
            "type": "image",
            "image": {
              "link": "url image.jpg"
            }
          }
        ]
      }
    ]
  }
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/send-whatsapp", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
```

{% endtab %}
{% endtabs %}


# RCS API

Coming Soon


# Verify API

#### **Two factor authentication (2FA) via SMS**

Verify API DecisionTelecom позволяет подтвердить номер мобильного телефона с помощью двухфакторной аутентификации. Создайте новый объект Verify через API, чтобы начать процесс проверки получателя. DecisionTelecom позаботится о создании токена и обеспечении доставки сообщения получателю.

Verify API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8 и значений в кодировке URL.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## Отправить верификацию&#x20;

{% tabs %}
{% tab title="POST REQUEST json string" %}

```
string https://web.it-decision.com/v1/api/two-factor-auth
```

{% endtab %}
{% endtabs %}

```json
{
    "phone":380776557788,
    "pin_length":4,
    "template_id":0,
    "country_iso":"en"
}
```

#### **Response:**

```json
{
    "id": 34234234,
    "phone": 380776557788,
    "href": "https://web.it-decision.com/api/get-pin?id=34234234",
    "status": "ACCEPTD"
}
```

#### Параметры:

**Id** <mark style="color:red;">int</mark> - уникальный случайный идентификатор, который создается на платформе DecisionTelecom. – Обязательный.

**phone** <mark style="color:red;">int</mark> - номер телефона, по которому вы хотите сделать запрос. – Обязательный.

**pin\_lenght** <mark style="color:red;">int</mark> - длина пин-кода, от 4 до 10 цифр. – Опционально, по умолчанию 4.

**templete\_id** <mark style="color:red;">int</mark> - по умолчанию 0 (текст сообщения шаблона: ваш проверочный код: \d{4,10}) — Обязательный.

**country\_iso** <mark style="color:red;">string</mark> - Опционально, по умолчанию «en».

## Проверка PIN-кода

{% tabs %}
{% tab title="GET REQUEST" %}

```
 https://web.it-decision.com/v1/api/get-pin?id=34234234
```

{% endtab %}
{% endtabs %}

#### Response:

```json
{
    "id": 34234234,
    "phone": 380776557788,
    "pin": 4323
}
```

Вам остается лишь сверить значения пин-кода, которое пользователь введет у вас при верификации и которое мы возвращаем вам в ответе. Если они совпадают значит верификация пройдена успешно.

## Примеры Verify

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

```
curl --location --request POST 'https://web.it-decision.com/v1/api/two-factor-auth' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data-raw '{"phone":380631211121,"pin_length":10,"template_id":0,"country_iso":"en"}'

```

{% endtab %}

{% tab title="Golang" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://web.it-decision.com/v1/api/two-factor-auth"
  method := "POST"

  payload := strings.NewReader(`{"phone":380631211121,"pin_length":10,"template_id":0,"country_iso":"en"}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

```

{% endtab %}

{% tab title="Java" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"phone\":380631211121,\"pin_length\":10,\"template_id\":0,\"country_iso\":\"en\"}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/two-factor-auth")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();

```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api key");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "phone": 380631211121,
  "pin_length": 10,
  "template_id": 0,
  "country_iso": "en"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://web.it-decision.com/v1/api/two-factor-auth", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

```

{% endtab %}

{% tab title="C#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/two-factor-auth");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""phone"":380631211121,""pin_length"":10,""template_id"":0,""country_iso"":""en""}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

```

{% endtab %}

{% tab title="C – libcUrl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/two-factor-auth");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"phone\":380631211121,\"pin_length\":10,\"template_id\":0,\"country_iso\":\"en\"}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);


```

{% endtab %}

{% tab title="NodJs" %}

```
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/two-factor-auth',
  'headers': {
    'Authorization': 'Basic api key',
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "phone": 380631211121,
  "pin_length": 10,
  "template_id": 0,
  "country_iso": "en"
});

req.write(postData);

req.end();

```

{% endtab %}

{% tab title="PHP" %}

```
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/two-factor-auth',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"phone":380631211121,"pin_length":10,"template_id":0,"country_iso":"en"}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;


```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "phone": 380631211121,
  "pin_length": 10,
  "template_id": 0,
  "country_iso": "en"
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/two-factor-auth", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

```

{% endtab %}

{% tab title="Ruby" %}

```
require "uri"
require "json"
require "net/http"

url = URI("https://web.it-decision.com/v1/api/two-factor-auth")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic api key"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "phone": 380631211121,
  "pin_length": 10,
  "template_id": 0,
  "country_iso": "en"
})

response = https.request(request)
puts response.read_body

```

{% endtab %}
{% endtabs %}


# Flash Call Verify API

Flash Call Verify API DecisionTelecom позволяет отправлять Flash вызовы для верификации в любую страну мира через API. Номер телефона, с которого будет осуществляться входящий звонок, будет содержать необходимый код для проверки, в последних 4-6 цифрах. Каждый вызов идентифицируется уникальным случайным идентификатором.

Flash Call Verify API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8 и значений в кодировке URL.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## Отправить flash call verification

Auth: Basic Auth (api key)

{% tabs %}
{% tab title="Method Post " %}

```
https://web.it-decision.com/v1/api/flash-call
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Params json:" %}

```json
{
   "phone":380631111111,
   "sender":"Decision",
   "text":1233,
   "validity_period":2
}
```

{% endtab %}
{% endtabs %}

**phone** <mark style="color:red;">int</mark> The telephone number that you want to do a network query on

**sender** <mark style="color:red;">string</mark>  The sender of the message. This can be a mobile phone number (including a country code) or an alphanumeric string. The maximum length of alphanumeric strings is 11 characters.

&#x20;**validity\_period** <mark style="color:red;">int</mark> SMS lifetime  min 2 minute max 4320

**Text** <mark style="color:red;">string</mark> Text consists only short code with 4-6 numbers

**Response:**\
Returns json string if the request was successful.

```json
{
   "id": 26381905,
   "phone": 380631111111,
   "status": "Accepted"
}
```

**Id** <mark style="color:red;">int</mark> - A unique random ID which is created on the DecisionTelecom platform.

**status** <mark style="color:red;">string</mark> – the status of the phone. Possible values: accepted, rejected, unknown, and failed

## Example code :

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

```
curl --location 'https//:web.it-decision.com/v1/api/flash-call' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data '{"phone":380631111111,"sender":"Decision","text":1233,"validity_period":2}'
```

{% endtab %}

{% tab title="GO" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https//:web.it-decision.com/v1/api/flash-call"
  method := "POST"

  payload := strings.NewReader(`{"phone":380631111111,"sender":"Decision","text":1233,"validity_period":2}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
```

{% endtab %}

{% tab title="C# " %}

```
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https//:web.it-decision.com/v1/api/flash-call");
request.Headers.Add("Authorization", "Basic api key");
var content = new StringContent("{\"phone\":380631111111,\"sender\":\"Decision\",\"text\":1233,\"validity_period\":2}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```

{% endtab %}

{% tab title="Java" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"phone\":380631111111,\"sender\":\"Decision\",\"text\":1233,\"validity_period\":2}");
Request request = new Request.Builder()
  .url("https//:web.it-decision.com/v1/api/flash-call")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();
```

{% endtab %}

{% tab title="C – libcurl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https//:web.it-decision.com/v1/api/flash-call");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"phone\":380631111111,\"sender\":\"Decision\",\"text\":1233,\"validity_period\":2}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
```

{% endtab %}

{% tab title="PHP" %}

```
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https//:web.it-decision.com/v1/api/flash-call',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"phone":380631111111,"sender":"Decision","text":1233,"validity_period":2}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("https")
payload = json.dumps({
  "phone": 380631111111,
  "sender": "Decision",
  "text": 1233,
  "validity_period": 2
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "//:web.it-decision.com/v1/api/flash-call", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
```

{% endtab %}
{% endtabs %}


# VIBER + SMS API

DecisionTelecom Viber + SMS API позволяет отправлять и получать деловые сообщения Viber в любую страну мира и из нее через API, и если Viber сообщение не было доставлено клиенту, то оно будет переслано и доставлено, как обычное смс сообщение. Каждое сообщение идентифицируется уникальным случайным идентификатором, поэтому пользователи всегда могут проверить статус сообщения, используя заданную конечную точку.

The Viber + SMS API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## Авторизация

## Базовая авторизация&#x20;

#### Пример:

```
$userHashKey = 'User Hash Key provided by your account manager';
$ch = curl_init('https://web.it-decision.com/v1/api/send-viber');
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$userHashKey");
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestParams)); // 
$requestParams - raquest array with correct data 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 
$result = curl_exec($ch); 
curl_close($ch);
```

## **Отправить Вайбер сообщение**

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

```
https://web.it-decision.com/v1/api/send-viber
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST" %}

```json
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,							
	"message_type":106, 									
	"text":"Message content", 								
	"text_sms":"SMS message content", // add this parameter: if, in the event of non-delivery via Viber, it is necessary to resend transactional message via SMS  
	"image":"https://yourdomain.com/images/image.jpg", 		
	"button_caption":"Join Us", 							
	"button_action":"https://yourdomain.com/join-us",   	
	"source_type":2, 										
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":40
}
```

{% endtab %}
{% endtabs %}

## Параметры

**source\_addr:**

<= 20 chars - от кого сообщение

**destination\_addr:**

<= 20 chars - кому сообщение

**message\_type (тип отправленного сообщения):**

106 только текст (удобно для транзакционных сообщений)

108 текст+картинка+кнопка (удобно для рекламных сообщений)

206 только текст (2Way)\*(удобно для рекламных сообщений)

208 текст+изображение+кнопка (двусторонняя)\* (удобно для рекламных сообщений)

**text:**

<= 1000 chars - текст Viber сообщения

**text\_sms:**

<= 70 chars for UCS-2 (16-bit) and <= 160 chars for Latin - альтернативный текст SMS, если сообщение Viber не доставлено (только для транзакционных сообщений)

**image (Правильный URL-адрес с изображением для рекламного сообщения с заголовком кнопки и действием кнопки):**

jpg or jpeg (тип mime — изображение/jpeg), максимальное разрешение 400x400 пикселей

png (тип mime — image/png), максимальное разрешение 400x400 пикселей

**button\_caption:**

<= 30 chars - надпись на кнопке

**button\_action:**

Правильный URL для перехода при нажатии кнопки

**source\_type (Процедура отправки сообщения):**

promotion message (сообщение может быть с текстом, изображением и кнопкой) - 1

transactional message (текстовое сообщение) – 2

**callback\_url:**

Правильный URL для обратного вызова статуса сообщения

**validity\_period:**

TTL (время жизни) позволяет отправителю ограничить время жизни сообщения. В случае, если сообщение не получило статус «доставлено» до истечения времени, сообщение не будет списано и не будет доставлено пользователю. В случае, если TTL не был указан (нет параметра «ttl»), Viber будет пытаться доставить сообщение в течение 1 дня.

promotion message - мин. TTL 40 секунд макс. TTL 21600 секунд (6 часов)

transactional message - мин. TTL 40 секунд макс. TTL 21600 секунд (6 часов)

transactional message + SMS - TTL всего 40 секунд

#### **Response:**

{% tabs %}
{% tab title=" JSON (POST)" %}

```json
{
    "message_id":429	
}
```

{% endtab %}
{% endtabs %}

#### Значение:

<mark style="color:red;">message\_id:</mark>

Идентификатор отправленного сообщения

#### **Получить сообщение от пользователя для двусторонних сообщений:**

Для двусторонних сообщений система DecisionTelecom Viber будет отправлять обратные вызовы с каждым сообщением пользователя. Содержимое данных отслеживания будет отправлено клиентом в соответствии с данными отслеживания в последнем сообщении, которое было получено на стороне клиента Viber.

Ответ подразумевает, что у пользователя API есть URL-адрес обратного вызова для этих сообщений.

#### **Response:**

{% tabs %}
{% tab title="JSON (POST)" %}

```json
{
    "message_token": 44444444444444,
    "phone_number": "972512222222",
    "time": 2121212121,
    "message": 
    {
        "text": "a message to the service",
        "tracking_data": "tracking_id:100035"
    }
}
```

{% endtab %}
{% endtabs %}

## Значения

**message\_token:**

токен сообщения ответа клиента

**phone\_number:**

номер телефона клиента

**time:**

время ответа клиента

**message:**

**text:**

текст ответного сообщения клиента

**tracking\_data:**

tracking\_id: Идентификатор сообщения, на которое отвечает клиент

## **Получить Вайбер сообщение**

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

```
https://web.it-decision.com/v1/api/receive-viber
```

{% endtab %}
{% endtabs %}

{% tabs %}
{% tab title="Request POST:" %}

```json
{
	"message_id":429	
}
```

{% endtab %}
{% endtabs %}

## Параметры

**message\_id:**

ID сообщения, статус которого вы хотите получить (за последние 5 дней)

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

```json
{
	"message_id":429, 			
	"status":1, 				
	"sms_message_id":36478, 	
	"sms_message_status":2		
}
```

{% endtab %}
{% endtabs %}

## Значения

**message\_id:**

ID сообщения, статус которого вы хотите получить (за последние 5 дней)

**status:**

Текущий статус сообщения Viber

**sms\_message\_id:**

Идентификатор SMS-сообщения (если доступно, только для транзакционных сообщений)

**sms\_message\_status:**

Статус SMS-сообщения (если доступно, только для транзакционных сообщений)

## **Статусы сообщений Вайбер**

| sent        | 0  |
| ----------- | -- |
| delivered   | 1  |
| error       | 2  |
| rejected    | 3  |
| undelivered | 4  |
| pending     | 5  |
| unknown     | 20 |

## **Статусы SMS сообщений**

| delivered     | 2 |
| ------------- | - |
| undeliverable | 5 |
| expired       | 3 |

## Ошибки

| Name    | Слишком много запросов |
| ------- | ---------------------- |
| message | Rate limit превышен    |
| code    | 0                      |
| status  | 429                    |

| Name    | Invalid Parameter: \[param\_name]             |
| ------- | --------------------------------------------- |
| message | Пустой параметр или ошибка проверки параметра |
| code    | 1                                             |
| status  | 400                                           |

| Name    | Внутренняя Ошибка Сервера                                                               |
| ------- | --------------------------------------------------------------------------------------- |
| message | Сервер столкнулся с непредвиденной ситуацией, из-за которой он не смог выполнить запрос |
| code    | 2                                                                                       |
| status  | 500                                                                                     |

| Name    | Требуется пополнение баланса |
| ------- | ---------------------------- |
| message | Баланс пользователя пуст     |
| code    | 3                            |
| status  | 402                          |

## Пример Viber + SMS

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

```
curl --location --request POST 'https://web.it-decision.com/v1/api/receive-viber' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data-raw '{"source_addr": "Custom Company","destination_addr": 380636111112,"message_type":106,"text":"Message content","text_sms":"SMS message content","image":"https://yourdomain.com/images/image.jpg","button_caption":"Join Us", "button_action":"https://yourdomain.com/join-us","source_type":2,"callback_url":"https://yourdomain.com/viber-callback","validity_period":3600
}'

```

{% endtab %}

{% tab title="C#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/receive-viber");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""source_addr"": ""Custom Company"",""destination_addr"": 380636111112,""message_type"":106,""text"":""Message content"",""text_sms"":""SMS message content"",""image"":""https://yourdomain.com/images/image.jpg"",""button_caption"":""Join Us"", ""button_action"":""https://yourdomain.com/join-us"",""source_type"":2,""callback_url"":""https://yourdomain.com/viber-callback"",""validity_period"":3600
" + "\n" +
@"}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

```

{% endtab %}

{% tab title=" Java" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"source_addr\": \"Custom Company\",\"destination_addr\": 380636111112,\"message_type\":106,\"text\":\"Message content\",\"text_sms\":\"SMS message content\",\"image\":\"https://yourdomain.com/images/image.jpg\",\"button_caption\":\"Join Us\", \"button_action\":\"https://yourdomain.com/join-us\",\"source_type\":2,\"callback_url\":\"https://yourdomain.com/viber-callback\",\"validity_period\":3600\r\n}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/receive-viber")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();

```

{% endtab %}

{% tab title="JavaScript" %}

```
var myHeaders = new Headers();
myHeaders.append("Authorization", "Basic api key");
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "source_addr": "Custom Company",
  "destination_addr": 380636111112,
  "message_type": 106,
  "text": "Message content",
  "text_sms": "SMS message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 2,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://web.it-decision.com/v1/api/receive-viber", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

```

{% endtab %}

{% tab title="C – libCurl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/receive-viber");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"source_addr\": \"Custom Company\",\"destination_addr\": 380636111112,\"message_type\":106,\"text\":\"Message content\",\"text_sms\":\"SMS message content\",\"image\":\"https://yourdomain.com/images/image.jpg\",\"button_caption\":\"Join Us\", \"button_action\":\"https://yourdomain.com/join-us\",\"source_type\":2,\"callback_url\":\"https://yourdomain.com/viber-callback\",\"validity_period\":3600\r\n}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);

```

{% endtab %}

{% tab title="NodeJs" %}

```
var https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/receive-viber',
  'headers': {
    'Authorization': 'Basic api key',
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "source_addr": "Custom Company",
  "destination_addr": 380636111112,
  "message_type": 106,
  "text": "Message content",
  "text_sms": "SMS message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 2,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
});

req.write(postData);

req.end();



```

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://web.it-decision.com/v1/api/receive-viber',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{"source_addr": "Custom Company","destination_addr": 380636111112,"message_type":106,"text":"Message content","text_sms":"SMS message content","image":"https://yourdomain.com/images/image.jpg","button_caption":"Join Us", "button_action":"https://yourdomain.com/join-us","source_type":2,"callback_url":"https://yourdomain.com/viber-callback","validity_period":3600
}',
  CURLOPT_HTTPHEADER => array(
    'Authorization: Basic api key',
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

```

{% endtab %}

{% tab title=" Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "source_addr": "Custom Company",
  "destination_addr": 380636111112,
  "message_type": 106,
  "text": "Message content",
  "text_sms": "SMS message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 2,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/receive-viber", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

```

{% endtab %}

{% tab title=" Ruby" %}

```
require "uri"
require "json"
require "net/http"

url = URI("https://web.it-decision.com/v1/api/receive-viber")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic api key"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "source_addr": "Custom Company",
  "destination_addr": 380636111112,
  "message_type": 106,
  "text": "Message content",
  "text_sms": "SMS message content",
  "image": "https://yourdomain.com/images/image.jpg",
  "button_caption": "Join Us",
  "button_action": "https://yourdomain.com/join-us",
  "source_type": 2,
  "callback_url": "https://yourdomain.com/viber-callback",
  "validity_period": 3600
})

response = https.request(request)
puts response.read_body


```

{% endtab %}
{% endtabs %}


# HLR API

DecisionTelecom позволяет отправлять сетевые запросы на любой мобильный номер по всему миру. Это позволяет вам просматривать, какой номер мобильного телефона принадлежит какому оператору в режиме реального времени и видеть, активен ли номер.

HLR API использует HTTPS с ключом доступа, который используется в качестве авторизации API. Полезные данные запросов и ответов форматируются как JSON с использованием кодировки UTF-8 и значений в кодировке URL.

**API Авторизация** - Базовый ключ доступа Base64.

Чтобы получить ключ API, пожалуйста, свяжитесь с вашим менеджером по работе с клиентами.

## Отправить HLR

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

```
 https://web.it-decision.com/v1/api/hlr 
```

{% endtab %}
{% endtabs %}

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

```json
{
    "phones":[380636151111,380631111112]
}
```

{% endtab %}
{% endtabs %}

#### Параметры:&#x20;

**Phones**: <mark style="color:red;">array</mark> - Список номеров телефонов, по которым вы хотите выполнить сетевой запрос. – Обязательный.

#### **Response:**

Возвращает JSON string если запрос был успешным.

```json
[
 {
          "id": 2345234,
          "phone": 380631111111,
          "href": "https://web.it-decision.com/v1/api/hlr-status?id=380631111111",
          "status": "Accepted"
 },
 {
          "id": 2345235,
          "phone": 380631111112,
          "href": "https://web.it-decision.com/v1/api/hlr-status?id=380631111112",
          "status": "Accepted"
 }
]  
```

#### **Параметры:**

**Id** <mark style="color:orange;">int</mark> - Уникальный случайный идентификатор, созданный на платформе DecisionTelecom. Обязательный.

**status** <mark style="color:red;">string</mark> – состояние телефона.

**Возможные значения:** accepted, sent, absent, active, unknown, and failed.

## **Статус HLR**

#### **Пример запроса:**

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

```
https://web.it-decision.com/v1/api/hlr-status?id=2345234  
```

{% endtab %}
{% endtabs %}

#### **Пример ответа JSON:**

```json
{
    "id": 2345234,
    "phone": 38063122121,
    "mcc": "255",
    "mnc": "06",
    "network": "Lifecell",
    "ported": false,
    "status": 0,
    "error": 0,
    "type": "mobile",
    "present": "yes",
    "status_message": "Success"
}
```

## Значения

**ID**: a unique random ID which is created on the DecisionTelecom

**Phone**: int The telephone number.

**MCC**: the Mobile Country Code of the current carrier.

**MNC**: the Mobile Network Code of the current carrier.

**Network**: the name of the current carrier.

**Ported**: boolean, true / false / null.

**Type**: text label: mobile / fixed.

**Present**: yes/ no / na (not available) – whether the subscriber is present in the network.

**Status\_message**: text, the description of the above ‘status’: Success / Invalid Number / Not allowed country.

**Status**: number, a code for the outcome of the query:

0 = success

1 = invalid Number

2 = not allowed country

**HTTP Unsuccessful Response format**, If the status is not 0 (Success), only the number, status and status\_message will be returned.

**Example Response**: { "status\_message" : "Invalid Number", "status" : 1 }

**Errors**:

0-No error.

1-Unknown subscriber: The number is not allocated.

2-The owning network cannot be reached.

3-The network cannot reach the number.

4-The location of the number is not known to the network.

5-The number, as published in HLR, in not known to the MSC.

6-The number is absent for SM.

7-Unknown equipment.

8-Roaming not allowed.

9-Illegal subscriber.

10-Bearer service not provisioned.

11-Tele-service not provisioned.

12-Illegal equipment.

13-Call barred.

21-Facility not supported.

27-Phone switched off.

28-Incompatible terminal.

31-The subscriber is busy.

32-The delivery of the SM has failed.

33-A congestion (a full waiting list) occurred.

34-System failure.

35-Missing data.

36-Data error.

191-Unsupported network for which offers portability status.&#x20;

192-Unsupported network for which offers the Origin Network.&#x20;

193-Landline Fixed network (not covered).

## Примеры **HLR**

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

```
curl --location --request POST 'https://web.it-decision.com/v1/api/hlr' \
--header 'Authorization: Basic api key' \
--header 'Content-Type: application/json' \
--data-raw '{"phones":[380636151111,380631111112]}'
```

{% endtab %}

{% tab title="PHP" %}
\<?php

&#x20;

$curl = curl\_init();

&#x20;

curl\_setopt\_array($curl, array(

&#x20; CURLOPT\_URL => '<https://web.it-decision.com/v1/api/hlr>',

&#x20; CURLOPT\_RETURNTRANSFER => true,

&#x20; CURLOPT\_ENCODING => '',

&#x20; CURLOPT\_MAXREDIRS => 10,

&#x20; CURLOPT\_TIMEOUT => 0,

&#x20; CURLOPT\_FOLLOWLOCATION => true,

&#x20; CURLOPT\_HTTP\_VERSION => CURL\_HTTP\_VERSION\_1\_1,

&#x20; CURLOPT\_CUSTOMREQUEST => 'POST',

&#x20; CURLOPT\_POSTFIELDS =>'{"phones":\[380636151111,380631111112]}',

&#x20; CURLOPT\_HTTPHEADER => array(

&#x20;   'Authorization: Basic api key',

&#x20;   'Content-Type: application/json'

&#x20; ),

));

&#x20;

$response = curl\_exec($curl);

&#x20;

curl\_close($curl);

echo $response;
{% endtab %}

{% tab title="GOLANG" %}

```
package main

import (
  "fmt"
  "strings"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://web.it-decision.com/v1/api/hlr"
  method := "POST"

  payload := strings.NewReader(`{"phones":[380636151111,380631111112]}`)

  client := &http.Client {
  }
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }
  req.Header.Add("Authorization", "Basic api key ")
  req.Header.Add("Content-Type", "application/json")

  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}

```

{% endtab %}

{% tab title="JAVA" %}

```
OkHttpClient client = new OkHttpClient().newBuilder()
  .build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"phones\":[380636151111,380631111112]}");
Request request = new Request.Builder()
  .url("https://web.it-decision.com/v1/api/hlr")
  .method("POST", body)
  .addHeader("Authorization", "Basic api key")
  .addHeader("Content-Type", "application/json")
  .build();
Response response = client.newCall(request).execute();
```

{% endtab %}

{% tab title="C#" %}

```
var client = new RestClient("https://web.it-decision.com/v1/api/hlr");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic api key");
request.AddHeader("Content-Type", "application/json");
var body = @"{""phones"":[380636151111,380631111112]}";
request.AddParameter("application/json", body,  ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
```

{% endtab %}

{% tab title="C - libcurl" %}

```
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
  curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
  curl_easy_setopt(curl, CURLOPT_URL, "https://web.it-decision.com/v1/api/hlr");
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_DEFAULT_PROTOCOL, "https");
  struct curl_slist *headers = NULL;
  headers = curl_slist_append(headers, "Authorization: Basic api key");
  headers = curl_slist_append(headers, "Content-Type: application/json");
  curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  const char *data = "{\"phones\":[380636151111,380631111112]}";
  curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
  res = curl_easy_perform(curl);
}
curl_easy_cleanup(curl);
```

{% endtab %}

{% tab title="NodeJS" %}

```
ar https = require('follow-redirects').https;
var fs = require('fs');

var options = {
  'method': 'POST',
  'hostname': 'web.it-decision.com',
  'path': '/v1/api/hlr',
  'headers': {
    'Authorization': 'Basic api key',
    'Content-Type': 'application/json'
  },
  'maxRedirects': 20
};

var req = https.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function (chunk) {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });

  res.on("error", function (error) {
    console.error(error);
  });
});

var postData = JSON.stringify({
  "phones": [
    380636151111,
    380631111112
  ]
});

req.write(postData);

req.end();

```

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

conn = http.client.HTTPSConnection("web.it-decision.com")
payload = json.dumps({
  "phones": [
    380636151111,
    380631111112
  ]
})
headers = {
  'Authorization': 'Basic api key',
  'Content-Type': 'application/json'
}
conn.request("POST", "/v1/api/hlr", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))

```

{% endtab %}

{% tab title="Ruby" %}

```
require "uri"
require "json"
require "net/http"

url = URI("https://web.it-decision.com/v1/api/hlr")

https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = "Basic api key"
request["Content-Type"] = "application/json"
request.body = JSON.dump({
  "phones": [
    380636151111,
    380631111112
  ]
})

response = https.request(request)
puts response.read_body

```

{% endtab %}
{% endtabs %}


# Voice API

VoIP-телефония для эффективной коммуникации. Воспользуйтесь услугами VoIP от DecisionTelecom и предлагайте своим клиентам высококачественные звонки по IP-протоколу, независимо от их местонахождения.

#### **Звонки по всему миру**

Используйте проверенные местные номера, чтобы звонить в любую точку мира и стать еще ближе к своим иностранным клиентам.

#### **Голосовые функции**

VoIP-телефония предлагает вам и вашим клиентам доступ к бесперебойному соединению и гораздо лучшую альтернативу звонкам в роуминге.

#### **Прозрачная платежная система**

Платите только за фактическое время разговора. Наша система тарифицирует звонки посекундно, а значит, вам не придется переплачивать.

#### **SIP-транк**

Как мобильный виртуальный оператор MVNO, мы предоставляем нашим клиентам шлюз VoIP для надежных звонков по всему миру.

Мы предоставляем подключение по протоколу SIP.

Протокол установления сеанса (SIP) — это процесс передачи голосовых вызовов по транку SIP или каналу SIP. SIP-вызовы обычно используют VoIP для передачи трафика аналоговых вызовов через интернет-соединение.

Мы можем предоставить столько SIP-транков, сколько вам нужно, их может быть два или более, просто сообщите нам, что вам нужно.

#### **Конфигурация соединения**

Для создания соединения нам необходимо знать ваш IP-адрес.

IP-адрес DecisionTelecom: 178.22.10.79

После создания SIP-транков наша служба голосовой поддержки предоставит вам информацию о количестве SIP-транков, соответствующих префиксах и IP-адресах.

#### **Вопросы?**

Мы всегда рады помочь с кодом или другими вопросами, которые могут у вас возникнуть! Ознакомьтесь с нашим API, справочником по SDK или свяжитесь с нашей службой поддержки: <https://www.decisiontele.com/ru/contact-expert.html>.


