# ­­­­­­­­DecisionTelecom API Overview

#### DecisionTelecom API Overview

**­­­­­­­­­**Explore our full API reference documentation and easily integrate SMS, Viber, WhatsApp, chat and voice capabilities into your website or application using DecisionTelecom APIs.

HTTPS is chosen as the transport layer of the DecisionTelecom API for the described protocol.

The access key is used as the basis for the authorization of the API. Request and response payloads are formatted as JSON (we also provide as alternative GET requests), using UTF-8 encoding and URL-encoded values.

**SDK**

The official DecisionTelecom API SDK libraries are available in multiple languages: <https://github.com/IT-DecisionTelecom>

**API Endpoint**

To use the DecisionTelecom APIs, you must first register for free on our website [www.decisiontele.com](http://www.decisiontele.com/)


# SMS API

DecisionTelecom SMS API allows you to send SMS messages to any country in the world via API. Each message is identified by a unique random ID, so users can always check the status of a message using given endpoint.

The SMS API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding and URL-encoded values.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## Send SMS

{% 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"
        }
    ]
}
```

## **SMS Status**

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

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

{% endtab %}
{% endtabs %}

#### **Response:**

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

#### **Parameters:**

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

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

**Text**: <mark style="color:red;">string</mark> – sms message text

**validity\_period**: <mark style="color:red;">int</mark> - SMS lifetime in minutes (min 1 minute, max 4320)

**sender:** <mark style="color:red;">string</mark> - The sender of the message, the maximum length is 11 characters

**part\_count**: <mark style="color:red;">int</mark> - amount of messages

**concat\_part**: <mark style="color:red;">int</mark> - Number of pieces of the message

**status**: <mark style="color:red;">string</mark> - possible sms status<br>

**Possible values of status:**

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

DELIVERED (DELIVRD) - The message has been successfully delivered to the end user.

EXPIRED (EXPIRED) - The message was not delivered because the delivery time expired.

DELETED (DELETED) - The message has been deleted and cannot be delivered.

UNDELIVERABLE (UNDELIV) - The message cannot be delivered due to a permanent error (e.g., incorrect number or other issues with the recipient).

ACCEPTED (ACCEPTD) - The message has been accepted by the operator's system but has not yet been delivered.

UNKNOWN (UNKNOWN) - The status of the message is unknown, possibly due to a temporary issue or an unidentified cause.

REJECTED (REJECTD) - The message was rejected by the system and will not be delivered (possibly due to operator policies or other technical reasons).

ENROUTE (ENROUTE) - The message has been forwarded to the network but has not yet been delivered to the end user.

## **Send SMS examples**

{% 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 %}

## SMS Delivery Report

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;

## Bulk SMS Messaging

HTTP Authorization - Basic access key Base64

## Send messages

{% 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

## Bulk sms messages examples

{% 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);

```

{% 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 %}

## Check balance

#### 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 %}

## Examples Check balance

{% 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)

Used to send and receive large volumes of SMS traffic. The SMPP protocol is especially popular among SMS providers and telecom operators.

Please contact one of our consultants to get the data for connecting via the SMPP protocol.

## **SMPP Server**

Below you can find the data for connection to the DecisionTelecom SMPP server:

Host name port TLS port

web.it-decision.com 2888 2999

## **User name and password**

Your account manager in DecisionTelecom will provide you with a username (system\_id) and password. If you haven't received them yet, or if you still need to make a request, simply send us an email at <support@it-decision.com>; We will be happy to help you.

## **Bindings and throughput**

Whenever an SMPP account is set up for you, you will get the required number of connections (binds) and throughput. In most cases these values will be 1 bind and 50 messages per second.

It is interesting to note that these values can be higher at the request of the client.

## **Security**

If you are connecting to any server via a TLS connection, be sure to select TCP port 2999. Also be aware that servers only accept methods SSLv1, SSLv2 and SSLv3.

## **Bind PDU**

The bind\_receiver, bind\_transceiver, or bind\_transmitter SMPP PDU request has a fixed set of fields. Most of the fields don't matter to us; in fact, we only read the system\_id, password, and interface\_version fields, and ignore the rest.

## **Interface\_version**

The DecisionTelecom SMPP server supports SMPP protocol version 3.4. Be aware that if you configure your SMPP client for version 3.3, you will miss out on some features, primarily the TLV information in the Deliver\_sm PDUs.

## **Submit\_sm PDU**

You can use the submit\_sm PDU to send us your messages. The submit\_sm PDU request also has a couple of fields that are not used by our platform and can be safely ignored.

## **Data\_coding**

The values of the data\_coding field are not explicitly declared in the SMPP specification, so each SMPP server is required to give its own definition. Below is a list of data encodings that we accept as input.

| 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 allows you to send and receive Viber business messages to and from any country in the world via API. Each message is identified by a unique random ID, so users can always check the status of a message using given endpoint.

The Viber API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## **Auth**

## Basic Auth

#### **Example**:

```
$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);
```

## **Send Viber message**

{% 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", 		
	"image_action":"https://yourdomain.com/join-us", // optional
	"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 promotional image messages (Animated GIF):
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,	
	"message_type":107, 								
	"image":"https://yourdomain.com/images/image.gif",
	"image_format":"gif", // for animate gif
	"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":1701, // 1701 for primary device, 1702 for all devices
	"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, // carousel is promotional message
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":6800,
	"text":"Message content",
	"carousel": {
	    "items": [
	      {
	        "title": "50% Off on All Shoes!50%",
	        "imageUrl": "https://example.com/images/sale.jpg",
	        // Expected formats - PNG, JPEG, JPG. Recommended size: 215x185px
	        "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",
	        // Expected formats - PNG, JPEG, JPG. Recommended size: 215x185px
	        "primaryButton": {
	          "label": "Explore",
	          "actionUrl": "https://example.com/summer"
	        },
	        "secondaryButton": {
	          "label": "Learn More",
	          "actionUrl": "https://example.com/summer-info"
	        }
	      }
	    ]
	  }
}

