# WhatsApp Business API

DecisionTelecom WhatsApp API le permite enviar y recibir mensajes comerciales de WhatsApp hacia y desde cualquier país del mundo a través de API. Cada mensaje se identifica mediante una identificación aleatoria única, por lo que los usuarios siempre pueden verificar el estado de un mensaje utilizando un punto final determinado.

La API de WhatsApp usa HTTPS con clave de acceso que se usa como autorización de la API. Las cargas útiles de solicitud y respuesta se formatean como JSON mediante la codificación UTF-8.

**Autorización API:** clave de acceso Base64.

Póngase en contacto con su administrador de cuenta para obtener una clave API.

## Auth

## Basic Auth

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

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

{% endtab %}
{% endtabs %}

## API Send WhatsApp message

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

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

{% endtab %}
{% endtabs %}

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

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

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

          // OR

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

{% endtab %}
{% endtabs %}

**source\_addr:**

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

**destination\_addr:**

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

**message\_type:**

&#x20;           Type of message to be sent:

&#x20;           1 text message

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

&#x20;           4 message based on registered template

**text:**

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

**file\_url:**

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

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

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

**callback\_url:**

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

**template\_name:**

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

**template\_params:**

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

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

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

{% endtab %}
{% endtabs %}

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

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

{% endtab %}
{% endtabs %}

**message\_id:**

Sent message ID

## API Receive WhatsApp message:

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

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

{% endtab %}
{% endtabs %}

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

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

{% endtab %}
{% endtabs %}

**message\_id:**

The ID of the message whose status you want to get

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

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

{% endtab %}
{% endtabs %}

**message\_id:**

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

**status:**

Current WhatsApp message status

## WhatsApp messages statuses

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

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

## Ejemplos Enviar mensaje de WhatsApp:

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

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

{% endtab %}

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

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

{% endtab %}

{% tab title="GO" %}

```
package main

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

func main() {

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

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

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

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

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

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

{% endtab %}

{% tab title="Java OkHttp" %}

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

{% endtab %}

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

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

{% endtab %}

{% tab title="PHP" %}

```
$curl = curl_init();

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

$response = curl_exec($curl);

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

{% endtab %}

{% tab title="NodJs" %}

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

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

{% endtab %}

{% tab title="Python" %}

```
import http.client
import json

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

{% endtab %}
{% endtabs %}
