Enviando notificaciones activas
Este servicio ejecuta plantillas de notificación y las envía a los usuarios a través de WhatsApp.
Propiedades JSON
- hash: Hash de la empresa donde el template está registrado.
- ANNAEXEC: El IV que se generó, debe utilizarse para encriptar los valores de otras variables.
- templateName: Nombre de la plantilla que se enviará.
- templateNamespace: Espacio de nombres de la plantilla que se enviará.
- templateData: Contiene la lista de números de teléfono y macros/variables para la plantilla que se enviará.
- DeliveryDate: (Opcional) Use esta propiedad para programar el envío. El formato debe ser completado como YYYYMMDDHHMMSS
- Reference: (Opcional) Utiliza este campo para tomar notas sobre el envío.
- PhoneList: Lista de teléfonos separados por punto y coma, por ejemplo, “551199999999;551388888888”
- Prop_Keys: Contiene la lista de macros que serán reemplazadas y sus valores.
- PropName: ID de la macro. Puede ser usada como {{0}}, {{1}}, {{2}},…
NOTA: El espacio {{0}} está reservado para archivos de medios y el valor debe ser una URL - PropValue: Valor que reemplazará a macro.
- PropName: ID de la macro. Puede ser usada como {{0}}, {{1}}, {{2}},…
- Prop_Parms: Contiene la lista de parámetros que se agregarán a la ejecución.
- PropName: Nombre del parámetro
- PropValue: Valor del parámetro
- ReturnMode: (Opcional) Define el tipo de retorno. Si no se proporciona, se considerará el valor por defecto.
- DEFAULT: Retorna una lista de teléfonos con sus respectivos estados de envío.
- RESUME: Devuelve un JSON con datos del envío.
- RequestStatus: Estado del envío
- CANCELED: Todas las notificaciones han sido canceladas.
- QUEUED: En cola para enviar
- PROCESSED: Todas las notificaciones han sido enviadas.
- PROCESSING: El sistema está enviando las notificaciones.
- RequestStatus: Estado del envío
Ejemplos
Algunos ejemplos de cómo implementar el envío de notificaciones de AnnA:
var httpClient = new HttpClient { BaseAddress = new Uri("YOUR_ANNA_URL") };
var result = await httpClient.PostAsJsonAsync("REST/Credentials/GetToken", new { hash = "COMPANY_HASH", user = "USER", pass = "PASSWORD" });
var tokenResponse = await result.Content.ReadFromJsonAsync<GetTokenResponse>();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResponse?.Data.Token);
var notificationsResponse = await httpClient.PostAsJsonAsync("REST/Notifications/Send", new { hash = "COMPANY_HASH", templateName = "TEMPLATE_NAME", templateNamespace = "TEMPLATE_NAMESPACE", templateData = new List<object> { new { PhoneList = "5511111111111;5522222222222", Prop_Keys = new List<object> { new { PropName = "{{1}}", PropValue = "Value 1" } }, Reference = "Test" } } });
Console.WriteLine(await notificationsResponse.Content.ReadAsStringAsync());
public class Main { public static void main(String[] args) throws IOException, InterruptedException { var httpClient = HttpClient.newHttpClient(); Gson gson = new Gson();
String environmentUri = "https://itda.com.br/anna20/";
var credentials = new HashMap<String,String>(); credentials.put("hash", "BA475308"); credentials.put("user", "5513981283143"); credentials.put("pass", "Eclipse00");
var credentialsJson = gson.toJson(credentials);
var httpRequest = HttpRequest.newBuilder() .uri(URI.create(environmentUri + "REST/Credentials/GetToken")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(credentialsJson)) .build();
var credentialsResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
var tokenObj = gson.fromJson(credentialsResponse.body(), GetTokenResponse.class);
var notificationRequestBody = new HashMap<String, Object>();
notificationRequestBody.put("hash", "BA475308"); notificationRequestBody.put("templateName", "checkambiente1"); notificationRequestBody.put("templateNamespace", "8251bcca_c203_4b97_9b74_d4179b9fa83e");
notificationRequestBody.put("templateData", new ArrayList<>( Arrays.asList( Map.ofEntries( Map.entry("PhoneList", "5513982051651"), Map.entry("Prop_Keys", new ArrayList<>(Arrays.asList( Map.ofEntries( Map.entry("PropName", "{{1}}"), Map.entry("Propvalue", "Guilherme Agunzo") ) ))), Map.entry("Reference", "Teste Java") ) ) ));
var getDataRequestBodyJson = gson.toJson(notificationRequestBody);
var getDataRequest = HttpRequest.newBuilder() .uri(URI.create(environmentUri + "REST/Notifications/Send")) .setHeader("Content-Type", "application/json") .setHeader("Authorization", "Bearer "+tokenObj.data.get("Token")) .POST(HttpRequest.BodyPublishers.ofString(getDataRequestBodyJson)) .build();
var getDataResponse = httpClient.send(getDataRequest, HttpResponse.BodyHandlers.ofString());
System.out.println(getDataResponse.body());
} }
class GetTokenResponse { public String success; public String message; public HashMap<String,Object> data; }
Auth.GetToken
// V3
// 1) Create Credentials DATA&Request_Properties.Set(!'hash', !'<COMPANY_HASH>') // Ex: ANNA1234&Request_Properties.Set(!'user', !'<PHONE_NUMBER>') // Ex: 5511912345678&Request_Properties.Set(!'pass', !'<PASSWORD>') // Ex: Pass1234!
// 2) Prepare and execute the HTTP request&HttpClient = new()&httpClient.AddHeader(!'Content-Type', !'application/json')&HttpClient.AddString(&Request_Properties.ToJson())&BaseURL = !'<BASE_URL>' // !'https://itda.com.br/anna20/'&HttpClient.Execute(HttpMethod.Post, &BaseURL + !'REST/Credentials/GetToken')
// 3) Check the response&Response_Properties.FromJson(&HttpClient.ToString())&Response_Properties.FromJson(&Response_Properties.Get(!'data'))&JWT_Token = &Response_Properties.Get(!'Token') // Token
&HttpResponse.AddString(&JWT_Token + !'<br>')if &httpClient.StatusCode = 200 &HttpResponse.AddString(!'token generated successfully.<br>' + &HttpClient.ToString())else &HttpResponse.AddString(!'Error generating token: ' + &httpClient.StatusCode.ToString().Trim() + !'<br>' + &HttpClient.ToString())endif// Expected// {// "success":true,// "message":"OK",// "data":{// "Token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21wYW55IjoiQW5uQSIsImlzcyI6Iml0ZGEuY29tLmJyIiwiZXhwIjoxNzQyODIyNjM1LCJqdGkiOiI4MGFkYzkyOC1kMjI5LTRkYWUtODE4NS0yOGViMjE0MzAzY2YifQ._LzJv83ZYrEoKG6tVgCMb157Hmd73L-y003JWxqa3w0",// "ExpiresIn":"3600"// }// }
Notification.Send
// V3
&HttpClient.AddString(!'{"hash":"<COMPANY_HASH>","user":"<PHONE_NUMBER>","pass":"<PASSWORD>"}')&HttpClient.Execute(HttpMethod.Post, !'https://itda.com.br/anna20/REST/Credentials/GetToken') // Use correct URL. Check documentation&Response_Properties.FromJson(&HttpClient.ToString())&Response_Properties.FromJson(&Response_Properties.Get(!'data'))&JWT_Token = &Response_Properties.Get(!'Token')// Check documentation to get JWT Token
/* SDT: notification - hash (Character(8)) - templateName (Varchar(500)) - templateNamespace (Varchar(500)) - templateData (Collection) // templateDataItem elements SDT: templateDataItem - DeliveryDate (Varchar(40)) - PhoneList (LongVarChar(2M)) - Reference (Varchar(100)) - Prop_Keys (Collection) // Prop_KeysItem elements SDT: Prop_KeysItem - PropName (Varchar(4K)) - PropValue (Varchar(4M)) - Prop_Parms (Collection) // Prop_ParmsItem elements SDT: Prop_ParmsItem - PropName (Varchar(4K)) - PropValue (Varchar(4M))*/
// 1) Create the main SDT¬ification.hash = !'<COMPANY_HASH>' // Your Company HASH¬ification.templateName = !'<TEMPLATE_NAME>' // Your Template Name¬ification.templateNamespace = !'<TEMPLATE_NAMESPACE>' // Your Template Namespace
// 2) Create an item for the templateData collection&templateDataItem = new()&templateDataItem.DeliveryDate = !'' // Use like YYYYMMDDhhmmss if needed&templateDataItem.PhoneList = !'<DESTINATION_PHONENUMBER>' // User ; to separate&templateDataItem.Reference = !'' // Annotation
// 3) Initialize the Prop_Keys collection. (PropValue can be base64 or fileURL) - (add items if needed)&PropKey = new()&PropKey.PropName = !'{{IMAGE}}'&PropKey.PropValue = !'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAHUlEQVR4nGIR6JBmIAUwkaR6VMOohiGlARAAAP//YB0A1iZ57AQAAAAASUVORK5CYII='&templateDataItem.Prop_Keys.Add(&PropKey)
// 4) Initialize the Prop_Parms collection (add items if needed)// Example:// &PropParm = new()// &PropParm.PropName = !'ExampleParam'// &PropParm.PropValue = !'ExampleValue'// &templateDataItem.Prop_Parms.Add(&PropParm)
// 5) Add the templateData item to the main SDT¬ification.templateData.Add(&templateDataItem)
// 6) Convert the SDT to JSON for the request body&RequestJson = ¬ification.ToJson()
// 7) Prepare and execute the HTTP request&httpClient = new()&httpClient.AddHeader(!'Authorization', !'Bearer ' + &JWT_Token) // Check documentation to obtain JWT Token&httpClient.AddHeader(!'Content-Type', !'application/json')&httpClient.AddString(&RequestJson)&BaseURL = !'<BASE_URL>' // !'https://itda.com.br/anna20/'&HttpClient.Execute(HttpMethod.Post, &BaseURL + !'REST/Notifications/Send')
// 8) Check the responseif &httpClient.StatusCode = 200 &HttpResponse.AddString(!'notification sent successfully.<br>' + &HttpClient.ToString())else &HttpResponse.AddString(!'Error sending notification: ' + &httpClient.StatusCode.ToString().Trim() + !'<br>' + &HttpClient.ToString())endif