Example for list messages:
{
	"source_addr": "Custom Company",
	"destination_addr": 8882222200,
	"message_type":801,
	"source_type":2, // list is trsnsactional message
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":1600,
	"text":"Survey title",
	"tracking_data": "tracking data for
survey", // tracking_data is mandatory for list message
  "survey": {
    "list_message_ui_type": 1,
    "options": [ // Number of options can be from 2 to 5.
      "option1 text",
      "option2 text",
      "option3 text",
      "option4 text",
      "option5 text"
    ]
  }
}
```

{% endtab %}
{% endtabs %}

### **Parameters**

**source\_addr:**

from 3 to 20 characters - from whom the message

**destination\_addr:**

from 11 to 20 digits - to whom the message

**message\_type (Type of message sent):**

225 - only text (for all devices)

7 - image (for primary device)

107 - image (for all devices)

8 - text+image+button (for primary device)

108 - text+image+button (for all devices)

9 - text+ button (for primary device)

109 - text+button (for all devices)

222 - send file (for all devices) , supported formats: .doc, .docx, .rtf, .dot, .dotx, .odt ,odf, .fodt, .txt, .info, .pdf, .xps, .pdax, .eps, xls, .xlsx, .ods, .fods, .csv, .xlsm, .xltx

1701 - template transactional text (for primary device) - Due to the release of a new [API template](/viber-templates-api-beta) on Viber, old transactional type 301 will soon be deprecated

1702 - template transactional text (for all devices) - Due to the release of a new [API template](/viber-templates-api-beta) on Viber, old transactional type 304 will soon be deprecated

801 - list message (for all devices)&#x20;

901 - carousel message (for all devices)

**text:**

up to 1000 characters - text of Viber message

**image (Correct URL with image for promotional message with button caption and button action):**

jpg or jpeg (mime type is image/jpeg), maximum resolution 800x800 pixels

png (mime type is image/png), maximum resolution 800x800 pixels

gif (mime type is image/gif), maximum resolution 800x800 pixels

**image\_action (optional):**

Correct URL for transition when you press the image. Specifies a separate URL for image clicks. If omitted, the click action will fall back to the URL specified in the standard **button\_action** parameter.

**image\_format (optional for Animated GIF):**

gif — Enables animation for .gif files (required for animated view).

img — Standard static image processing (default behavior if the parameter is omitted).

**button\_caption:**

from 1 to 30 characters - button caption

**button\_action:**

Correct URL for transition when you press the button

**source\_type (Message sending procedure):**

promotion message (the message can be with text, picture, button) - 1

transactional message (template text message) – 2

**callback\_url:**

Correct URL for message status callback

**validity\_period:**

TTL (Time to live) allows the sender to limit the lifetime of a message. In case the message did not get the status "delivered" before the time ended, the message will not be charged and will not be delivered to the user. In case no TTL was provided (no "ttl" parameter) Viber will try to deliver the message for up to 1 day.

promotion message - min TTL 60 seconds max TTL 43200 seconds (12 hours)

transactional message - min TTL 60 seconds max TTL 43200 seconds (12 hours)

**file\_url:**

Only for 222 message type сorrect URL for document.\
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\
The file name must contain an extension and must not exceed 25 characters.\
File size must be up to 200 MB.

**carousel:**&#x20;

message type enables businesses to send a single message featuring text and multiple\
customizable sections (items), each showcasing different products or services along with\
dedicated media and a call-to-action.\
The message type allows presenting from 2 to 5 individual items. Each carousel item includes an\
image, a brief description, and offers up to 2 customizable buttons. All items in the carousel can\
have different sets of buttons.

**items:** from 2 to 5 carousel items.

* title (Mandatory) - Item title text. From 2 to 38 UTF-8 characters.
* imageUrl (Mandatory) - Expected formats - PNG, JPEG, jpg. Recommended size: 215x185
* primaryButton (Mandatory) - Holds a set of primary button parameters.
* secondaryButton (Optional) - Holds a set of secondary button parameters.
* label (Mandatory) - Button parameter. The text that will appear on the action button. Up to 10 UTF-8 characters when inside the primaryButton. Up to 12 UTF-8 characters when inside the secondaryButton.
* actionUrl (Mandatory) - Button parameter. The URL users are directed to or the action performed when pressing the action button\or tap on the image.

**survey:**&#x20;

List messages provide the opportunity to present users with a question and 2-5 answers\
from which they will be able to select one. Once a user selects an option, it will be\
highlighted as selected. The corresponding option text will be sent from the user to the\
business chat, triggering a user’s reply callback to the message URL, provided to the manager and set in your account settings.

After selection, the user will be able to change his selection.\
Upon changing the selection, an additional message will be sent on the user behalf in the\
chat and an additional reply callback will be sent to the message URL, provided to the manager and set in your account settings.

To utilize this message type, please ensure **that your business account has a**\
**message URL value configured**.

**list\_message\_ui\_type**: (Optional) - Defines the visual style of the options:\
1 - Radio Buttons (Legacy): The classic list selection style.\
2 - Buttons (New): A modern horizontal button layout\
Fallback to 1, if not provided.

**options:** from 2 to 5 list items.

* text (Mandatory) - Up to 85 UTF-8 characters.
* tracking\_data (Mandatory) - Mandatory for List message type. Tracking information for the sent message.
* options (Mandatory) - Number of options can be from 2 to 5.
* option text (Mandatory) - Up to 50 UTF-8 characters per option.

### GIF Support

*This feature is supported on devices running Viber version 28.1 and above.*\
Messages with images now support animated GIF format. By default,\
all sent images are processed as static. To display an animated GIF, you must explicitly pass the\
**image\_format** parameter in the request payload.

**Paramete**r: "**image\_format**" (optional)\
**Possible values**:\
gif — Enables animation for .gif files (required for animated view).\
img — Standard static image processing (default behavior if the parameter is\
omitted).

### Response:

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

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

{% endtab %}
{% endtabs %}

### **Values**:

**message\_id:**

Sent message ID

### **User’s reply callback for list message**:

Text response indicating user’s selection will be sent to the **URL provided to the manager and set in your account settings** along with tracking information provided in the request:

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

```json
{
    "message_token":5420791495801572569,
    "phone_number":"+972611200716", 
    "time":"1584475182",
    "service_id":3001, 
    "message": {
        "text":"Yes, very satisfied",
        "tracking_data": "tracking data for survey"
    }
}
```

{% endtab %}
{% endtabs %}

## Send verification messages (**OTP)**

### Logic

A templated message is a predefined message stored on Viber side which allows the\
sender to define specific values upon sending the message. Viber\`s verification messages\
are new message types designed for sending one time passwords (OTP) using\
pre-approved and pre-designed templates.

### Availability

Templates described in the [Predefined OTP Templates section](#predefined-otp-templates) are available for all services by default.\
In contrast to our regex template logic, there is no need to submit a template for each\
and every service separately, they are already stored on our side.

### Copy

A templated message has a predefined copy which includes [predefined variables](#predefined-otp-templates) that\
can be defined to hold a requested value by the sender.\
Variables are specific and defined for each template and will be validated according to\
specific limitations of each variable.

Example of templated message structure:\
Your code is **{{pin}}**.\
Please don't share your code with ANYONE. We'll never call or message you and ask for it.

In this case, the sender can define the pin value when sending the message. For\
example, if the sender will define the pin as 123456, the message that will be shown to\
the user will be:\
Your code is **123456**.\
Please don't share your code with ANYONE. We'll never call or message you and ask for it.

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

```json
Example for verification messages (OTP):
{
	"source_addr": "Custom Company", 						
	"destination_addr": 8882222200,							
	"message_type":701, // 701 - OTP to primary only; 702 - to all of the user devices									
	"source_type":2,    // OTP is trasactional message										
	"callback_url":"https://yourdomain.com/viber-callback",
	"validity_period":180,
	"template_id":"0aac888f-2ee2-4112-9659-1755a951966a", // see more in Predefined OTP Templates section
	"template_params":{ // see more about params in Predefined OTP Templates section
		"pin":"5234567"
		/*"code_reason":"subscribed to the newsletter"*/
		/*"business_platform_name": "Custom Company"*/
		/*"business_platform_action_name": "Custom Company"*/
		/*"pin_type":"custom pin type"*/
		/*"code_validity_time":15*/
	},	
  "template_lang": "en" // See more about locales in Localization section
}
```

{% endtab %}
{% endtabs %}

### Additional Parameters for OTP

**message\_type:**\
Mandatory.\
**701** - template message sent to primary only\
**702** - template message sent to all of the user devices

**template\_id:** \
Mandatory. [Predefined code](#predefined-otp-templates) of a template copy to be sent.

**template\_params:**\
Mandatory. A range of variables which are specific per template. For the\
templates and possible values description. Each template holds a different\
set of parameters which will be validated upon request.

**template\_lang:** Optional - if not specified, the default value&#x20;will be the device language. In case the device language is not supported,&#x20;the copy will be presented in English. [Locales list](#localization)

### Predefined OTP Templates

<table data-full-width="false"><thead><tr><th width="277.5999755859375">1.Basic OTP</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>0aac888f-2ee2-4112-9659-1755a951966a</td></tr><tr><td>English Copy</td><td>Your code is <strong>{{pin}}</strong>.<br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT</td></tr></tbody></table>

<table data-full-width="false"><thead><tr><th width="277.5999755859375">2.Basic OTP valid for 5 minutes</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>c2cdc028-a48b-4187-bbaf-3aaa137b6e23</td></tr><tr><td>English Copy</td><td>Your code is <strong>{{pin}}</strong>. It's valid for 5 minutes.<br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT</td></tr></tbody></table>

<table data-full-width="false"><thead><tr><th width="277.5999755859375">3.OTP with business/platform name</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>c33cccaf-735f-4d62-8383-a76bf4999e2d</td></tr><tr><td>English Copy</td><td><p><strong>{{business_platform_name}}</strong>: Your code is <strong>{{pin}}</strong>. </p><p><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</p></td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{business_platform_name}} - TEXT</td></tr></tbody></table>

<table data-full-width="false"><thead><tr><th width="277.5999755859375">4.Basic OTP with code validity time</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>bed0942f-e07e-4879-834b-29cc4cf3ec35</td></tr><tr><td>English Copy</td><td>Your code is <strong>{{pin}}</strong>. It's valid for <strong>{{code_validity_time}}</strong> minutes. <br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{code_validity_time}} - NUMBER</td></tr></tbody></table>

<table data-full-width="false"><thead><tr><th width="277.5999755859375">5.OTP with code type &#x26; validity time</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>60d67b38-b9fb-444a-80e6-754447e010c6</td></tr><tr><td>English Copy</td><td>Your <strong>{{pin_type}}</strong> code is <strong>{{pin}}</strong>. It's valid for <strong>{{code_validity_time}}</strong> minutes. <br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{pin_type}} - TEXT <br>{{code_validity_time}} - NUMBER</td></tr></tbody></table>

<table data-full-width="false"><thead><tr><th width="277.5999755859375">6.OTP with business/platform  name &#x26;  validity time</th><th></th></tr></thead><tbody><tr><td>Template ID</td><td>6c929cef-29b4-4349-bc9d-2a07bdbb6e43</td></tr><tr><td>English Copy</td><td>Your <strong>{{business_platform_name}}</strong> code is <strong>{{pin}}</strong>. It's valid for <strong>{{code_validity_time}}</strong> hours. <br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{business_platform_name}} - TEXT <br>{{code_validity_time}} - NUMBER</td></tr></tbody></table>

<table><thead><tr><th width="277.5999755859375">7.OTP with type of code type</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>82ba31a3-db42-4e87-82e8-33fa92b9e5ed</td></tr><tr><td>English Copy</td><td>Your <strong>{{pin_type}}</strong> code is <strong>{{pin}}</strong>.<br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT<br>{{pin_type}} - TEXT</td></tr></tbody></table>

<table><thead><tr><th width="277.5999755859375">8.OTP with details on OTP action/platform</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>210ee8a9-1ed5-43cd-96e4-65bba311ab40</td></tr><tr><td>English Copy</td><td>Your one-time password for <strong>{{business_platform_action_name}}</strong> is <strong>{{pin}}</strong>.<br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{business_platform_action_name}} - TEXT</td></tr></tbody></table>

<table><thead><tr><th width="277.5999755859375">9.OTP with business/platform name &#x26; code reason</th><th width="468"></th></tr></thead><tbody><tr><td>Template ID</td><td>be56d97b-2a33-4c89-ac5f-f555a2c827d9</td></tr><tr><td>English Copy</td><td><strong>{{business_platform_name}}</strong>: Your code is <strong>{{pin}}</strong>. You got this code because <strong>{{code_reason}}</strong>. <br><strong>Please don't share your code with ANYONE</strong>. We'll never call or message you and ask for it.</td></tr><tr><td>Parameters and<br>Validations</td><td>{{pin}} - TEXT <br>{{business_platform_name}} - TEXT <br>{{code_reason}} - TEXT</td></tr></tbody></table>

### Localization

Localization templang parameter will be according to ISO 639-1 encoding, represented by 2\
letter code as follows:

| Language                   | template\_lang (ISO 639-1) |
| -------------------------- | -------------------------- |
| English                    | en                         |
| Arabic                     | ar                         |
| Bulgarian                  | bg                         |
| Croatian                   | hr                         |
| Czech                      | cs                         |
| Danish                     | da                         |
| German                     | de                         |
| Greek                      | el                         |
| Spanish                    | es                         |
| Finnish                    | fi                         |
| French                     | fr                         |
| Hebrew                     | he                         |
| Burmese                    | my                         |
| Hungarian                  | hu                         |
| Indonesian                 | id                         |
| Italian                    | it                         |
| Japanese                   | ja                         |
| Norwegian                  | nb                         |
| Dutch                      | nl                         |
| Polish                     | pl                         |
| Portuguese&#xD; (Portugal) | pt                         |
| Portuguese (Brazil)        | br                         |
| Romanian                   | ro                         |
| Russian                    | ru                         |
| Slovak                     | sk                         |
| Serbian                    | sr                         |
| Swedish                    | sv                         |
| Thai                       | th                         |
| Turkish                    | tr                         |
| Ukrainian                  | uk                         |
| Vietnamese                 | vi                         |
| Persian                    | fa                         |
| Belarusian                 | be                         |

## **Receive Viber message**

{% 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 %}

### Parameters

**message\_id:**

The ID of the message whose status you want to get (for the last 30 days)

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

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

{% endtab %}
{% endtabs %}

### Values

**message\_id:**

The ID of the message whose status you want to get (for the last 30 days)

**status:**

Current Viber message status

## **Receive bulk Viber messages**

The number of verified messages is no more than 200 in one request.

{% 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 %}

### Parameters

**message\_id:**

The ID of the message whose status you want to get (for the last 30 days)

{% 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 %}

### Values

**message\_id:**

The ID of the message whose status you want to get (for the last 30 days)

**status:**

Current Viber message status

## **Callback**

The callback will be returned to the URL specified when sending the message in the parameter 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 %}

### Values

**message\_id:**

The ID of the message

**status:**

Current Viber message status

**reject\_code:**

code returned by Viber when rejecting a message:

1 - Internal server error.

2 - The ID wasn’t in use for over a year/The ID was recently created and

wasn’t uploaded to the server yet.

3 - An error in the request’s structure. Could be a missing comma, brackets,

text over 1000 characters, etc.

5 - Incorrect message type. Either a non-supported type or an incorrect value.

6 - Missing mandatory parameters.

7 - Indicates a server timeout on Viber’s end.

8 - The ID was blocked by the user/The user blocked business messages

completely on their device.

9 - The destination number is not registered as a Viber user.

10 - Not an Android or iOS device with a Viber version that supports Business

Messages.

401 - The request was sent from a non-whitelisted IP for this ID/An incorrect ID

that doesn’t belong to the partner was used in the request.

13 - An error in the billing process

18 - Missing value/Incorrect value in the request for “label” parameter.

28 - The file that is being attempted to be sent is not in a supported format for

this feature.

29 - The name of the file is more than the maximum 25 characters.

30 - In case the thumbnail URL is compiled of more than 1000 characters.

38 - The provided template ID is not found (for OTP)

39 - Template variables did not pass the server validation (for OTP)

40 - One of the List messages parameters failed validation.

41 - One of the Carousel messages parameters failed validation.

**matching\_template\_id:**

ID issued by Viber when registering a template. If the parameter is present and the parameter value is empty, it means the message does not match any of the registered templates and has been re-rated from transactional to promotional message on the Viber side.

## **Viber messages statuses**

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

## **Errors**

| 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:

source\_addr more than 20 chars

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                 |

## Viber example

{% 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 allows you to send and receive WhatsApp business messages to and from any country in the world via API. Each message is identified by a unique random ID, so users can always check the status of a message using given endpoint.

The WhatsApp API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## 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                              |

## Examples Send WhatsApp message:

{% 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_xxx_xxxxx","language":{"policy":"deterministic","code":"en_US"},"name":"media_2_english","components":[{"type":"header","parameters":[{"type":"image","image":{"link":"url image.jpg"}}]}]}}'
```

