Intelligent Messaging API
Cuándo elegir IM API
Elija IM API cuando una solicitud deba gestionar la entrega a través de varios canales con reglas de fallback; por ejemplo, intentar primero por WhatsApp y luego por SMS. Elija una API de un solo canal cuando su integración solo necesite enviar mensajes por un canal conocido.
Descripción general
Intelligent Messaging API de Modica ofrece fallback automático a canales de entrega alternativos (SMS, WhatsApp, email, etc.).
El fallback puede activarse por un evento específico (y un timeout).
Ejemplo: usar SMS como fallback si el mensaje de WhatsApp no se entrega en un plazo de 10 segundos.
Qué puede hacer la API
- Enviar una solicitud de mensaje al endpoint Intelligent Messaging
- Entregar el mensaje por el canal SMS predeterminado cuando no se especifiquen intentos de entrega
- Intentar hasta 10 canales en orden, como WhatsApp Business, luego SMS y después email
- Activar el fallback según eventos de entrega y valores de timeout de hasta 7 días
- Enviar mensajes de texto o mensajes con templates predefinidos
- Enviar email con un asunto y una opción de charset
- Aplicar un sender mask
- Definir un tiempo de expiración después del cual el mensaje ya no se entrega
- Adjuntar su propia referencia, que se devuelve en los status callbacks
- Recibir status callbacks del mensaje y de cada intento de entrega
- Incluir un correlation ID para que su aplicación pueda rastrear las solicitudes de extremo a extremo
Cómo funciona
En la práctica, la API sigue un flujo de trabajo sencillo:
- Autentíquese con sus credenciales de IM API.
- Envíe una solicitud de mensaje a
/message. - Incluya el destino, el cuerpo del mensaje o el template, y los intentos de entrega opcionales.
- Si se especifican intentos de entrega, la API prueba cada canal en orden.
- Si no se alcanza un evento configurado dentro del timeout, la API usa el siguiente canal como fallback.
Cuándo usar IM API
Use IM API cuando su aplicación necesite orquestar canales en lugar de seguir un flujo fijo que use solo SMS o solo WhatsApp. Es útil para notificaciones a clientes en las que se prefiera WhatsApp, pero se deba usar SMS si el mensaje de WhatsApp no se recibe o no se lee dentro de un plazo definido.
Si su aplicación siempre envía mensajes por un solo canal, use directamente la API de ese canal. Para flujos que solo usan SMS, consulte REST v2 o REST v1. Para flujos que solo usan WhatsApp, consulte WhatsApp for Business API.
Antes de empezar
Antes de realizar su primera solicitud, confirme lo siguiente:
- Se aprovisionó su aplicación de IM API.
- Tiene el nombre de la aplicación y la contraseña para HTTP Basic Authentication.
- La dirección IP de su servidor de envío está autorizada si se habilitó el IP allowlisting.
- El número móvil del destinatario está en formato internacional.
- Los templates de WhatsApp que se utilicen en los mensajes con templates ya están configurados y aprobados.
- Si envía mensajes por email, se configuró la dirección de email del remitente para su aplicación.
- Si desea recibir actualizaciones de entrega, se configuró la URL de status callback.
Ruta de la primera solicitud exitosa
En la mayoría de las implementaciones, la forma más rápida de validar la conectividad y la configuración es:
- Autenticarse con sus credenciales de IM API.
- Enviar una solicitud POST sencilla a
/messagecon un destino móvil y un cuerpo de texto. - Confirmar la respuesta
202y guardar el ID de mensaje devuelto. - Añadir intentos de entrega después de que la solicitud SMS sencilla se realice correctamente.
- Probar la ruta de fallback enviando primero un intento por WhatsApp Business y luego por SMS.
Autenticación
Se usa HTTP Basic Authentication para todas las solicitudes. Si accede a la API sin las credenciales correctas o sin permiso para acceder a la API, recibirá una respuesta HTTP 401.
Las credenciales de su aplicación gateway (nombre de la aplicación y contraseña) están disponibles en la página de configuración de IM API en Modica.
Necesitará una cuenta de usuario y una contraseña para obtenerlas.
Si no tiene estos datos, contacte a support@modicagroup.com.
Direcciones IP autorizadas
Puede añadir las IP o los rangos de IP de sus servidores mediante el botón “Add IP Address”, debajo de “Authorised IP Addresses”.
Tenga en cuenta que, una vez que se añada una o más direcciones IP o rangos de IP, se rechazarán las conexiones desde cualquier otra dirección IP. Cualquier intento desde una IP que no esté en la lista recibirá un error de autenticación.
URI base
Todo acceso a la API se realiza mediante HTTPS y utiliza la siguiente dirección:
https://api.modicagroup.com/rest/im/v1
Versiones
La versión actual de IM API es v1.
Especificación OpenAPI
Esta API se desarrolló de acuerdo con la especificación OpenAPI definida aquí.
La especificación OpenAPI (Swagger) se encuentra aquí: aquí.
Aquí puede ver ejemplos de código y más información.
Envío de mensajes inteligentes
Puede enviar un mensaje IM a los siguientes endpoints con la utilidad cURL.
Enviar un mensaje IM sencillo como SMS
curl -X POST 'https://api.modicagroup.com/rest/im/v1/message' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic <TOKEN>' \
-d '{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "text",
"text": {
"body": "Contenido de mi SMS"
}
}
}'
const response = await fetch("https://api.modicagroup.com/rest/im/v1/message", {
method: "POST",
headers: {
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json"
},
body: JSON.stringify({
destination: {
mobile: "+64272383189"
},
message: {
type: "text",
text: {
body: "Contenido de mi SMS"
}
}
})
});
const result = await response.json();import requests
response = requests.post(
"https://api.modicagroup.com/rest/im/v1/message",
headers={
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json",
},
json={
"destination": {
"mobile": "+64272383189",
},
"message": {
"type": "text",
"text": {
"body": "Contenido de mi SMS",
},
},
},
)
result = response.json()<?php
$payload = json_encode([
"destination" => [
"mobile" => "+64272383189"
],
"message" => [
"type" => "text",
"text" => [
"body" => "Contenido de mi SMS"
]
]
]);
$ch = curl_init("https://api.modicagroup.com/rest/im/v1/message");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic <TOKEN>",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
require "json"
require "net/http"
require "uri"
uri = URI("https://api.modicagroup.com/rest/im/v1/message")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Basic <TOKEN>"
request["Content-Type"] = "application/json"
request.body = {
destination: {
mobile: "+64272383189"
},
message: {
type: "text",
text: {
body: "Contenido de mi SMS"
}
}
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
endimport java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String payload = """
{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "text",
"text": {
"body": "Contenido de mi SMS"
}
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.modicagroup.com/rest/im/v1/message"))
.header("Authorization", "Basic <TOKEN>")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());using System.Text;
using var client = new HttpClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"https://api.modicagroup.com/rest/im/v1/message");
request.Headers.TryAddWithoutValidation("Authorization", "Basic <TOKEN>");
request.Content = new StringContent(
"""{"destination":{"mobile":"+64272383189"},"message":{"type":"text","text":{"body":"Contenido de mi SMS"}}}""",
Encoding.UTF8,
"application/json");
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();Nota: si no se proporciona el campo delivery_attempts, el canal de entrega predeterminado será sms.
Respuesta 202:
{
"id": "b95fc11e-37f0-4770-a082-6ea22d4c4d12"
}
El id identifica el mensaje en cada status callback. Consulte Errores para las solicitudes fallidas.
Enviar un mensaje IM sencillo como WAB con fallback a SMS después de 10 segundos
curl -X POST 'https://api.modicagroup.com/rest/im/v1/message' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic <TOKEN>' \
-d '{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "text",
"text": {
"body": "Prueba"
}
},
"delivery_attempts": [
{
"channel": "wab",
"event": "received",
"timeout": 10
},
{
"channel": "sms"
}
]
}'
const response = await fetch("https://api.modicagroup.com/rest/im/v1/message", {
method: "POST",
headers: {
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json"
},
body: JSON.stringify({
destination: {
mobile: "+64272383189"
},
message: {
type: "text",
text: {
body: "Prueba"
}
},
delivery_attempts: [
{
channel: "wab",
event: "received",
timeout: 10
},
{
channel: "sms"
}
]
})
});
const result = await response.json();import requests
response = requests.post(
"https://api.modicagroup.com/rest/im/v1/message",
headers={
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json",
},
json={
"destination": {
"mobile": "+64272383189",
},
"message": {
"type": "text",
"text": {
"body": "Prueba",
},
},
"delivery_attempts": [
{
"channel": "wab",
"event": "received",
"timeout": 10,
},
{
"channel": "sms",
},
],
},
)
result = response.json()<?php
$payload = json_encode([
"destination" => [
"mobile" => "+64272383189"
],
"message" => [
"type" => "text",
"text" => [
"body" => "Prueba"
]
],
"delivery_attempts" => [
[
"channel" => "wab",
"event" => "received",
"timeout" => 10
],
[
"channel" => "sms"
]
]
]);
$ch = curl_init("https://api.modicagroup.com/rest/im/v1/message");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic <TOKEN>",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
require "json"
require "net/http"
require "uri"
uri = URI("https://api.modicagroup.com/rest/im/v1/message")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Basic <TOKEN>"
request["Content-Type"] = "application/json"
request.body = {
destination: {
mobile: "+64272383189"
},
message: {
type: "text",
text: {
body: "Prueba"
}
},
delivery_attempts: [
{
channel: "wab",
event: "received",
timeout: 10
},
{
channel: "sms"
}
]
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
endimport java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String payload = """
{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "text",
"text": {
"body": "Prueba"
}
},
"delivery_attempts": [
{
"channel": "wab",
"event": "received",
"timeout": 10
},
{
"channel": "sms"
}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.modicagroup.com/rest/im/v1/message"))
.header("Authorization", "Basic <TOKEN>")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());using System.Text;
using var client = new HttpClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"https://api.modicagroup.com/rest/im/v1/message");
request.Headers.TryAddWithoutValidation("Authorization", "Basic <TOKEN>");
request.Content = new StringContent(
"""{"destination":{"mobile":"+64272383189"},"message":{"type":"text","text":{"body":"Prueba"}},"delivery_attempts":[{"channel":"wab","event":"received","timeout":10},{"channel":"sms"}]}""",
Encoding.UTF8,
"application/json");
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();Nota: el evento received significa que el destinatario recibió el mensaje.
Enviar un mensaje IM con un template predefinido
curl -X POST 'https://api.modicagroup.com/rest/im/v1/message' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic <TOKEN>' \
-H 'X-Correlation-Id: f55c5554-87ed-4bde-8991-a2f4a1aa89fb' \
-d '{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "template",
"template": {
"template_id": "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
"language": "es",
"parameters": [
{
"name": "reference",
"text": "AZXSNIJN"
}
]
}
},
"delivery_attempts": [
{
"channel": "wab",
"event": "read",
"timeout": 10
},
{
"channel": "sms"
}
]
}'
const response = await fetch("https://api.modicagroup.com/rest/im/v1/message", {
method: "POST",
headers: {
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json",
"X-Correlation-Id": "f55c5554-87ed-4bde-8991-a2f4a1aa89fb"
},
body: JSON.stringify({
destination: {
mobile: "+64272383189"
},
message: {
type: "template",
template: {
template_id: "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
language: "es",
parameters: [
{
name: "reference",
text: "AZXSNIJN"
}
]
}
},
delivery_attempts: [
{
channel: "wab",
event: "read",
timeout: 10
},
{
channel: "sms"
}
]
})
});
const result = await response.json();import requests
response = requests.post(
"https://api.modicagroup.com/rest/im/v1/message",
headers={
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json",
"X-Correlation-Id": "f55c5554-87ed-4bde-8991-a2f4a1aa89fb",
},
json={
"destination": {
"mobile": "+64272383189",
},
"message": {
"type": "template",
"template": {
"template_id": "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
"language": "es",
"parameters": [
{
"name": "reference",
"text": "AZXSNIJN",
},
],
},
},
"delivery_attempts": [
{
"channel": "wab",
"event": "read",
"timeout": 10,
},
{
"channel": "sms",
},
],
},
)
result = response.json()<?php
$payload = json_encode([
"destination" => [
"mobile" => "+64272383189"
],
"message" => [
"type" => "template",
"template" => [
"template_id" => "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
"language" => "es",
"parameters" => [
[
"name" => "reference",
"text" => "AZXSNIJN"
]
]
]
],
"delivery_attempts" => [
[
"channel" => "wab",
"event" => "read",
"timeout" => 10
],
[
"channel" => "sms"
]
]
]);
$ch = curl_init("https://api.modicagroup.com/rest/im/v1/message");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic <TOKEN>",
"Content-Type: application/json",
"X-Correlation-Id: f55c5554-87ed-4bde-8991-a2f4a1aa89fb"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
require "json"
require "net/http"
require "uri"
uri = URI("https://api.modicagroup.com/rest/im/v1/message")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Basic <TOKEN>"
request["Content-Type"] = "application/json"
request["X-Correlation-Id"] = "f55c5554-87ed-4bde-8991-a2f4a1aa89fb"
request.body = {
destination: {
mobile: "+64272383189"
},
message: {
type: "template",
template: {
template_id: "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
language: "es",
parameters: [
{
name: "reference",
text: "AZXSNIJN"
}
]
}
},
delivery_attempts: [
{
channel: "wab",
event: "read",
timeout: 10
},
{
channel: "sms"
}
]
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
endimport java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String payload = """
{
"destination": {
"mobile": "+64272383189"
},
"message": {
"type": "template",
"template": {
"template_id": "bdff32db-1fd8-4270-99af-1f00c8ffdb3c",
"language": "es",
"parameters": [
{
"name": "reference",
"text": "AZXSNIJN"
}
]
}
},
"delivery_attempts": [
{
"channel": "wab",
"event": "read",
"timeout": 10
},
{
"channel": "sms"
}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.modicagroup.com/rest/im/v1/message"))
.header("Authorization", "Basic <TOKEN>")
.header("Content-Type", "application/json")
.header("X-Correlation-Id", "f55c5554-87ed-4bde-8991-a2f4a1aa89fb")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());using System.Text;
using var client = new HttpClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"https://api.modicagroup.com/rest/im/v1/message");
request.Headers.TryAddWithoutValidation("Authorization", "Basic <TOKEN>");
request.Headers.Add("X-Correlation-Id", "f55c5554-87ed-4bde-8991-a2f4a1aa89fb");
request.Content = new StringContent(
"""{"destination":{"mobile":"+64272383189"},"message":{"type":"template","template":{"template_id":"bdff32db-1fd8-4270-99af-1f00c8ffdb3c","language":"es","parameters":[{"name":"reference","text":"AZXSNIJN"}]}},"delivery_attempts":[{"channel":"wab","event":"read","timeout":10},{"channel":"sms"}]}""",
Encoding.UTF8,
"application/json");
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();Nota: el template bdff32db-1fd8-4270-99af-1f00c8ffdb3c acepta un parámetro llamado reference que, en este mensaje, se reemplazará por el valor AZXSNIJN.
Enviar por WhatsApp, SMS y email
Este ejemplo intenta primero por WhatsApp Business, luego por SMS y después por email. Añade un asunto al email y su propia referencia. También define un tiempo de expiración, después del cual no se realizan más intentos.
curl -X POST 'https://api.modicagroup.com/rest/im/v1/message' \
-H 'Content-Type: application/json' \
-H 'Authorization: Basic <TOKEN>' \
-d '{
"destination": {
"mobile": "+64272383189",
"email": "jane.citizen@example.com"
},
"message": {
"type": "text",
"text": {
"subject": "Su pedido ha sido enviado",
"body": "Su pedido 10452 ha sido enviado y llegará el viernes."
}
},
"delivery_attempts": [
{ "channel": "wab", "event": "read", "timeout": 3600 },
{ "channel": "sms", "event": "received", "timeout": 3600 },
{ "channel": "email" }
],
"reference": "order-10452",
"expires": "2026-11-05T10:00:00+13:00"
}'
const response = await fetch("https://api.modicagroup.com/rest/im/v1/message", {
method: "POST",
headers: {
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json"
},
body: JSON.stringify({
destination: {
mobile: "+64272383189",
email: "jane.citizen@example.com"
},
message: {
type: "text",
text: {
subject: "Su pedido ha sido enviado",
body: "Su pedido 10452 ha sido enviado y llegará el viernes."
}
},
delivery_attempts: [
{ channel: "wab", event: "read", timeout: 3600 },
{ channel: "sms", event: "received", timeout: 3600 },
{ channel: "email" }
],
reference: "order-10452",
expires: "2026-11-05T10:00:00+13:00"
})
});
const result = await response.json();import requests
response = requests.post(
"https://api.modicagroup.com/rest/im/v1/message",
headers={
"Authorization": "Basic <TOKEN>",
"Content-Type": "application/json",
},
json={
"destination": {
"mobile": "+64272383189",
"email": "jane.citizen@example.com",
},
"message": {
"type": "text",
"text": {
"subject": "Su pedido ha sido enviado",
"body": "Su pedido 10452 ha sido enviado y llegará el viernes.",
},
},
"delivery_attempts": [
{"channel": "wab", "event": "read", "timeout": 3600},
{"channel": "sms", "event": "received", "timeout": 3600},
{"channel": "email"},
],
"reference": "order-10452",
"expires": "2026-11-05T10:00:00+13:00",
},
)
result = response.json()<?php
$payload = json_encode([
"destination" => [
"mobile" => "+64272383189",
"email" => "jane.citizen@example.com"
],
"message" => [
"type" => "text",
"text" => [
"subject" => "Su pedido ha sido enviado",
"body" => "Su pedido 10452 ha sido enviado y llegará el viernes."
]
],
"delivery_attempts" => [
["channel" => "wab", "event" => "read", "timeout" => 3600],
["channel" => "sms", "event" => "received", "timeout" => 3600],
["channel" => "email"]
],
"reference" => "order-10452",
"expires" => "2026-11-05T10:00:00+13:00"
]);
$ch = curl_init("https://api.modicagroup.com/rest/im/v1/message");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Basic <TOKEN>",
"Content-Type: application/json"
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
?>
require "json"
require "net/http"
require "uri"
uri = URI("https://api.modicagroup.com/rest/im/v1/message")
request = Net::HTTP::Post.new(uri)
request["Authorization"] = "Basic <TOKEN>"
request["Content-Type"] = "application/json"
request.body = {
destination: {
mobile: "+64272383189",
email: "jane.citizen@example.com"
},
message: {
type: "text",
text: {
subject: "Su pedido ha sido enviado",
body: "Su pedido 10452 ha sido enviado y llegará el viernes."
}
},
delivery_attempts: [
{ channel: "wab", event: "read", timeout: 3600 },
{ channel: "sms", event: "received", timeout: 3600 },
{ channel: "email" }
],
reference: "order-10452",
expires: "2026-11-05T10:00:00+13:00"
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
endimport java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
String payload = """
{
"destination": {
"mobile": "+64272383189",
"email": "jane.citizen@example.com"
},
"message": {
"type": "text",
"text": {
"subject": "Su pedido ha sido enviado",
"body": "Su pedido 10452 ha sido enviado y llegará el viernes."
}
},
"delivery_attempts": [
{ "channel": "wab", "event": "read", "timeout": 3600 },
{ "channel": "sms", "event": "received", "timeout": 3600 },
{ "channel": "email" }
],
"reference": "order-10452",
"expires": "2026-11-05T10:00:00+13:00"
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.modicagroup.com/rest/im/v1/message"))
.header("Authorization", "Basic <TOKEN>")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(payload))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());using System.Text;
using var client = new HttpClient();
var request = new HttpRequestMessage(
HttpMethod.Post,
"https://api.modicagroup.com/rest/im/v1/message");
request.Headers.TryAddWithoutValidation("Authorization", "Basic <TOKEN>");
request.Content = new StringContent(
"""{"destination":{"mobile":"+64272383189","email":"jane.citizen@example.com"},"message":{"type":"text","text":{"subject":"Su pedido ha sido enviado","body":"Su pedido 10452 ha sido enviado y llegará el viernes."}},"delivery_attempts":[{"channel":"wab","event":"read","timeout":3600},{"channel":"sms","event":"received","timeout":3600},{"channel":"email"}],"reference":"order-10452","expires":"2026-11-05T10:00:00+13:00"}""",
Encoding.UTF8,
"application/json");
var response = await client.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();Nota: un intento por email requiere destination.email, y un intento por WhatsApp, SMS, MMS o RCS requiere destination.mobile. Cada intento se envía desde el remitente predeterminado configurado para su aplicación en ese canal.
Referencia de la solicitud
Campos de la solicitud
| Campo | Obligatorio | Descripción |
|---|---|---|
destination |
Sí | A quién se enviará el mensaje. Defina mobile (formato E.164, como +64272383189), email o ambos para cubrir todos los canales que utilice. |
message |
Sí | El contenido del mensaje. type puede ser text o template y debe incluir el objeto text o template correspondiente. |
delivery_attempts |
No | Los canales que se intentarán, en orden. De 1 a 10 intentos. Si se omite, el mensaje se envía por SMS. |
reference |
No | Su propia referencia para el mensaje, de hasta 255 caracteres. Se devuelve en los status callbacks. |
mask |
No | Un sender mask que se aplicará al mensaje, de hasta 20 caracteres. |
expires |
No | Una fecha y hora RFC 3339, como 2026-11-05T10:00:00+13:00. El mensaje no se entrega después de esa fecha y hora. |
charset |
No | El charset del contenido del email: ASCII, UTF-8, ISO-8859-1 o Shift_JIS. |
Mensajes de texto
| Campo | Obligatorio | Descripción |
|---|---|---|
text.body |
Sí | El contenido del mensaje, de hasta 10.000 caracteres. |
text.subject |
No | El asunto del email, de hasta 256 caracteres. Solo se usa para los intentos por email. Puede contener letras, números, espacios, guiones y guiones bajos. |
Mensajes con template
| Campo | Obligatorio | Descripción |
|---|---|---|
template.template_id |
Sí | El ID de un template predefinido. |
template.language |
No | El código de idioma del template, como en o es. |
template.parameters |
No | Hasta 20 pares de name y text. Cada valor de text reemplaza el parámetro con el nombre correspondiente en el template, con un máximo de 256 caracteres. |
Intentos de entrega
Cada intento de entrega tiene los siguientes campos:
| Campo | Obligatorio | Descripción |
|---|---|---|
channel |
Sí | Uno de los siguientes: wab (WhatsApp Business), sms, mms, email o rcs. |
event |
Todos los intentos excepto el último | El status que cuenta como éxito para este intento, como received o read. |
timeout |
Todos los intentos excepto el último | Cuánto tiempo se debe esperar por el evento, en segundos, antes de pasar al siguiente intento. De 0 a 604800 (7 días). |
Los intentos se ejecutan en orden. Si un intento alcanza su evento dentro del timeout, la entrega se detiene en ese punto. De lo contrario, comienza el siguiente intento. El último intento no tiene fallback, por lo que no necesita event ni timeout.
Errores
| Status | Significado |
|---|---|
202 |
El mensaje fue aceptado. El cuerpo de la respuesta contiene su id. |
400 |
El cuerpo de la solicitud no es JSON válido o no coincide con el esquema de la API. |
401 |
Faltan las credenciales, son incorrectas o la solicitud provino de una dirección IP no autorizada. |
422 |
La solicitud está bien formada, pero no pasó la validación. La respuesta enumera cada problema. |
429 |
Demasiadas solicitudes. Reduzca la frecuencia y vuelva a intentarlo. |
500 |
Se produjo un error interno. Vuelva a intentarlo más tarde. |
Respuesta 422:
{
"message": "Validation failed",
"errors": [
{
"field": "delivery_attempts.0.timeout",
"description": "timeout must not be empty"
},
{
"field": "destination.email",
"description": "email must not be empty"
}
]
}
Status callbacks
Solo recibirá status callbacks si configuró una URL de status callback para su aplicación de IM API. Recomendamos usar https:// para la URL de callback.
Cuando cambia el status de un mensaje, se envía una solicitud POST a su URL de callback con un cuerpo JSON:
{
"id": "b95fc11e-37f0-4770-a082-6ea22d4c4d12",
"status": "received",
"channel": "sms",
"reference": "order-10452"
}
| Campo | Descripción |
|---|---|
id |
El ID de mensaje devuelto cuando se aceptó el mensaje. |
status |
El nuevo status. Consulte Estado del mensaje. |
channel |
El channel del intento de entrega, como wab, sms o email. Se omite cuando el status corresponde al mensaje en general, por ejemplo, si se rechaza antes de iniciar cualquier intento. |
detail |
Más información sobre el status, cuando esté disponible. |
reference |
La referencia que envió con el mensaje. Solo aparece si definió una. |
Puede recibir varios callbacks para un mismo mensaje: uno por cada cambio de status de cada intento de entrega y otro para el mensaje en general. Use channel para identificar a qué intento corresponde un callback.
Estado del mensaje
| Status | Descripción |
|---|---|
| accepted | El mensaje fue aceptado para su entrega |
| submitted | El mensaje fue enviado al canal para su entrega |
| sent | El canal envió el mensaje |
| received | El destinatario recibió el mensaje |
| read | El destinatario leyó el mensaje |
| frozen | Un error transitorio puso este mensaje en estado frozen |
| rejected | El mensaje fue rechazado. detail describe el motivo |
| failed | No se pudo entregar el mensaje |
| dead | Un administrador eliminó el mensaje |
| expired | No se pudo entregar el mensaje antes de su expiración |
Ayuda
¿Tiene problemas para integrar alguno de nuestros servicios? Contacte a support@modicagroup.com y le ayudaremos a resolverlos.