{% 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 DecisionTelecom API allows you to verify your mobile phone number using two-factor authentication. Create a new Verify object via the API to start the recipient verification process. DecisionTelecom will take care of generating the token and ensuring that the message is delivered to the recipient.

The Verify API uses HTTPS with an access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding and URL-encoded values.

**API Authorization** - Basic Access Key Base64.

Please contact your account manager to get API key.

## Send Verification

{% 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"
}
```

#### Parameters:

**Id** <mark style="color:red;">string</mark> - a unique random identifier that is generated on the DecisionTelecom platform. - Required.

**phone** <mark style="color:red;">int</mark> - the phone number where you would like to make a request. - Required.

**pin\_lenght** <mark style="color:red;">int</mark> - PIN code length, from 4 to 10 digits. - Optional, by default 4.

**templete\_id** <mark style="color:red;">int</mark> - default 0 (template message text: your verification code: \d{4,10}) - Required.

**country\_iso** <mark style="color:red;">string</mark> - Optional, by default «en».

## Check PIN code

{% 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
}
```

All you have to do is to check the pin code value that the user enters during verification and pin code value that we return to you in the response. If they match, then the verification was successful.

## Verify examples

{% 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

DecisionTelecom Flash Call Verify API allows you to send flash calls verifications to any country in the world via API. The phone number from which the incoming call will be made, will contain the required code for verification, in the last 4-6 digits.

Each call is identified by a unique random ID.

The Flash Call Verify API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding and URL-encoded values.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## Send 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 allows you to send and receive Viber business messages to and from any country in the world via API, and if Viber message is not delivered to a client, it will be resend and delivered as regular SMS message. Each message is identified by a unique random ID, so users can always check the status of a message using given endpoint.

The Viber + SMS API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## **Auth**

## Basic Auth

#### **Example**:

```
$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);
```

## **Send Viber message**

{% 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":225, 									
    "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":1, 										
    "callback_url":"https://yourdomain.com/viber-callback",
    "validity_period":60
}
```

{% endtab %}
{% endtabs %}

## **Parameters**

**source\_addr:**

<= 20 chars - from whom the message

**destination\_addr:**

<= 20 chars - to whom the message

**message\_type (Type of message sent):**

225 only text (promotional messages)

108 text+image+button (promotional messages)

**text:**

<= 1000 chars - text of Viber message

**text\_sms:**

<= 70 chars for UCS-2 (16-bit) and <= 160 chars for Latin - alternative SMS text if Viber message is not delivered (only for transactional messages)

**image (Correct URL with image for promotional message with button caption and button action):**

jpg or jpeg (mime type is image/jpeg), maximum resolution 400x400 pixels

png (mime type is image/png), maximum resolution 400x400 pixels

**button\_caption:**

<= 30 chars - button caption

**button\_action:**

Correct URL for transition when you press the button

**source\_type (Message sending procedure):**

promotion message (the message can contain only text or text, an image, and a button) - 1

**callback\_url:**

Correct URL for message status callback

**validity\_period:**

TTL (Time to live) allows the sender to limit the life time of a message. In case the message did not get the status "delivered" before the time ended, the message will not be charged and will not be delivered to the user. In case no TTL was provided (no "ttl" parameter) Viber will try to deliver the message for up to 1 day.

promotional message - min TTL 40 seconds max TTL 21600 seconds (6 hours)

#### **Response:**

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

```json
{
    "message_id":4291233	
}
```

{% endtab %}
{% endtabs %}

#### **Values**:

**message\_id:**

Sent message ID

## **Receive Viber message**

{% 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 %}

## **Parameters**

**message\_id:**

The ID of the message whose status you want to get (for the last 5 days)

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

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

{% endtab %}
{% endtabs %}

## **Values**

**message\_id:**

The ID of the message whose status you want to get (for the last 5 days)

**status:**

Current Viber message status

**sms\_message\_id:**

SMS message ID (if available, the status of an SMS message can be obtained using the [SMS API](/sms-api))

## **Viber messages statuses**

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

## **Errors**

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

| Name    | Invalid Parameter: \[param\_name]             |
| ------- | --------------------------------------------- |
| messege | Empty parameter or parameter validation error |
| code    | 1                                             |
| status  | 400                                           |

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

| Name    | Topup balance is required |
| ------- | ------------------------- |
| messege | User balance is empty     |
| code    | 3                         |
| status  | 402                       |

## Viber + SMS example

{% 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 allows you to send network requests to any mobile number around the world. This allows you to view which mobile phone number belongs to which operator in real time and see if the number is active.

**API Authorization -** Basic access key Base64.

Please contact your account manager for an API key.

## Send HLR

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

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

{% endtab %}
{% endtabs %}

**Request JSON:**

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

#### **Parameters:**

**Phones**: <mark style="color:red;">array</mark> - The list of phone numbers on which you want to make a network request. - Required.

#### **Response:**

Returns JSON string if the request was successful.

```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"
 }
]  
```

#### **Parameters:**

**Id** <mark style="color:red;">int</mark> - A unique random identifier generated by the DecisionTelecom platform. - Required.

**status** <mark style="color:red;">string</mark> – phone state.

**Possible values:** accepted, sent, absent, active, unknown, and failed.

## **Status HLR**

#### **Request example:**

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

```
//singl
https://web.it-decision.com/v1/api/hlr-status?id=2345234
//bullk
https://web.it-decision.com/v1/api/hlr-status?id=["1","2","3"]
```

{% endtab %}
{% endtabs %}

#### **Response Example JSON:**

```json
//singl
{
    "id": 2345234,
    "phone": 38061122121,
    "mcc": "255",
    "mnc": "06",
    "network": "Lifecell",
    "ported": false,
    "status": 0,
    "error": 0,
    "type": "mobile",
    "present": "yes",
    "status_message": "Success"
}
//bullk
[
    {
        "id": "1",
        "phone": 120111111111,
        "mcc": "310",
        "mnc": "012",
        "network": "Verizon Wireless:6006 - SVR/2",
        "ported": false,
        "status": 0,
        "present": "yes",
        "error": 0,
        "type": "mobile",
        "status_message": "Success"
    },
    {
        "id": "2",
        "phone": 12011111111,
        "mcc": "310",
        "mnc": "260",
        "network": "T-Mobile US-SVR-10X/2",
        "ported": true,
        "status": 0,
        "present": "yes",
        "error": 0,
        "type": "mobile",
        "status_message": "Success"
    },
    {
        "id": "3",
        "phone": 120111111111,
        "mcc": "310",
        "mnc": "260",
        "network": "T-Mobile US-SVR-10X/2",
        "ported": true,
        "status": 0,
        "present": "yes",
        "error": 0,
        "type": "mobile",
        "status_message": "Success"
    }
]
```

## Values

**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 examples

{% 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 Telephony for Effective Communication. Use DecisionTelecom’s VoIP services and offer highquality calls through IP protocol to your customers, regardless of their location.

#### Worldwide calls

Use verified local numbers to call anywhere in the world and become even closer to your foreign customers.

#### Voice features

VoIP telephony offers you and your customers access to uninterrupted connection and a much better alternative to roaming calls.

#### Transparent payment system

Pay only for the actual time of talking. Our system charges for calls by the second, which means you won’t have to overpay.

#### SIP trunk

As MVNO we provide to our clients VoIP Gateway for reliable worldwide calling.

We provide interconnection via SIP protocol.&#x20;

Session Initiation Protocol (SIP) calling, it's process of transmitting voice calls over a SIP trunk or a SIP channel. SIP calling generally uses VoIP to move your analog call traffic over an internet connection.&#x20;

We can provide to as many SIP trunks as you need, it could be two or more, just let us know you needs.

#### Interconnection configuration

To create interconnection, we have to know your IP address.

The DecisionTelecom IP: 178.22.10.79

After creating SIP trunks, our Voice Support Team will provide to you with information about amount of SIP trunks, correspondent Prefixes and IPs.

#### **Questions?**

We are always happy to help with code or other doubts you may have! Check out our API, SDK reference or contact our support team: <https://www.decisiontele.com/en/contact-expert.html>.


# Viber Bot API

Decision Telecom Viber Bot API allows you to send and receive Viber Bot messages via API.

To implement the API, you will need the following:

1. **An Active Viber account** on a platform that supports bots (iOS/Android). This account will be set as the account administrator after the account creation process.
2. **Active bot** — since 5.02.24, Viber bots can only be created on commercial terms. Please contact our manager **to receive the Viber Bot activation form.**
3. **Account authentication token** - unique account identifier used to validate your account in all API requests. Each request posted to Rakuten Viber by the account will need to contain the token. When your bot is created, you will be added as an admin and the token will appear in your Viber account settings (More > Settings > Bots > Edit Info > Your app key)
4. **Set-up account webhook** — this needs to be done once during the account setup process to define your webhook and the type of responses you would like to receive.

**Supported platforms**

Bots are currently supported on iOS and Android devices running Viber version 6.5 and above and on desktop from version 6.5.3.

## API Authorization

The Viber Bot API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding.

Please contact your Decision Telecom account manager to **get an Base64 access API key**.

## Viber Bot Authorization

The authentication token (also known as application key) is a unique and secret account identifier. Each API request must include an HTTP Header called X-Viber-Auth-Token containing the account’s authentication token.

**Example**:

```
$userHashKey = 'User Hash Key provided by your account manager'; 
$ch = curl_init('https://web.it-decision.com/v2/api/viber-bot-set-webhook'); 
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(
	'X-Viber-Auth-Token: 445da6az1s345z78-dazcczb2542zv51a-e0vc5fva17480im9', 
	'Content-Type: application/json'
    )
); 
$result = curl_exec($ch); 
curl_close($ch);
```

The authentication token is generated upon bot creation and can be viewed by the account’s admins in the “edit info” screen of their bot or on the Viber Admin Panel.

<figure><img src="https://developers.viber.com/docs/img/authToken.jpg" alt=""><figcaption></figcaption></figure>

**Note:** Failing to send the authentication token in the header will result in an error.

## Webhooks

Once you have your token you will be able to set your account’s webhook. This webhook will be used for receiving callbacks and user messages from Viber.

Setting the webhook will be done by calling the `set_webhook` API with a valid & certified URL. This action defines the account’s webhook and the type of events the account wants to be notified about.

For security reasons only URLs with valid and official SSL certificate from a trusted CA will be allowed. The certificate CA should be on the Sun Java trusted root certificates list.

Once a `set_webhook` request is sent Viber will send a callback to the webhook to check its availability and return a response to the user. The check succeeds if the Viber server receives HTTP status 200 in response to the callback, but fails if it recieves any other status. If your set\_webhook response doesn’t have `"status":0`, please verify that all requests to your webhook URL receive HTTP status 200 in response.

Note that once you set your webhook the 1-on-1 conversation with your account will become available. To disable 1-on-1 conversation with your account you’ll need to remove your webhook – see [removing your webhook](#removing-your-webhook) below.

Viber’s API allows you to receive user names and photos. This has been updated to comply with privacy laws and allow developers who don’t make use of user names and photos as part of their service to opt out. If you don’t use user names photos, please opt-out to default values.

To set the request, pass `send_name` and `send_photo` flags with the `set_webhook` request.

**Note:** This feature will work if the user has allowed “Content Personalisation” (More → Privacy → personal data). If the user has disallowed content personalization, you will receive placeholder values.

### Setting a Webhook

**Resource URL**

```html
https://web.it-decision.com/v2/api/viber-bot-set-webhook
```

**Post data**

```json
{
   "url":"https://my.host.com",
   "event_types":[
      "delivered",
      "seen",
      "failed",
      "subscribed",
      "unsubscribed",
      "conversation_started"
   ],
   "send_name":true,
   "send_photo":true
}
```

**Post parameters**

| Name         | Description                                                                                                                                                              | Validation                                                                                                          |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| url          | required. Account webhook URL to receive callbacks & messages from users                                                                                                 | Webhook URL must use SSL Note: Viber doesn’t support self signed certificates                                       |
| event\_types | optional. Indicates the types of Viber events that the account owner would like to be notified about. **Don’t include this parameter in your request to get all events** | Possible values: `delivered`, `seen`, `failed`, `subscribed`, `unsubscribed` , `conversation_started` and `message` |
| send\_name   | optional. Indicates whether or not the bot should receive the user name. Default `true`                                                                                  | Possible values: `true`, `false`                                                                                    |
| send\_photo  | optional. Indicates whether or not the bot should receive the user photo. Default `true`                                                                                 | Possible values: `true`, `false`                                                                                    |

**Set webhook Response**

```json
{
   "status":0,
   "status_message":"ok",
   "event_types":[
      "subscribed",
      "unsubscribed",
      "conversation_started",
      "delivered",
      "failed",
      "message",
      "seen"
   ]
}
```

**Response parameters**

| Name            | Description                                                                                            | Possible values                                                                                                                                                                                                                                                                             |
| --------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| status          | Action result                                                                                          | `0` for success. In case of failure – appropriate failure status number. See [error codes](#error-codes) table for additional information                                                                                                                                                   |
| status\_message | `ok` or failure reason                                                                                 | <p>Success: <code>ok</code>.<br>Failure: <code>invalidAuthToken</code>, <code>badData</code>, <code>missingData</code> and <code>failure</code>. See <a href="#error-codes">error codes</a> table for additional information.<br>Http code 404: Requesting an invalid <code>URL</code>.</p> |
| event\_types    | List of event types you will receive a callback for. Should return the same values sent in the request | `delivered`, `seen`, `failed`, `subscribed`, `unsubscribed` , `conversation_started` and `message`                                                                                                                                                                                          |

**Event types filtering**

The `event_types` parameter allows accounts to choose which events they would get a callback for.\
The following events are mandatory and can’t be filtered out: `message`, `subscribed` and `unsubscribed`.\
The following events can be filtered out during the `set_webhook` request: `delivered`, `seen`, `failed` and `conversation_started`.\
Sending a `set_webhook` request with no event\_types parameter means getting **all** events.\
Sending a `set_webhook` request with empty `event_types` list `("event_types": [])` means getting **only mandatory** events. See [callbacks](#callbacks) section for full callbacks events information.

**Set webhook callback**

For each `set_webhook` request Viber will send a callback to the webhook URL to confirm it is available. The expected HTTP response to the callback is `200` OK – any other response will mean the webhook is not available. If the webhook is not available the `set_webhook` response sent to the user will be status 1: invalidUrl.

**Callback data**

```json
{
   "event":"webhook",
   "timestamp":1457764197627,
   "message_token":241256543215
}
```

**Callback parameters**

| Name           | Description                                        | Possible values |
| -------------- | -------------------------------------------------- | --------------- |
| event          | Callback type – which event triggered the callback | webhook         |
| timestamp      | Time of the event that triggered the callback      | Epoch time      |
| message\_token | Unique ID of the message                           |                 |

#### Removing your webhook <a href="#removing-your-webhook" id="removing-your-webhook"></a>

Once you set a webhook to your bot your 1-on-1 conversation button will appear and users will be able to access it.\
At the moment there is no option to disable the 1-on-1 conversation from the bot settings, so to disable this option you’ll need to remove the webhook you set for the account. Removing the webhook is done by Posting a `set_webhook` request with an empty webhook string.

**Resource URL**

```html
https://web.it-decision.com/v2/api/viber-bot-set-webhook
```

**Post data**

```json
{
   "url":""
}
```

**Post parameters**

| Name | Description                                                                                                                                      |
| ---- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| url  | required. Account webhook URL to receive callbacks & messages from users. In this case, use an empty string to remove any previously set webhook |

## Send Message <a href="#send-message" id="send-message"></a>

The `send_message` API allows accounts to send messages to Viber users who subscribe to the account. Sending a message to a user will be possible only after the user has subscribed to the bot. (see `subscribed` [callback](#subscribed) for additional information). You can share your bot with the users via a [deeplink](https://developers.viber.com/docs/tools/deep-links/).

The API supports a variety of message types: `text`, `picture`, `video`, `file`, `location`, `sticker`, `contact`, `carousel content` and `URL`. Specific post data examples and required parameters for each message type are given below.

**Validation**

Maximum total JSON size of the request is 10kb.

**Resource URL**

```html
https://web.it-decision.com/v2/api/viber-bot-send-message
```

#### General send message parameters <a href="#general-send-message-parameters" id="general-send-message-parameters"></a>

The following parameters are available for all message types:

| Name              | Description                                                                                                              | Validation                                                                                                                                      |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| receiver          | Unique Viber user id                                                                                                     | required, subscribed valid user id                                                                                                              |
| type              | Message type                                                                                                             | required. Available message types: `text`, `picture`, `video`, `file`, `location`, `contact`, `sticker`, `carousel content` and `url`           |
| sender.name       | The sender’s name to display                                                                                             | required. Max 28 characters                                                                                                                     |
| sender.avatar     | The sender’s avatar URL                                                                                                  | optional. Avatar size should be no more than 100 kb. Recommended 720x720                                                                        |
| tracking\_data    | Allow the account to track messages and user’s replies. Sent `tracking_data` value will be passed back with user’s reply | optional. max 4096 characters                                                                                                                   |
| min\_api\_version | Minimal API version required by clients for this message (default 1)                                                     | optional. client version support the API version. Certain features may not work as expected if set to a number that’s below their requirements. |

#### Response <a href="#response" id="response"></a>

**Response parameters**

| Name        | Description              | Possible values |
| ----------- | ------------------------ | --------------- |
| message\_id | Unique ID of the message |                 |

**Response example:**

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

**Callback parameters**

| Name            | Description                                                                                                          | Possible values                                                                                                                                                                                                                                                                             |
| --------------- | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| status          | Action result                                                                                                        | `0` for success. In case of failure - appropriate failure status number. See [error codes](#error-codes) table for additional information                                                                                                                                                   |
| status\_message | `ok` or failure reason                                                                                               | <p>Success: <code>ok</code>.<br>Failure: <code>invalidAuthToken</code>, <code>badData</code>, <code>missingData</code> and <code>failure</code>. See <a href="#error-codes">error codes</a> table for additional information.<br>Http code 404: Requesting an invalid <code>URL</code>.</p> |
| message\_id     | Unique ID of the message                                                                                             |                                                                                                                                                                                                                                                                                             |
| message\_token  | Unique ID of the message received from Viber                                                                         |                                                                                                                                                                                                                                                                                             |
| chat\_hostname  | Internal use                                                                                                         |                                                                                                                                                                                                                                                                                             |
| billing\_status | An indication of how this message is categorized for billing purposes, allowing you to know if it was charged or not | An integer between 0 and 5. See below an explanation for all possible values.                                                                                                                                                                                                               |

Below you can find the possible values for the billing\_status parameter:

| Value | Description                                                                                              |
| ----- | -------------------------------------------------------------------------------------------------------- |
| `0`   | Default for all cases other than the ones listed below: chat extension, reply to open conversation, etc. |
| `1`   | 1:1 message/keyboard sent in a session                                                                   |
| `2`   | 1:1 message/keyboard sent in a session                                                                   |
| `3`   | Free out of session 1:1 message/keyboard                                                                 |
| `4`   | Free out of session 1:1 message/keyboard                                                                 |
| `5`   | Charged out of session 1:1 message/keyboard                                                              |

**Callback example:**

```json
{
   "status":0,
   "status_message":"ok",
   "message_token":5741311803571721087,
   "chat_hostname":"SN-CHAT-05_",
   "billing_status":1
}
```

#### Message types <a href="#message-types" id="message-types"></a>

Below is a list of all supported message types with post data examples.

**Text message**

**Post data**

```json
{
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"text",
   "text":"Hello world!"
}
```

**Post parameters**

| Name | Description             | Validation                                                                                            |
| ---- | ----------------------- | ----------------------------------------------------------------------------------------------------- |
| type | Message type            | required. `text`. Supports [text formatting](https://developers.viber.com/docs/tools/text-formatting) |
| text | The text of the message | required. Max length 7,000 characters                                                                 |

**Picture message**

**Post data**

```json
{  
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{  
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"picture",
   "text":"Photo description",
   "media":"https://www.images.com/img.jpg",
   "thumbnail":"https://www.images.com/thumb.jpg"
}
```

**Post parameters**

| Name      | Description                                                    | Validation                                                                                                                                                                                                                                                                                     |
| --------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type      | Message type                                                   | required. `picture`                                                                                                                                                                                                                                                                            |
| text      | Description of the photo. Can be an empty string if irrelevant | required. Max 768 characters                                                                                                                                                                                                                                                                   |
| media     | URL of the image (JPEG, PNG, non-animated GIF)                 | required. The URL must have a resource with a `.jpeg`, `.png` or `.gif` file extension as the last path segment. Example: `https://www.example.com/path/image.jpeg`. Max image size: 1MB on iOS, 3MB on Android. **Note** GIFs are only static. To send animated GIFs please check URL message |
| thumbnail | URL of a reduced size image (JPEG, PNG, GIF)                   | optional. Recommended: 400x400. Max size: 100kb.                                                                                                                                                                                                                                               |

**Video message**

**Post data**

```json
{  
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{  
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"video",
   "media":"https://www.images.com/video.mp4",
   "thumbnail":"https://www.images.com/thumb.jpg",
   "size":10000,
   "duration":10
}
```

**Post parameters**

| Name      | Description                                                  | Validation                                                                                                                                                                                       |
| --------- | ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| type      | Message type                                                 | required. `video`                                                                                                                                                                                |
| media     | URL of the video (MP4, H264)                                 | required. Max size 26 MB. Only MP4 and H264 are supported. The URL must have a resource with a `.mp4` file extension as the last path segment. Example: `https://www.example.com/path/video.mp4` |
| size      | Size of the video in bytes                                   | required                                                                                                                                                                                         |
| duration  | Video duration in seconds; will be displayed to the receiver | optional. Max 180 seconds                                                                                                                                                                        |
| thumbnail | URL of a reduced size image (JPEG)                           | optional. Max size 100 kb. Recommended: 400x400. Only JPEG format is supported                                                                                                                   |

**File message**

**Post data**

```json
{  
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{  
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"file",
   "media":"https://www.images.com/file.doc",
   "size":10000,
   "file_name":"name_of_file.doc"
}
```

**Post parameters**

| Name       | Description               | Validation                                                                                                                                                                                                     |
| ---------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| type       | Message type              | required. `file`                                                                                                                                                                                               |
| media      | URL of the file           | required. Max size 50 MB. URL should include the file extension. See [forbidden file formats](#forbidden-file-formats) for unsupported file types                                                              |
| size       | Size of the file in bytes | required                                                                                                                                                                                                       |
| file\_name | Name of the file          | required. File name should include extension. Max 256 characters (including file extension). Sending a file without extension or with the wrong extension might cause the client to be unable to open the file |

**Contact message**

**Post data**

```json
{
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"contact",
   "contact":{
      "name":"Itamar",
      "phone_number":"+972511123123"
   }
}
```

**Post parameters**

| Name                  | Description                 | Validation                  |
| --------------------- | --------------------------- | --------------------------- |
| type                  | Message type                | required. `contact`         |
| contact.name          | Name of the contact         | required. Max 28 characters |
| contact.phone\_number | Phone number of the contact | required. Max 18 characters |

**Location message**

**Post data**

```json
{
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"location",
   "location":{
      "lat":"37.7898",
      "lon":"-122.3942"
   }
}
```

**Post parameters**

| Name     | Description          | Validation                                                        |
| -------- | -------------------- | ----------------------------------------------------------------- |
| type     | Message type         | required. `location`                                              |
| location | Location coordinates | required. latitude (±90°) & longitude (±180°) within valid ranges |

**URL message**

**Post data**

```json
{
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"url",
   "media":"https://www.website.com/go_here"
}
```

**Post parameters**

| Name  | Description  | Validation                     |
| ----- | ------------ | ------------------------------ |
| type  | Message type | required. `url`                |
| media | URL, GIF     | required. Max 2,000 characters |

**Sticker message**

**Post data**

```json
{
   "receiver":"01234567890A=",
   "min_api_version":1,
   "sender":{
      "name":"John McClane",
      "avatar":"https://avatar.example.com"
   },
   "tracking_data":"tracking data",
   "type":"sticker",
   "sticker_id":46105
}
```

**Post parameters**

| Name        | Description                                                                                                             | Validation          |
| ----------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------- |
| type        | Message type                                                                                                            | required. `sticker` |
| sticker\_id | Unique Viber sticker ID. For examples visit the [sticker IDs](https://developers.viber.com/docs/tools/sticker-ids) page |                     |

**Rich Media message / Carousel content message**

The Rich Media message type allows sending messages with pre-defined layout, including height (rows number), width (columns number), text, images and buttons.

Below you will find an exmaple of a Carousel Content Message, that allows a user to scroll through a list of items, each composed of an image, description and call to action button.

![](https://developers.viber.com/docs/img/rest_rich_messages.jpg)

Each item on the list shown to the user is a button in the Rich Media message’s “Buttons” array. Sending one button is also permitted.

The parameters for Rich Media message and its buttons are also used for Keyboards. You can find additional information on them in [the following article](https://developers.viber.com/docs/tools/keyboards/).

**Notes:**

1. Carousel Content Message is supported on devices running Viber version 6.7 and above.
2. Each button is limited to a maximum of 7 rows.
3. Forwarding is not supported for Rich Media messages.
4. ActionTypes `location-picker` and `share-phone` are not supported for Rich Media messages.

**Post data**

```json
{
   "receiver":"nsId6t9MWy3mq09RAeXiug==",
   "type":"rich_media",
   "min_api_version":7,
   "rich_media":{
      "Type":"rich_media",
      "ButtonsGroupColumns":6,
      "ButtonsGroupRows":7,
      "BgColor":"#FFFFFF",
      "Buttons":[
         {
            "Columns":6,
            "Rows":3,
            "ActionType":"open-url",
            "ActionBody":"https://www.google.com",
            "Image":"https://html-test:8080/myweb/guy/assets/imageRMsmall2.png"
         },
         {
            "Columns":6,
            "Rows":2,
            "Text":"<font color=#323232><b>Headphones with Microphone, On-ear Wired earphones</b></font><font color=#777777><br>Sound Intone </font><font color=#6fc133>$17.99</font>",
            "ActionType":"open-url",
            "ActionBody":"https://www.google.com",
            "TextSize":"medium",
            "TextVAlign":"middle",
            "TextHAlign":"left"
         },
         {
            "Columns":6,
            "Rows":1,
            "ActionType":"reply",
            "ActionBody":"https://www.google.com",
            "Text":"<font color=#ffffff>Buy</font>",
            "TextSize":"large",
            "TextVAlign":"middle",
            "TextHAlign":"middle",
            "Image":"https://s14.postimg.org/4mmt4rw1t/Button.png"
         },
         {
            "Columns":6,
            "Rows":1,
            "ActionType":"reply",
            "ActionBody":"https://www.google.com",
            "Text":"<font color=#8367db>MORE DETAILS</font>",
            "TextSize":"small",
            "TextVAlign":"middle",
            "TextHAlign":"middle"
         },
         {
            "Columns":6,
            "Rows":3,
            "ActionType":"open-url",
            "ActionBody":"https://www.google.com",
            "Image":"https://s16.postimg.org/wi8jx20wl/image_RMsmall2.png"
         },
         {
            "Columns":6,
            "Rows":2,
            "Text":"<font color=#323232><b>Hanes Men's Humor Graphic T-Shirt</b></font><font color=#777777><br>Hanes</font><font color=#6fc133>$10.99</font>",
            "ActionType":"open-url",
            "ActionBody":"https://www.google.com",
            "TextSize":"medium",
            "TextVAlign":"middle",
            "TextHAlign":"left"
         },
         {
            "Columns":6,
            "Rows":1,
            "ActionType":"reply",
            "ActionBody":"https://www.google.com",
            "Text":"<font color=#ffffff>Buy</font>",
            "TextSize":"large",
            "TextVAlign":"middle",
            "TextHAlign":"middle",
            "Image":"https://s14.postimg.org/4mmt4rw1t/Button.png"
         },
         {
            "Columns":6,
            "Rows":1,
            "ActionType":"reply",
            "ActionBody":"https://www.google.com",
            "Text":"<font color=#8367db>MORE DETAILS</font>",
            "TextSize":"small",
            "TextVAlign":"middle",
            "TextHAlign":"middle"
         }
      ]
   }
}
```

**Post parameters**

| Name                            | Description                                                     | Possible values                                     |
| ------------------------------- | --------------------------------------------------------------- | --------------------------------------------------- |
| alt\_text                       | Backward compatibility text                                     |                                                     |
| rich\_media.ButtonsGroupColumns | Number of columns per carousel content block. Default 6 columns | 1 - 6                                               |
| rich\_media.ButtonsGroupRows    | Number of rows per carousel content block. Default 7 rows       | 1 - 7                                               |
| rich\_media.Buttons             | Array of buttons                                                | Max of 6 \* ButtonsGroupColumns \* ButtonsGroupRows |

**Button element**

| Name    | Description                                     | Possible values        |
| ------- | ----------------------------------------------- | ---------------------- |
| Columns | Button column span. Default ButtonsGroupColumns | 1..ButtonsGroupColumns |
| Rows    | Button row span. Default ButtonsGroupRows       | 1..ButtonsGroupRows    |

### Keyboards <a href="#keyboards" id="keyboards"></a>

The Viber API allows sending a custom keyboard using the `send_message` API, to supply the user with a set of predefined replies or actions. The keyboard can be attached to any message type or sent on it’s on. Once received, the keyboard will appear to the user instead of the device’s native keyboard. The keyboards are fully customizable and can be created and designed specifically for the account’s needs. The client will always display the last keyboard that was sent to it.

Read [the following article](https://developers.viber.com/docs/tools/keyboards/) to learn more about keyboards.

**Validation**

Maximum total JSON size of the request is 10kb.

#### Resource URL <a href="#resource-url-3" id="resource-url-3"></a>

```html
https://web.it-decision.com/v2/api/viber-bot-send-message
```

#### Post data <a href="#post-data-11" id="post-data-11"></a>

Keyboards can be attached to any message type and be sent and displayed together. To attach a keyboard to a message simply add the keyboard’s parameters to the message JSON.\
The example below shows a keyboard sent with a text message (note that the keyboard doesn’t contain all optional values).

```json
{
   "receiver":"01234567890A=",
   "min_api_version":7,
   "type":"text",
   "text":"Hello world",
   "keyboard":{
      "Type":"keyboard",
      "DefaultHeight":false,
      "Buttons":[
         {
            "ActionType":"reply",
            "ActionBody":"reply to me",
            "Text":"Key text",
            "TextSize":"regular"
         }
      ]
   }
}
```

### Get Account Info <a href="#get-account-info" id="get-account-info"></a>

The `get_account_info` request will fetch the account’s details as registered in Viber. The account admin will be able to edit most of these details from his Viber client.

#### Resource URL <a href="#resource-url-5" id="resource-url-5"></a>

```html
https://web.it-decision.com/v2/api/viber-bot-get-account-info
```

#### Post data <a href="#post-data-12" id="post-data-12"></a>

```json
{
}
```

#### Response <a href="#response-2" id="response-2"></a>

```json
{
   "status":0,
   "status_message":"ok",
   "id":"pa:75346594275468546724",
   "name":"account name",
   "uri":"accountUri",
   "icon":"https://example.com",
   "background":"https://example.com",
   "category":"category",
   "subcategory":"sub category",
   "location":{
      "lon":0.1,
      "lat":0.2
   },
   "country":"UK",
   "webhook":"https://my.site.com",
   "event_types":[
      "delivered",
      "seen"
   ],
   "subscribers_count":35,
   "members":[
      {
         "id":"01234567890A=",
         "name":"my name",
         "avatar":"https://example.com",
         "role":"admin"
      }
   ]
}
```

**Response parameters**

| Name               | Description                                                               | Possible values                                                                                                                                                                                                                                                                             |
| ------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| status             | Action result                                                             | `0` for success. In case of failure – appropriate failure status number. See [error codes](#error-codes) table for additional information                                                                                                                                                   |
| status\_message    | `ok` or failure reason                                                    | <p>Success: <code>ok</code>.<br>Failure: <code>invalidAuthToken</code>, <code>badData</code>, <code>missingData</code> and <code>failure</code>. See <a href="#error-codes">error codes</a> table for additional information.<br>Http code 404: Requesting an invalid <code>URL</code>.</p> |
| id                 | Unique numeric id of the account                                          |                                                                                                                                                                                                                                                                                             |
| name               | Account name                                                              | Max 75 characters                                                                                                                                                                                                                                                                           |
| uri                | Unique URI of the Account                                                 |                                                                                                                                                                                                                                                                                             |
| icon               | Account icon URL                                                          | JPEG, 720x720, size no more than 512 kb                                                                                                                                                                                                                                                     |
| background         | Conversation background URL                                               | JPEG, max 1920x1920, size no more than 512 kb                                                                                                                                                                                                                                               |
| category           | Account category                                                          |                                                                                                                                                                                                                                                                                             |
| subcategory        | Account sub-category                                                      |                                                                                                                                                                                                                                                                                             |
| location           | Account location (coordinates). Will be used for finding accounts near me | lat & lon coordinates                                                                                                                                                                                                                                                                       |
| country            | Account country                                                           | 2 letters country code - ISO ALPHA-2 Code                                                                                                                                                                                                                                                   |
| webhook            | Account registered webhook                                                | webhook URL                                                                                                                                                                                                                                                                                 |
| event\_types       | Account registered events – as set by `set_webhook` request               | `delivered`, `seen`, `failed` and `conversation_started`                                                                                                                                                                                                                                    |
| subscribers\_count | Number of subscribers                                                     |                                                                                                                                                                                                                                                                                             |
| members            | Members of the bot’s public chat                                          | `id`, `name`, `avatar`, `role` for each Public Chat member (admin/participant). Deprecated.                                                                                                                                                                                                 |

### Get User Details <a href="#get-user-details" id="get-user-details"></a>

The `get_user_details` request will fetch the details of a specific Viber user based on his unique user ID. The user ID can be obtained from the callbacks sent to the account regarding user’s actions. This request can be sent twice during a 12 hours period for each user ID.

#### Resource URL <a href="#resource-url-6" id="resource-url-6"></a>

```html
https://web.it-decision.com/v2/api/viber-bot-get-user-details
```

#### Post data <a href="#post-data-13" id="post-data-13"></a>

```json
{
   "id":"01234567890A="
}
```

**Post parameters**

| Name | Description          | Validation                         |
| ---- | -------------------- | ---------------------------------- |
| id   | Unique Viber user id | required. subscribed valid user id |

#### Response <a href="#response-3" id="response-3"></a>

```json
{
   "status":0,
   "status_message":"ok",
   "message_token":4912661846655238145,
   "user":{
      "id":"01234567890A=",
      "name":"John McClane",
      "avatar":"https://avatar.example.com",
      "country":"UK",
      "language":"en",
      "primary_device_os":"android 7.1",
      "api_version":1,
      "viber_version":"6.5.0",
      "mcc":1,
      "mnc":1,
      "device_type":"iPhone9,4"
   }
}
```

**Response parameters**

| Name                     | Description                                                         | Possible values                                                                                                                                                                                                                                                                                                                    |
| ------------------------ | ------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| status                   | Action result                                                       | `0` for success. In case of failure – appropriate failure status number. See [error codes](#error-codes) table for additional information                                                                                                                                                                                          |
| status\_message          | `ok` or failure reason                                              | <p>Success: <code>ok</code>.<br>Failure: <code>invalidAuthToken</code>, <code>badData</code>, <code>receiverNoSuitableDevice</code>, <code>missingData</code> and <code>failure</code>. See <a href="#error-codes">error codes</a> table for additional information.<br>Http code 404: Requesting an invalid <code>URL</code>.</p> |
| message\_token           | Unique id of the message                                            |                                                                                                                                                                                                                                                                                                                                    |
| user.id                  | Unique Viber user id                                                |                                                                                                                                                                                                                                                                                                                                    |
| user.name                | User’s Viber name                                                   |                                                                                                                                                                                                                                                                                                                                    |
| user.avatar              | URL of the user’s avatar                                            |                                                                                                                                                                                                                                                                                                                                    |
| user.country             | User’s country code                                                 | 2 letters country code - ISO ALPHA-2 Code                                                                                                                                                                                                                                                                                          |
| user.language            | The language set in the user’s Viber settings.                      | ISO 639-1                                                                                                                                                                                                                                                                                                                          |
| user.primary\_device\_os | The operating system type and version of the user’s primary device. |                                                                                                                                                                                                                                                                                                                                    |
| user.api\_version        | Max API version, matching the most updated user’s device            | Currently only 1. Additional versions will be added in the future                                                                                                                                                                                                                                                                  |
| user.viber\_version      | The Viber version installed on the user’s primary device            |                                                                                                                                                                                                                                                                                                                                    |
| user.mcc                 | Mobile country code                                                 |                                                                                                                                                                                                                                                                                                                                    |
| user.mnc                 | Mobile network code                                                 |                                                                                                                                                                                                                                                                                                                                    |
| user.device\_type        | The user’s device type                                              |                                                                                                                                                                                                                                                                                                                                    |

### Get Online <a href="#get-online" id="get-online"></a>

The `get_online` request will fetch the online status of a given subscribed account members. The API supports up to 100 user id per request and those users must be subscribed to the account.

#### Resource URL <a href="#resource-url-7" id="resource-url-7"></a>

```html
https://web.it-decision.com/v2/api/viber-bot-get-online
```

#### Post data <a href="#post-data-14" id="post-data-14"></a>

```json
{  
   "ids":[  
      "01234567890=",
      "01234567891=",
      "01234567893="
   ]
}
```

**Post parameters**

| Name | Description          | Validation                    |
| ---- | -------------------- | ----------------------------- |
| ids  | Unique Viber user id | required. 100 ids per request |

#### Response <a href="#response-4" id="response-4"></a>

```json
{
   "status":0,
   "status_message":"ok",
   "users":[
      {
         "id":"01234567890=",
         "online_status":0,
         "online_status_message":"online"
      },
      {
         "id":"01234567891=",
         "online_status":1,
         "online_status_message":"offline",
         "last_online":1457764197627
      },
      {
         "id":"01234567893=",
         "online_status":3,
         "online_status_message":"tryLater"
      }
   ]
}
```

**Response parameters**

| Name                              | Description            | Possible values                                                                                                                                                                                                                                                                             |   |
| --------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | - |
| status                            | Action result          | `0` for success. In case of failure – appropriate failure status number. See [error codes](#error-codes) table for additional information                                                                                                                                                   |   |
| status\_message                   | `ok` or failure reason | <p>Success: <code>ok</code>.<br>Failure: <code>invalidAuthToken</code>, <code>badData</code>, <code>missingData</code> and <code>failure</code>. See <a href="#error-codes">error codes</a> table for additional information.<br>Http code 404: Requesting an invalid <code>URL</code>.</p> |   |
| user\[x].id                       | Unique Viber user id   |                                                                                                                                                                                                                                                                                             |   |
| user\[x].online\_status           | Online status code     | `0` for online, `1` for offline, `2` for undisclosed - user set Viber to hide status, `3` for try later - internal error, `4` for unavailable - not a Viber user / unsubscribed / unregistered                                                                                              |   |
| user\[x]. online\_status\_message | Online status message  |                                                                                                                                                                                                                                                                                             |   |

### Callbacks <a href="#callbacks" id="callbacks"></a>

Callbacks will come from a specific IP: **35.156.198.8**

#### Re-try logic

In case the webhook is offline Decision Telecom server will re-try to deliver the callback until HTTP status code `200` is received. There will be 3 retry attempts with exponential intervals:

1. 5 minutes
2. 15 minutes
3. 30 minutes

#### Subscribed <a href="#subscribed" id="subscribed"></a>

Before an account can send messages to a user, the user will need to subscribe to the account. Subscribing can take place if the user sends a message to the bot - when a user sends its first message to a bot the user will be automatically subscribed to the bot. Sending the first message will not trigger a subscribe callback, only a message callback (see [receive message from user](#receive-message-from-user) section).

You will receive a subscribed event when unsubscribed users do the following:

1. Open conversation with the bot.
2. Tap on the 3-dots button in the top right and then on “Chat Info”.
3. Tap on “Receive messages”.

**Note:** A subscribe event will delete any `context` or `tracking_data` information related to the conversation. This means that if a user had a conversation with a service and then chose to unsubscribe and subscribe again, a new conversation will be started without any information related to the old conversation.

**Callback data**

```json
{
   "event":"subscribed",
   "timestamp":1457764197627,
   "user":{
      "id":"01234567890A=",
      "name":"John McClane",
      "avatar":"https://avatar.example.com",
      "country":"UK",
      "language":"en",
      "api_version":1
   },
   "message_token":4912661846655238145
}
```

**Callback parameters**

| Name              | Description                                                              | Possible values  |
| ----------------- | ------------------------------------------------------------------------ | ---------------- |
| event             | Callback type - which event triggered the callback                       | subscribed       |
| timestamp         | Time of the event that triggered the callback                            | Epoch time       |
| user.id           | Unique Viber user id                                                     |                  |
| user.name         | User’s Viber name                                                        |                  |
| user.avatar       | URL of user’s avatar                                                     |                  |
| user.country      | User’s 2 letter country code                                             | ISO ALPHA-2 Code |
| user.language     | User’s phone language. Will be returned according to the device language | ISO 639-1        |
| user.api\_version | The maximal Viber version that is supported by all of the user’s devices |                  |
| message\_token    | Unique ID of the message                                                 |                  |
| chat\_hostname    | Internal use                                                             |                  |

#### Unsubscribed <a href="#unsubscribed" id="unsubscribed"></a>

The user will have the option to unsubscribe from the PA. This will trigger an unsubscribed callback.

**Callback data**

```json
{
   "event":"unsubscribed",
   "timestamp":1457764197627,
   "user_id":"01234567890A=",
   "message_token":4912661846655238145
}
```

**Callback parameters**

| Name           | Description                                        | Possible values |
| -------------- | -------------------------------------------------- | --------------- |
| event          | Callback type - which event triggered the callback | unsubscribed    |
| timestamp      | Time of the event that triggered the callback      | Epoch time      |
| user\_id       | Unique Viber user id                               |                 |
| message\_token | Unique ID of the message                           |                 |

#### Conversation started <a href="#conversation-started" id="conversation-started"></a>

Conversation started event fires when a user opens a conversation with the bot using the “message” button (found on the account’s info screen) or using a [deep link](https://developers.viber.com/docs/tools/deep-links).

This event is **not** considered a subscribe event and doesn’t allow the account to send messages to the user; however, it will allow sending one “welcome message” to the user. See [sending a welcome message](#sending-a-welcome-message) below for more information.

Once a `conversation_started` callback is received, the Bot will be able to send a single “welcome message” sent as a regular `send_message` request. The `receiver` parameter is **mandatory** in this case.

**Note**: the `conversation_started` callback doesn’t contain the `context` parameter by default.

To add this paramater and determine its value, you can use a deeplink like this: `viber://pa?chatURI=your_bot_URI&context=your_context`

**Callback data**

```json
{
   "event":"conversation_started",
   "timestamp":1457764197627,
   "message_token":4912661846655238145,
   "type":"open",
   "context":"context information",
   "user":{
      "id":"01234567890A=",
      "name":"John McClane",
      "avatar":"https://avatar.example.com",
      "country":"UK",
      "language":"en",
      "api_version":1
   },
   "subscribed":false
}
```

**Callback parameters**

| Name              | Description                                                                                                                                                                                                 | Possible values                                     |
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| event             | Callback type - which event triggered the callback                                                                                                                                                          | `conversation_started`                              |
| timestamp         | Time of the event that triggered the callback                                                                                                                                                               | Epoch time                                          |
| message\_token    | Unique ID of the message                                                                                                                                                                                    |                                                     |
| type              | The specific type of `conversation_started` event                                                                                                                                                           | `open`. Additional types may be added in the future |
| context           | Any additional parameters added to the deep link used to access the conversation passed as a string. See [deep link](https://developers.viber.com/docs/tools/deep-links) section for additional information |                                                     |
| user.id           | Unique Viber user id                                                                                                                                                                                        |                                                     |
| user.name         | User’s Viber name                                                                                                                                                                                           |                                                     |
| user.avatar       | URL of user’s avatar                                                                                                                                                                                        |                                                     |
| user.country      | User’s 2 letter country code                                                                                                                                                                                | ISO ALPHA-2 Code                                    |
| user.language     | User’s phone language                                                                                                                                                                                       |                                                     |
| user.api\_version | Max API version, matching the most updated user’s device                                                                                                                                                    |                                                     |
| subscribed        | indicated whether a user is already subscribed                                                                                                                                                              | `true` if subscribed and `false` otherwise          |

#### Sending a welcome message <a href="#sending-a-welcome-message" id="sending-a-welcome-message"></a>

The Viber API allows sending messages to users only after they subscribe to the account. However, Viber allows the account to send a single “welcome message” to a user when the user initiates the conversation, before the user subscribed.

The welcome message will be sent as a regular message, following `conversation_started` callback, which will be received from Viber once the user opens the conversation with the account. To learn more about conversation\_started event and its triggering conditions, please refer to [`Conversation started`](#conversation-started) in the callbacks section of the documentation.

**Welcome message flow**

Sending a welcome message will be done according to the following flow:

1. The user initiates a one-on-one conversation with the bot.
2. The Viber server sends `conversation_started` event to bot’s webhook.
3. The account receives the `conversation_started` event and should respond within **5 minutes** by sending a message request to the[ `send_message`](#send-message) endpoint.

#### Message receipts callbacks <a href="#message-receipts-callbacks" id="message-receipts-callbacks"></a>

Viber offers message status updates for each message sent, allowing the account to be notified when the message was delivered to the user’s device (`delivered status`) and when the conversation containing the message was opened (`seen status`).

The seen callback will only be sent once when the user reads the unread messages, regardless of the number of messages sent to them, or the number of devices they are using.

If the message recipient is using their Viber account on multiple devices, each of the devices will return a delivered, meaning that several delivered callbacks can be received for a single message.

If Viber is unable to deliver the message to the client it will try to deliver it for up to 14 days. If the message wasn’t delivered within the 14 days it will not be delivered and no “delivered” or “seen” callbacks will be received for it.

**Callback data**

**Delivered**

```json
{
   "event":"delivered",
   "timestamp":1457764197627,
   "message_id":29275345,
   "message_token":4912661846655238145,
   "user_id":"01234567890A="
}
```

**Seen**

```json
{
   "event":"seen",
   "timestamp":1457764197627,
   "message_id":29275345,
   "message_token":4912661846655238145,
   "user_id":"01234567890A="
}
```

**Callback parameters**

| Name           | Description                                        | Possible values     |
| -------------- | -------------------------------------------------- | ------------------- |
| event          | Callback type - which event triggered the callback | `delivered`, `seen` |
| timestamp      | Time of the event that triggered the callback      | Epoch time          |
| message\_id    | Unique ID of the message on Decison Telecom server |                     |
| message\_token | Unique ID of the message on Viber server           |                     |
| user\_id       | Unique Viber user id                               |                     |

#### Failed callback <a href="#failed-callback" id="failed-callback"></a>

The “failed” callback will be triggered if a message has reached the client but failed any of the client validations.

Since some of the message validations take place on the server while the others take place on the client, some messages may only fail after reaching the client. In such cases the flow will be as follows:

1. Message is sent.
2. Response with status 0 is received to indicate a successful request.
3. The message reaches the client and fails client validation.
4. “Failed” callback is sent to the webhook, containing the unique message token and a string explaining the failure.

Even though the verification fails, such messages can still be delivered to users and receive delivery statuses.

**Callback data**

```json
{  
   "event":"failed",
   "timestamp":1457764197627,
   "message_id":29275345,
   "message_token":4912661846655238145,
   "user_id":"01234567890A=",
   "desc":"failure description"
}
```

**Callback parameters**

| Name           | Description                                        | Possible values |
| -------------- | -------------------------------------------------- | --------------- |
| event          | Callback type - which event triggered the callback | `failed`        |
| timestamp      | Time of the event that triggered the callback      | Epoch time      |
| message\_id    | Unique ID of the message on Decison Telecom server |                 |
| message\_token | Unique ID of the message on Viber server           |                 |
| user\_id       | Unique Viber user id                               |                 |
| desc           | A string describing the failure                    |                 |

#### Receive message from user <a href="#receive-message-from-user" id="receive-message-from-user"></a>

The API allows the user to send messages to the PA. Excluding `file` type, all message types are supported for sending from bot to user and from user to bot. These include: `text`, `picture`, `video`, `contact`, `URL` and `location`. The following callback data describes the structure of messages sent from user to PA.

**Callback data**

```json
{
   "event":"message",
   "timestamp":1457764197627,
   "message_token":4912661846655238145,
   "sender":{
      "id":"01234567890A=",
      "name":"John McClane",
      "avatar":"https://avatar.example.com",
      "country":"UK",
      "language":"en",
      "api_version":1
   },
   "message":{
      "type":"text",
      "text":"a message to the service",
      "media":"https://example.com",
      "location":{
         "lat":50.76891,
         "lon":6.11499
      },
      "tracking_data":"tracking data"
   }
}
```

**Callback general parameters**

| Name                | Description                                                                | Possible values  |
| ------------------- | -------------------------------------------------------------------------- | ---------------- |
| event               | Callback type - which event triggered the callback                         | `message`        |
| timestamp           | Time of the event that triggered the callback                              | Epoch time       |
| message\_token      | Unique ID of the message                                                   |                  |
| sender.id           | Unique Viber user id of the message sender                                 |                  |
| sender.name         | Sender’s Viber name                                                        |                  |
| sender.avatar       | Sender’s avatar URL                                                        |                  |
| sender.country      | Sender’s 2 letter country code                                             | ISO ALPHA-2 Code |
| sender.language     | Sender’s phone language. Will be returned according to the device language | ISO 639-1        |
| sender.api\_version | The maximal Viber version that is supported by all of the user’s devices   |                  |
| message             | Detailed in the chart below                                                |                  |

**Callback message parameters**

The callback message parameters depend on the type of message. For each message type, only the relevant parameters will be received.

| Name           | Description                                                                                                           | Possible values                                                                |
| -------------- | --------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| type           | Message type                                                                                                          | `text`, `picture`, `video`, `file`, `sticker`, `contact`, `url` and `location` |
| text           | The message text                                                                                                      |                                                                                |
| media          | URL of the message media - can be `image`, `video`, `file` and `url`. Image/Video/File URLs will have a TTL of 1 hour |                                                                                |
| location       | Location coordinates                                                                                                  | lat & lon within valid ranges                                                  |
| contact        | `name` - contact’s username, `phone_number` - contact’s phone number and `avatar` as the avatar URL                   | `name` - max 128 characters. Only one `phone_number` per contact can be sent   |
| tracking\_data | Tracking data sent with the last message to the user                                                                  |                                                                                |
| file\_name     | File name                                                                                                             | Relevant for `file` type messages                                              |
| file\_size     | File size in bytes                                                                                                    | Relevant for `file` type messages                                              |
| duration       | Video length in milliseconds                                                                                          | Relevant for `video` type messages                                             |
| sticker\_id    | Viber sticker id                                                                                                      | Relevant for `sticker` type messages                                           |

**Message status**

Once a `200` OK response is received from the PA, the message status will change to `delivered` on the user’s side. “Seen” status is not currently supported for messages sent from user to PA.

### Error Codes <a href="#error-codes" id="error-codes"></a>

The following error codes will be returned with API responses. The `status` parameter will include the error code value while the `status_message` parameter will include the error name or a more specific string describing the error.

| Value | Name                           | Description                                                                                             |
| ----- | ------------------------------ | ------------------------------------------------------------------------------------------------------- |
| `0`   | `ok`                           | Success                                                                                                 |
| `1`   | `invalidUrl`                   | The webhook URL is not valid                                                                            |
| `2`   | `invalidAuthToken`             | The authentication token is not valid                                                                   |
| `3`   | `badData`                      | There is an error in the request itself (missing comma, brackets, etc.)                                 |
| `4`   | `missingData`                  | Some mandatory data is missing                                                                          |
| `5`   | `receiverNotRegistered`        | The receiver is not registered to Viber                                                                 |
| `6`   | `receiverNotSubscribed`        | The receiver is not subscribed to the account                                                           |
| `7`   | `publicAccountBlocked`         | The account is blocked                                                                                  |
| `8`   | `publicAccountNotFound`        | The account associated with the token is not a account.                                                 |
| `9`   | `publicAccountSuspended`       | The account is suspended                                                                                |
| `10`  | `webhookNotSet`                | No webhook was set for the account                                                                      |
| `11`  | `receiverNoSuitableDevice`     | The receiver is using a device or a Viber version that don’t support accounts                           |
| `12`  | `tooManyRequests`              | Rate control breach                                                                                     |
| `13`  | `apiVersionNotSupported`       | Maximum supported account version by all user’s devices is less than the `minApiVersion` in the message |
| `14`  | `incompatibleWithVersion`      | `minApiVersion` is not compatible to the message fields                                                 |
| `15`  | `publicAccountNotAuthorized`   | The account is not authorized                                                                           |
| `16`  | `inchatReplyMessageNotAllowed` | Inline message not allowed                                                                              |
| `17`  | `publicAccountIsNotInline`     | The account is not inline                                                                               |
| `18`  | `noPublicChat`                 | Failed to `post to public account`. The bot is missing a Public Chat interface                          |
| `19`  | `cannotSendBroadcast`          | Cannot send broadcast message                                                                           |
| `20`  | `broadcastNotAllowed`          | Attempt to send broadcast message from the bot                                                          |
| `21`  | `unsupportedCountry`           | The message sent is not supported in the destination country                                            |
| `22`  | `paymentUnsupported`           | The bot does not support payment messages                                                               |
| `23`  | `freeMessagesExceeded`         | The bot has reached the monthly threshold                                                               |
| `24`  | `noBalance`                    | No balance for a billable bot                                                                           |
| other | `General error`                | General error                                                                                           |

**Note:** Failing to send the authentication token in the header will result in an error with the `missing auth_token` message.

### Forbidden File Formats <a href="#forbidden-file-formats" id="forbidden-file-formats"></a>

| Extension | Format                                 | Operating system(s)    |
| --------- | -------------------------------------- | ---------------------- |
| ACTION    | Automator Action                       | Mac OS                 |
| APK       | Application                            | Android                |
| APP       | Executable                             | Mac OS                 |
| BAT       | Batch File                             | Windows                |
| BIN       | Binary Executable                      | Windows, Mac OS, Linux |
| CMD       | Command Script                         | Windows                |
| COM       | Command File                           | Windows                |
| COMMAND   | Terminal Command                       | Mac OS                 |
| CPL       | Control Panel Extension                | Windows                |
| CSH       | C Shell Script                         | Mac OS, Linux          |
| EXE       | Executable                             | Windows                |
| GADGET    | Windows Gadget                         | Windows                |
| INF1      | Setup Information File                 | Windows                |
| INS       | Internet Communication Settings        | Windows                |
| INX       | InstallShield Compiled Script          | Windows                |
| IPA       | Application                            | iOS                    |
| ISU       | InstallShield Uninstaller Script       | Windows                |
| JOB       | Windows Task Scheduler Job File        | Windows                |
| JSE       | JScript Encoded File                   | Windows                |
| KSH       | Unix Korn Shell Script                 | Linux                  |
| LNK       | File Shortcut                          | Windows                |
| MSC       | Microsoft Common Console Document      | Windows                |
| MSI       | Windows Installer Package              | Windows                |
| MSP       | Windows Installer Patch                | Windows                |
| MST       | Windows Installer Setup Transform File | Windows                |
| OSX       | Executable                             | Mac OS                 |
| OUT       | Executable                             | Linux                  |
| PAF       | Portable Application Installer File    | Windows                |
| PIF       | Program Information File               | Windows                |
| PRG       | Executable                             | GEM                    |
| PS1       | Windows PowerShell Cmdlet              | Windows                |
| REG       | Registry Data File                     | Windows                |
| RGS       | Registry Script                        | Windows                |
| RUN       | Executable                             | Linux                  |
| SCT       | Windows Scriptlet                      | Windows                |
| SHB       | Windows Document Shortcut              | Windows                |
| SHS       | Shell Scrap Object                     | Windows                |
| U3P       | U3 Smart Application                   | Windows                |
| VB        | VBScript File                          | Windows                |
| VBE       | VBScript Encoded Script                | Windows                |
| VBS       | VBScript File                          | Windows                |
| VBSCRIPT  | Visual Basic Script                    | Windows                |
| WORKFLOW  | Automator Workflow                     | Mac OS                 |
| WS        | Windows Script                         | Windows                |
| WSF       | Windows Script                         | Windows                |

### **Server Errors**

| 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                                           |

| 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                       |

<br>


# Viber templates API (beta)

DecisionTelecom Viber API allows you to send and receive Viber business messages to and from any country in the world via API. Each message is identified by a unique random ID, so users can always check the status of a message using given endpoint.

The Viber templates API uses HTTPS with access key that is used as the API authorization. Request and response payloads are formatted as JSON using UTF-8 encoding.

**API Authorization** - Base64 access key.

Please contact your account manager to get an API key.

## **Auth**

## Basic Auth

#### **Example**:

```
$userHashKey = 'User Hash Key provided by your account manager';
$ch = curl_init('https://web.it-decision.com/v2/api/create-template-api');
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);
```

## **Create transactional Viber template**

A Transactional Template is a standardized, pre-approved message format for notifications\
(e.g., order confirmations, shipping updates). It consists of:\
**Fixed Text**: Static content that remains constant.\
**Placeholders (Variables)**: Dynamic fields replaced with recipient-specific data at the\
time of sending.

Use this request to submit a new template. After creation, the template enters moderation\
queue. You must await the Approved status before use.

\
**Exceptions:**

* Max template length (excluding curly braces {{}}) - 1000 characters
* The number of Placeholders (Variables) cannot be more than 8
* The number of characters in a Placeholder (Variable) is no more than 125
* Placeholders (Variables) CANNOT BE at the beginning of the text or at the end of the text
* Placeholders (Variables) CANNOT BE URLs or links.

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

```
https://web.it-decision.com/v2/api/create-viber-template-api
```

{% endtab %}
{% endtabs %}

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

```json
Example for trasactional Viber template:
{
    "name":"Custom name",
    "template":"Dear {{John Doe}}, your {{john_doe}} account expires on {{September 18, 2026}}. Please renew your account using the link https://customsite.com/.",
    "callback_url":"https://customsite.com/templates-callback",
    "lang":"en"
}
```

{% endtab %}
{% endtabs %}

### **Parameters**

**name:** Mandatory, template name - cannot be more than 100 characters

**template**: Mandatory. Max template length (excluding curly braces {{}}) - 1000 characters.\
A message with example phrases in {{...}} structures that will differ when subsequently sent as transactional messages. When forming a transactional message, these phrases will be used for sending in accordance with the new transactional message types 1701 and 1702. \
For example, the transactional message sent for the template from the example above would be: \
*Dear Alex* Cossac&#x6B;*, your alex\_*&#x63;ossack *account expires on October 15*, \_2027. Please renew your account using the link <https://customsite.com/._\\>
Here *Alex* Cossack, *alex\_*&#x63;ossack, *October 15*, *2027* are phrases that can vary in transactional messages of this template.

**callback\_url**: Mandatory. The callback URL to which template approval statuses will be sent.

**lang:** Mandatory. Template language code (e.g., en, uk, fr). [Locales list](#localization)

### Response:

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

```json
{
    "success": true,
    "message": "Template successfully created",
    "data": {
        "example": "Dear John Doe, your john_doe account expires on September 18, 2026. Please renew your account using the link https://customsite.com/.",
        "template_text": "Dear {{var1}}, your {{var2}} account expires on {{var3}}. Please renew your account using the link https://customsite.com/.",
        "name": "Custom Name",
        "lang": "en",
        "status_template": "Pending Approval",
        "template_id": "36568982-d84c-42ce-9c72-8caf62cd8b05",
        "created_at": "2026-06-10 06:58:00",
        "id": 46
    }
}
```

{% endtab %}
{% endtabs %}

### **Values**:

**success:** true/false

**message**: message about success or failure of template creation

**data**: Object with information about the created template.\
**data.id**: Internal ID of the template in the database.\
**data.name**: Name of the template.\
**data.template\_id**: Unique template identifier for your Viber account.\
**data.template\_text**: Template text with Placeholders (Variables) names.\
**data.example**: Generated example message.\
**data.status\_template**: Current status of the template - **Pending Approval**, **Created**, **Approved**, **Rejected**.\
**data.created\_at**: (datetime) Date the template was created.\
**data.lang**: Template language.

### Receiving statuses at the specified callback\_url:

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

```json
{
    "template_id": "0aac888f-2ee2-4112-9659-1755a951966a",
    "status_template": "Approved"
}
```

{% endtab %}
{% endtabs %}

**template\_id:** ID received in the API response when creating the template.

**status\_template:** state of template , can be: **Pending Approval**, **Created**, **Approved**, **Rejected**.

## **Get Viber template data**

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

```
 https://web.it-decision.com/v2/api/get-viber-template-api
```

{% endtab %}
{% endtabs %}

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

```json
{
    "id":4291235
}
```

{% endtab %}
{% endtabs %}

### Parameters

**id:**

The Internal ID of the template whose status you want to get

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

```json
{
    "success": true,
    "message": "Template received successfully",
    "data": {
        "id": 4291235,
        "template_id": "36568982-d84c-42ce-9c72-8caf62cd8b05",
        "name": "Custom Name",
        "template_text": "Dear {{var1}}, your {{var2}} account expires on {{var3}}. Please renew your account using the link https://customsite.com/.",
        "example": "Dear John Doe, your john_doe account expires on September 18, 2026. Please renew your account using the link https://customsite.com/.",
        "status_template": "Approved",
        "created_at": "2026-06-10 06:58:00",
        "lang": "en"
    }
}
```

{% endtab %}
{% endtabs %}

### Values

**success:** true/false

**message**: message about success or failure of get template

**data**: Object with information about the created template.\
**data.id**: Internal ID of the template in the database.\
**data.name**: Name of the template.\
**data.template\_id**: Unique template identifier for your Viber account.\
**data.template\_text**: Template text with Placeholders (Variables) names.\
**data.example**: Generated example message.\
**data.status\_template**: Current status of the template - **Pending Approval**, **Created**, **Approved**, **Rejected**.\
**data.created\_at**: (datetime) Date the template was created.\
**data.lang**: Template language.

## **Localization**&#x20;

| Language              | Code (lang) |
| --------------------- | ----------- |
| Arabic                | ar          |
| Armenian              | hy          |
| Belarusian            | be          |
| Bosnian               | bs          |
| Bulgarian             | bg          |
| Burmese               | my          |
| Chinese (Simplified)  | zh-Hans     |
| Chinese (Traditional) | zh-Hant     |
| Croatian              | hr          |
| Czech                 | cs          |
| Danish                | da          |
| Dutch                 | nl          |
| English               | en          |
| Finnish               | fi          |
| French                | fr\_FR      |
| Georgian              | ka          |
| German                | de          |
| Greek                 | el          |
| Hebrew                | he          |
| Hungarian             | hu          |
| Indonesian            | id          |
| Italian               | it          |
| Japanese              | ja          |
| Nepali                | ne          |
| Norwegian             | no          |
| Persian               | fa          |
| Polish                | pl          |
| Portuguese (Brazil)   | pt\_BR      |
| Portuguese (Portugal) | pt\_PT      |
| Romanian              | ro          |
| Russian               | ru          |
| Serbian               | sr          |
| Slovak                | sk          |
| Slovenian             | sl          |
| Spanish               | es\_ES      |
| Swedish               | sv          |
| Thai                  | th          |
| Turkish               | tr          |
| Ukrainian             | uk          |
| Vietnamese            | vi          |

## **Errors**

| 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:

callback\_url is not url

callback\_url url wrong scheme

| Name    | Internal server error                                              |
| ------- | ------------------------------------------------------------------ |
| message | Error for template registration on Viber side: \<Viber side error> |
| code    | 1                                                                  |
| status  | 400                                                                |

| Name    | Message Template error                                                                   |
| ------- | ---------------------------------------------------------------------------------------- |
| message | Viber Business Account is not configured. Please contact your manager for clarification. |
| code    | 7                                                                                        |
| status  | 400                                                                                      |

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


# eSIM API

Provision, activate, and manage eSIMs and data packages using the DecisionTelecom eSIM API.

The eSIM API supports client creation, eSIM allocation, compatible package assignment, activation data retrieval, top-ups, usage monitoring, package removal, and release of eSIMs.

### API reference

| Section          | Contents                                                                          |
| ---------------- | --------------------------------------------------------------------------------- |
| Authentication   | Base URL and request headers.                                                     |
| Packages         | List Packages and client-specific catalog prices.                                 |
| eSIMs            | Inventory, assigned packages, identifiers, assignment, and management guides.     |
| Usage            | Package usage requests, field mappings, remaining data, and multiple assignments. |
| Statuses         | Catalog, allocation, assignment, and usage status context.                        |
| Integration Flow | Recommended catalog, provisioning, and usage synchronization sequence.            |

### Management guides

* **Provision an eSIM**: create a B2C client, select an available eSIM, find compatible packages, assign the eSIM and package, and retrieve activation data.
* **Top Up an eSIM**: add a package to an existing eSIM.
* **Remove a Package**: remove a package assignment.
* **Release an eSIM**: unassign an eSIM from its client.

Open the corresponding page from the eSIM API navigation.


# Authentication

Authenticate all requests using your client Bearer token.

### Base URL

```
https://esim-api.it-decision.com
```

Endpoint paths in this section include `/api/v1`.

### Request headers

| Header        | Value                                      |
| ------------- | ------------------------------------------ |
| Authorization | `Bearer <TOKEN>`                           |
| Accept        | `application/json`                         |
| Content-Type  | `application/json` for JSON request bodies |

```http
GET /api/v1/packages?page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

Replace `<TOKEN>` with your client token in your server-side integration. Keep tokens secret. Package prices returned for your client token are client-specific.


# Packages

Retrieve the catalog available to your client account. Prices returned for your client token are client-specific.

Use **List Packages** to synchronize the full catalog. Iterate through every page using the pagination metadata returned by the API.

Catalog availability (`package.start` / `package.end`) is separate from the validity of an assignment on an eSIM (`usageStartAt` / `usageExpireAt`).


# List Packages

Synchronize the package catalog available to your client account.

### Request

```http
GET /api/v1/packages?page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

| Query parameter | Description                                                |
| --------------- | ---------------------------------------------------------- |
| `page`          | Page number; start at 1.                                   |
| `perPage`       | Number of items requested per page; this example uses 100. |

Iterate through all pages using the pagination metadata returned by the API.

### Response

Simplified package item. The price shown is an illustrative client-specific price.

```json
{
  "id": "a0966054-2e2f-4e7f-aead-99817f365d1d",
  "code": "9153",
  "name": "Global 3GB 7 days",
  "price": 8.50,
  "dataLimit": 3,
  "limit": 7,
  "limitType": "day",
  "status": "live",
  "active": true
}
```

| Field                 | Description                                                                                                                   |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `id`                  | Package identifier used as `packageId`.                                                                                       |
| `code`                | Package catalog code.                                                                                                         |
| `name`                | Display name.                                                                                                                 |
| `price`               | Price specific to your client account.                                                                                        |
| `dataLimit`           | Total data allowance; 3 GB in this example.                                                                                   |
| `limit` / `limitType` | Package duration; 7 days in this example.                                                                                     |
| `status` / `active`   | Catalog status and availability flag.                                                                                         |
| `start` / `end`       | Product availability period in the catalog, when returned. These are not the validity dates of a package assigned to an eSIM. |

For assignment validity, use `usageStartAt` and `usageExpireAt`.


# eSIMs

Manage eSIM inventory and package assignments.

| Identifier      | Meaning                                                                                                                     |
| --------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `esimId`        | Internal eSIM identifier from `data[].id` in `GET /api/v1/esims`, or the response from `POST /api/v1/esims/assign-package`. |
| `iccid`         | eSIM card identifier. Store the mapping `ICCID -> esimId`.                                                                  |
| `packageId`     | Catalog package identifier.                                                                                                 |
| `packageEsimId` | Identifier of one package assignment: `packageEsims[].id`. Use it for package usage requests.                               |

An eSIM can have multiple package assignments. Keep each assignment ID and evaluate its status, queue position, and usage fields.


# List eSIMs

Retrieve eSIM inventory and store the identifiers needed for subsequent requests.

### Request

```http
GET /api/v1/esims?page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

To select unallocated inventory during provisioning:

```http
GET /api/v1/esims?allocated=false&page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

| Query parameter    | Description                                                          |
| ------------------ | -------------------------------------------------------------------- |
| `allocated`        | Use `false` for unallocated eSIMs or `true` for allocated eSIMs.     |
| `page` / `perPage` | Pagination controls. Iterate using the returned pagination metadata. |

### Response

Simplified response showing identifier fields only.

```json
{
  "data": [
    {
      "id": "f452f335-4845-4a44-bf4d-261943bf4081",
      "iccid": "<ICCID>"
    }
  ]
}
```

| Field          | Description                      |
| -------------- | -------------------------------- |
| `data[].id`    | Internal `esimId`.               |
| `data[].iccid` | ICCID associated with that eSIM. |

Store the mapping `ICCID -> esimId`. To retrieve package assignments and usage fields, use **Get eSIMs with Assigned Packages**.


# Get eSIMs with Assigned Packages

Retrieve allocated eSIMs together with their package assignments.

### Request

```http
GET /api/v1/esims?scopeBy=package&allocated=true&page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

| Query parameter    | Description                                                       |
| ------------------ | ----------------------------------------------------------------- |
| `scopeBy`          | Set to `package` to retrieve package assignments.                 |
| `allocated`        | Set to `true` to retrieve allocated eSIMs.                        |
| `page` / `perPage` | Iterate through all pages using the returned pagination metadata. |

### Response

Simplified eSIM item. The example omits activation data and uses an illustrative client-specific price.

```json
{
  "id": "f452f335-4845-4a44-bf4d-261943bf4081",
  "iccid": "<ICCID>",
  "packageEsims": [
    {
      "id": "e693b396-3507-4f32-8604-4352418ddc15",
      "status": "active",
      "usageStartAt": "2026-10-14T15:40:55.759Z",
      "usageExpireAt": "2026-10-21T15:40:55.759Z",
      "usageValue": "1.206621",
      "usageStatus": "In Use",
      "queuePosition": 1,
      "package": {
        "id": "a0966054-2e2f-4e7f-aead-99817f365d1d",
        "name": "Global 3GB 7 days",
        "price": 8.50,
        "dataLimit": 3,
        "limit": 7,
        "limitType": "day"
      }
    }
  ]
}
```

| Field                          | Description                                                            |
| ------------------------------ | ---------------------------------------------------------------------- |
| `id`                           | eSIM identifier (`esimId`); found at `data[].id` in the list response. |
| `iccid`                        | ICCID; store its mapping to `esimId`.                                  |
| `packageEsims[].id`            | Assignment identifier (`packageEsimId`).                               |
| `packageEsims[].package.id`    | Catalog package identifier.                                            |
| `packageEsims[].queuePosition` | Assignment queue position. Evaluate with status and usage fields.      |

**Important:** one eSIM may have multiple `packageEsims` entries. Do not assume `packageEsims[0]` is the only or current package. Use `status`, `queuePosition`, and usage fields to select the relevant assignment.

See **Usage Fields** for allowance, consumption, validity dates, and status mappings.


# Get eSIM ID

Use the internal `esimId` when an endpoint requires an eSIM identifier. An ICCID and an `esimId` identify the same eSIM in different ways; they are not interchangeable request values.

### Obtain esimId

| Source                                       | Value to store                                                      |
| -------------------------------------------- | ------------------------------------------------------------------- |
| `GET /api/v1/esims`                          | `data[].id`, together with the same item’s `data[].iccid`.          |
| `POST /api/v1/esims/assign-package` response | The assigned eSIM ID and ICCID returned by the assignment response. |

Store the mapping `ICCID -> esimId` when an eSIM is selected or assigned.

```json
{
  "iccid": "<ICCID>",
  "esimId": "f452f335-4845-4a44-bf4d-261943bf4081"
}
```

This is a suggested local storage record, not an API response schema.

### Obtain packageEsimId

Retrieve the eSIM with its assigned packages:

```http
GET /api/v1/esims?scopeBy=package&allocated=true&page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

Use `packageEsims[].id` as `packageEsimId`. This identifies one package assignment, not the catalog package or the eSIM itself. Store every relevant assignment ID alongside its `esimId` and ICCID.

Pass `packageEsimId` to `POST /api/v1/packages/usage`. If multiple assignments are returned, choose the relevant assignment using `status`, `queuePosition`, and usage fields.


# Assign Package

Assign a compatible package to an eSIM and keep the identifiers returned by the assignment operation.

### Before assignment

| Identifier  | How to obtain it                                                               |
| ----------- | ------------------------------------------------------------------------------ |
| `clientId`  | Create the B2C client as described in **Provision an eSIM**.                   |
| `esimId`    | Use `data[].id` from `GET /api/v1/esims`.                                      |
| `packageId` | Select a compatible package using the package lookup in **Provision an eSIM**. |

### Assignment operation

```http
POST /api/v1/esims/assign-package
Authorization: Bearer <TOKEN>
Content-Type: application/json
Accept: application/json
```

The assignment response returns the assigned eSIM ID and ICCID. Store the mapping `ICCID -> esimId`. The complete provisioning sequence is documented in **Provision an eSIM**.

### Retrieve the assignment identifier

After assignment, retrieve the allocated eSIMs with packages:

```http
GET /api/v1/esims?scopeBy=package&allocated=true&page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

Use the relevant `packageEsims[].id` as `packageEsimId`. Store it for usage monitoring. Assignment does not by itself establish the actual package activation date; use `usageStartAt` and `usageExpireAt` for validity on the eSIM.

For additional packages on an existing eSIM, see **Top Up an eSIM**. For usage selection when several assignments exist, see **Multiple Packages on One eSIM**.


# Release an eSIM

Unassign an eSIM from a client and make it available for future allocation.

Use this operation when an eSIM needs to be removed from the current client and returned to the pool of available eSIMs.

#### Request

PATCH /api/v1/esims/transfer

```
curl --location --request PATCH \
"https://esim-api.it-decision.com/api/v1/esims/transfer" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer <TOKEN>" \
--data '{
  "esims": [
    "<ESIM_ID>"
  ],
  "clientId": null
}'
```

#### Result

The eSIM is unassigned from the current client and becomes available for future allocation.

{% hint style="info" %}
Setting clientId to null releases the eSIM from the client without deleting the eSIM itself.
{% endhint %}


# Provision an eSIM

Step-by-step guide to create a client, allocate an eSIM, assign a data package, and retrieve the activation QR code.

Follow these steps to provision an eSIM for an end user. All credentials and identifiers below are placeholders.

### 1. Create a B2C Client

Create a client of type `b2c`. B2C clients do not have platform access and cannot create packages.

#### Request

```bash
curl --request POST "https://esim-api.it-decision.com/api/v1/clients" \
  --header "Authorization: Bearer <TOKEN>" \
  --form "name=My B2C Client" \
  --form "email=b2c-client@example.com" \
  --form "type=b2c" \
  --form "identifier=my_b2c_client_001" \
  --form "platformAccess=false" \
  --form "packageCreation=false"
```

#### Result

The response contains the new `clientId`. Save it for assignment.

### 2. Get an Available eSIM

Retrieve unallocated eSIMs.

#### Request

```http
GET /api/v1/esims?allocated=false
Authorization: Bearer <TOKEN>
Accept: application/json
```

#### Result

Select `data[].id` as `esimId` and store the mapping `ICCID -> esimId` using the same item’s `iccid`.

### 3. Find Compatible Packages

Retrieve packages compatible with the selected eSIM.

#### Request

```http
POST /api/v1/esims/find-packages
Authorization: Bearer <TOKEN>
Content-Type: application/json
Accept: application/json
```

```json
{
  "esims": ["<ESIM_ID>"]
}
```

#### Result

Select and save the required `packageId` from the compatible packages returned by the API.

### 4. Assign eSIM, Package, and Client

Assign the selected eSIM and compatible data package to the B2C client.

#### Request

```http
POST /api/v1/esims/assign-package
Authorization: Bearer <TOKEN>
Content-Type: application/json
Accept: application/json
```

```json
{
  "esims": ["<ESIM_ID>"],
  "packages": ["<PACKAGE_ID>"],
  "client": "<CLIENT_ID>"
}
```

| Body field | Description                              |
| ---------- | ---------------------------------------- |
| `esims`    | Selected eSIM identifiers.               |
| `packages` | Compatible package identifiers.          |
| `client`   | B2C client identifier created in step 1. |

#### Result

The eSIM becomes allocated to the client and the selected package is assigned. Save the eSIM ID and ICCID returned by the assignment response. For actual package activation and expiration, use `usageStartAt` and `usageExpireAt`.

Retrieve the eSIM with assigned packages and store `packageEsims[].id` as `packageEsimId` for usage monitoring.

### 5. Retrieve the QR Code

Retrieve activation data for the allocated eSIM.

#### Request

```http
GET /api/v1/esims?allocated=true&ids=<ESIM_ID>
Authorization: Bearer <TOKEN>
Accept: application/json
```

#### Result

The response returns the QR code or activation data. Provide it securely to the intended end user so they can install and activate the eSIM. Do not include actual activation data in public examples.


# Top Up an eSIM

### Overview

An existing eSIM can have multiple packages assigned simultaneously. This allows customers to purchase additional data without replacing or reinstalling the eSIM profile.

### 1. Find Compatible Packages

Retrieve available packages for the existing eSIM.

#### Request

POST /api/v1/esims/find-packages

```
curl --location "https://esim-api.it-decision.com/api/v1/esims/find-packages" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer <TOKEN>" \
--data '{
  "esims": [
    "<ESIM_ID>"
  ]
}'
```

#### Result

The response returns a list of compatible packages available for the selected eSIM. Select the desired packageId.

### 2. Assign the New Package

Assign the selected package to the existing eSIM.

#### Request

POST /api/v1/esims/add-esims

```
curl --location "https://esim-api.it-decision.com/api/v1/esims/add-esims" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer <TOKEN>" \
--data '{
  "esims": [
    "<ESIM_ID>"
  ],
  "packages": [
    "<PACKAGE_ID>"
  ],
  "client": "<CLIENT_ID>"
}'
```

#### Response

204 No Content

#### Result

The new package is associated with the existing eSIM.

{% hint style="info" %}
No new eSIM profile or QR code is required. The customer continues using the same installed eSIM, and additional connectivity becomes available according to the assigned package rules.
{% endhint %}


# Remove a Package

Remove a data package from an existing eSIM without deleting the eSIM itself.

Use this operation when a package expires, needs to be replaced, was assigned incorrectly, or a subscription is cancelled.

#### Request

DELETE /api/v1/esims/remove-packages

```
curl --location --request DELETE \
"https://esim-api.it-decision.com/api/v1/esims/remove-packages" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer <TOKEN>" \
--data '{
  "packageEsimIds": [
    "<PACKAGE_ESIM_ID>"
  ]
}'
```

#### Recommended Method

Use packageEsimIds when you want to remove a specific package-to-eSIM association.

#### Alternative Methods

* `combinations` — Remove specific `esimId` + `packageId` pairs.
* `esims + packages` — Remove all matching combinations between the provided eSIMs and packages.

#### Result

Only the package-to-eSIM association is removed.

{% hint style="info" %}
The eSIM is not deleted, the package is not deleted, and other packages assigned to the same eSIM are not affected.
{% endhint %}

The eSIM loses access only to the data allowance provided by the removed package.


# Usage

Monitor data allowance, consumption, remaining data, validity dates, and status for each package assigned to an eSIM.

The eSIM list with `scopeBy=package&allocated=true` includes assignment usage fields. For the latest details of a specific assignment, call `POST /api/v1/packages/usage` using `packageEsims[].id` as `packageEsimId`.

| Page                          | Purpose                                                     |
| ----------------------------- | ----------------------------------------------------------- |
| Get Package Usage             | Request usage for one assignment.                           |
| Usage Fields                  | Map allowance, consumption, dates, and status fields.       |
| Remaining Data                | Calculate the unused allowance in consistent units.         |
| Multiple Packages on One eSIM | Select the relevant assignment when several packages exist. |

Usage is near real-time. Mobile-network reporting may introduce a short delay after the latest data session.


# Get Package Usage

Request the latest usage details for one package assigned to an eSIM.

### Request

```http
POST /api/v1/packages/usage
Authorization: Bearer <TOKEN>
Content-Type: application/json
Accept: application/json
```

```json
{
  "packageEsimId": "e693b396-3507-4f32-8604-4352418ddc15"
}
```

| Body field      | Description                                                                                                       |
| --------------- | ----------------------------------------------------------------------------------------------------------------- |
| `packageEsimId` | ID of the package-to-eSIM assignment. Obtain it from `packageEsims[].id` in the eSIM list with assigned packages. |

### Response

Simplified usage response:

```json
{
  "success": true,
  "errmsg": "",
  "package": {
    "package_status": "In Use",
    "status": "active",
    "rate_groups": [
      {
        "rate_group_allowance": 3,
        "rate_group_allow_qtyp": "GB",
        "rate_group_usage": 1.206621,
        "rate_group_starttime": "2026-10-14 15:40:55",
        "rate_group_expire": "2026-10-21 15:40:55",
        "rate_group_days_used": 5
      }
    ]
  }
}
```

| Response field                                | Description                                                   |
| --------------------------------------------- | ------------------------------------------------------------- |
| `success`                                     | Whether the usage request succeeded.                          |
| `errmsg`                                      | Error message when returned.                                  |
| `package.package_status`                      | Package usage status; `In Use` in this example.               |
| `package.status`                              | Technical assignment status; `active` in this example.        |
| `package.rate_groups[].rate_group_allowance`  | Total data allowance for the rate group.                      |
| `package.rate_groups[].rate_group_allow_qtyp` | Data unit; `GB` in this example.                              |
| `package.rate_groups[].rate_group_usage`      | Used data in the rate group’s unit.                           |
| `package.rate_groups[].rate_group_starttime`  | Package activation date and time reported for the rate group. |
| `package.rate_groups[].rate_group_expire`     | Package expiration date and time reported for the rate group. |
| `package.rate_groups[].rate_group_days_used`  | Number of usage days reported for the rate group.             |

### Remaining traffic

```
remaining = rate_group_allowance - rate_group_usage
3 - 1.206621 = 1.793379 GB
```

Calculate per relevant rate group and preserve its unit. Do not combine different units without conversion.

**Reporting delay:** usage is near real-time and may have a short mobile-network reporting delay.


# Usage Fields

The fields below belong to each `packageEsims[]` assignment returned by the eSIM list with assigned packages.

| Information                 | API field or calculation         | Example                    |
| --------------------------- | -------------------------------- | -------------------------- |
| Total data allowance        | `package.dataLimit`              | 3 GB                       |
| Used data                   | `usageValue`                     | 1.206621 GB                |
| Remaining data              | `package.dataLimit - usageValue` | 1.793379 GB                |
| Package activation date     | `usageStartAt`                   | `2026-10-14T15:40:55.759Z` |
| Package expiration date     | `usageExpireAt`                  | `2026-10-21T15:40:55.759Z` |
| Usage status                | `usageStatus`                    | `In Use`                   |
| Technical assignment status | `status`                         | `active`                   |
| Assignment identifier       | `id` within `packageEsims[]`     | Use as `packageEsimId`.    |
| eSIM identifier             | Parent eSIM `id` and `iccid`     | Store `ICCID -> esimId`.   |

`usageValue` may be returned as a numeric string. Convert it to a numeric value before calculating remaining data, and use the same data unit as the allowance.

### Catalog dates and assignment validity

| Fields                           | Meaning                                                      |
| -------------------------------- | ------------------------------------------------------------ |
| `package.start` / `package.end`  | Product availability period in the catalog.                  |
| `usageStartAt` / `usageExpireAt` | Actual validity period of the package on this specific eSIM. |

Do not use catalog availability dates as the activation or expiration dates of an assigned package. If a usage date is not yet available, keep it unavailable rather than substituting a catalog date.

For the dedicated endpoint’s `rate_group_*` fields, see **Get Package Usage**. Usage is near real-time and may have a short mobile-network reporting delay.


# Remaining Data

Calculate the remaining data allowance for the relevant package assignment.

### From eSIM assignment fields

```
remainingData = package.dataLimit - usageValue
```

| Value                                 | Example     |
| ------------------------------------- | ----------- |
| Total allowance (`package.dataLimit`) | 3 GB        |
| Used data (`usageValue`)              | 1.206621 GB |
| Remaining data                        | 1.793379 GB |

Convert numeric strings such as `usageValue` to numbers before subtraction. Use consistent units for both values.

### From the dedicated usage endpoint

```
remainingTraffic = rate_group_allowance - rate_group_usage
3 - 1.206621 = 1.793379 GB
```

Read the unit from `rate_group_allow_qtyp`. Calculate per relevant rate group; do not add or subtract values in different units without conversion.

Remaining data alone does not establish whether a package can be used. Check the assignment status, usage status, activation date, and expiration date.

Usage is near real-time and may have a short mobile-network reporting delay. When several packages are assigned to an eSIM, calculate the balance for each relevant assignment instead of assuming the first array entry is current.


# Multiple Packages on One eSIM

One eSIM may contain multiple `packageEsims` entries. Each entry is a separate package-to-eSIM assignment with its own ID, status, usage, and validity dates.

**Do not assume `packageEsims[0]` is always the only or current package.**

| Field                              | How to use it                                                                         |
| ---------------------------------- | ------------------------------------------------------------------------------------- |
| `packageEsims[].id`                | Identify the exact assignment and use it as `packageEsimId` for usage requests.       |
| `status`                           | Inspect the technical assignment status.                                              |
| `queuePosition`                    | Inspect the assignment’s position in the queue together with status and usage fields. |
| `usageStatus`                      | Inspect the reported usage state.                                                     |
| `usageStartAt` / `usageExpireAt`   | Determine the actual validity period for this assignment.                             |
| `usageValue` / `package.dataLimit` | Display used and remaining allowance for this assignment.                             |

### Recommended handling

1. Retrieve all pages of allocated eSIMs with package assignments.
2. Store each `packageEsims[].id` with the parent `esimId` and ICCID.
3. Evaluate `status`, `queuePosition`, usage status, and validity dates for each assignment.
4. Select the assignment relevant to the customer’s package, or display multiple relevant assignments separately.
5. Call `POST /api/v1/packages/usage` with that assignment’s `packageEsimId` when fresh usage is needed.

Do not infer assignment relevance from array order alone. Do not merge balances from different assignments unless your application explicitly presents such a total and handles units and validity correctly.

See **Top Up an eSIM** for assigning additional packages without replacing the installed eSIM profile.


# Statuses

Interpret status fields in their own context. Catalog availability, eSIM allocation, technical assignment status, and usage state describe different aspects of the service.

| Context                  | Field                        | Meaning                                       | Example          |
| ------------------------ | ---------------------------- | --------------------------------------------- | ---------------- |
| Package catalog          | `status`                     | Product status in the catalog.                | `live`           |
| Package catalog          | `active`                     | Product availability flag.                    | `true`           |
| eSIM listing             | `allocated` query filter     | Selects allocated or unallocated inventory.   | `true` / `false` |
| Package assignment       | `packageEsims[].status`      | Technical status of the package assignment.   | `active`         |
| Package assignment       | `packageEsims[].usageStatus` | Reported usage state of the assigned package. | `In Use`         |
| Dedicated usage response | `package.status`             | Technical assignment status.                  | `active`         |
| Dedicated usage response | `package.package_status`     | Reported package usage state.                 | `In Use`         |

These are example values, not an exhaustive list of status enums. Preserve returned values and handle unfamiliar values safely in your integration.

A technical assignment status such as `active` does not replace the usage state or validity dates. Evaluate status together with `usageStartAt`, `usageExpireAt`, `usageValue`, and `queuePosition` when selecting the relevant assignment.

Use `usageStatus` or `package_status` for the reported usage state. Do not present the catalog status or assignment status as if it were the eSIM’s mobile-network registration state.


# Integration Flow

Use this sequence to synchronize the catalog, provision eSIMs, and monitor each package assignment.

### Catalog synchronization

```http
GET /api/v1/packages?page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

Iterate through all pages using the returned pagination metadata. Store the catalog identifiers, allowance, duration, availability, coverage when returned, and your client-specific prices.

### Provisioning

Follow **Provision an eSIM** to create a B2C client, select unallocated inventory, find compatible packages, assign the package, and retrieve activation data for the end user. Store `ICCID -> esimId` when selecting or assigning the eSIM.

The `POST /api/v1/esims/assign-package` response also provides the assigned eSIM ID and ICCID.

### Assignment synchronization

```http
GET /api/v1/esims?scopeBy=package&allocated=true&page=1&perPage=100
Authorization: Bearer <TOKEN>
Accept: application/json
```

Iterate through all pages. For every assignment, store the parent ICCID, `esimId`, and `packageEsimId` from `packageEsims[].id`. Keep multiple assignments per eSIM rather than replacing them with the first array entry.

### Customer usage display

Display total allowance, used data, remaining data, activation date, expiration date, and usage and technical assignment statuses. Use the mappings in **Usage Fields**.

For actual validity on an eSIM, use `usageStartAt` / `usageExpireAt`. Catalog `package.start` / `package.end` describe product availability.

### Refresh usage

```http
POST /api/v1/packages/usage
Authorization: Bearer <TOKEN>
Content-Type: application/json
Accept: application/json
```

```json
{
  "packageEsimId": "e693b396-3507-4f32-8604-4352418ddc15"
}
```

Select the relevant assignment using its ID, `status`, `queuePosition`, and usage fields. Calculate remaining traffic as `rate_group_allowance - rate_group_usage` in the reported unit. Usage is near real-time and may have a short mobile-network reporting delay.

### Ongoing management

Use **Top Up an eSIM** for additional packages, **Remove a Package** to remove a specific assignment, and **Release an eSIM** to unassign the eSIM from its client. Keep activation data and credentials private.


