Enviando notificações ativas
Esse serviço executa templates de notificação e envia para os usuários via WhatsApp
Variáveis POST
- HASH: Hash da empresa que o template está cadastrado
- ANNAEXEC: O IV que foi gerado, esse deve ser utilizado para encriptação dos valores de outras variáveis
- Name: Nome do template que será enviado
- Namespace: Namespace do template que será enviado
- TemplateData: Contém a lista de telefones e macros/variáveis para o template que será enviado
- DeliveryDate: (Opcional) Utilize essa propriedade para agendar o envio. O formato deve ser preenchido como YYYYMMDDHHMM
- Reference: (Opcional) Utilize esse campo para fazer anotações sobre o envio
- PhoneList: Lista de telefones separados por ponto e vírgula, por exemplo, “551199999999;551388888888”
- Prop_Keys: Contém a lista de macros que serão substituídas e seus valores
- PropName: ID da macro. Pode ser utilizada como {{0}}, {{1}}, {{2}},…
NOTA: O slot {{0}} é reservado para arquivos de mídia e o valor deve ser um URL - PropValue: Valor que irá substituir a macro
- PropName: ID da macro. Pode ser utilizada como {{0}}, {{1}}, {{2}},…
- Prop_Parms: Contém a lista de parâmetros que serão adicionados a execução
- PropName: Nome do parâmetro
- PropValue: Valor do parâmetro
- ReturnMode: (Opcional) Define o tipo de retorno. Se não informado, então o valor DEFAULT será considerado
- DEFAULT: Retorno uma lista de telefones com seus respectivos estados de envio
- RESUME: Retorna um JSON com dados do envio
- RequestStatus: Estado do envio
- CANCELED: Todas as notificações foram canceladas
- QUEUED: Em fila para enviar
- PROCESSED: Todas as notificações foram enviadas
- PROCESSING: O sistema está enviado as notificações
- RequestStatus: Estado do envio
Exemplos
Alguns exemplo de como implementar o envio de notificações AnnA:
public static string Execute_WebService() { string DecKey = "DECRYPTION_KEY"; string EncKey = "ENCRYPTION_KEY"; string Hash = "COMPANY_HASH"; // Generate new IV TripleDESCryptoServiceProvider auxTdes = new TripleDESCryptoServiceProvider(); auxTdes.GenerateIV(); byte[] IVArray = auxTdes.IV; string IV = Convert.ToBase64String(IVArray);
string templateName = "TEMPLATE_NAME"; string encryptedTemplateName = Encrypt(templateName, EncKey, IV); string templateNamespace = "TEMPLATE_NAMESPACE"; string encryptedTemplateNamespace = Encrypt(templateNamespace, EncKey, IV);
string json = "[{"; json += "\"PhoneList\":\"950691561;914694745\","; json += "\"Prop_Keys\":"; json += " ["; json += " {"; json += " \"PropName\":\"{{1}}\","; json += " \"PropValue\":\"AnnA\""; json += " },"; json += " {"; json += " \"PropName\":\"{{2}}\","; json += " \"PropValue\":\"10/07/2021\""; json += " }"; json += " ],"; json += "\"Prop_Parms\":"; json += " ["; json += " {"; json += " \"PropName\":\"var\","; json += " \"PropValue\":\"AnnA\""; json += " }"; json += " ]},"; json += " {"; json += "\"PhoneList\":\"977225248;971195982\","; json += "\"Prop_Keys\":"; json += " ["; json += " {"; json += " \"PropName\":\"{{2}}\","; json += " \"PropValue\":\"10/08/2021\""; json += " }"; json += " ],"; json += "\"Prop_Parms\":"; json += " ["; json += " {"; json += " \"PropName\":\"var\","; json += " \"PropValue\":\"AnnA\""; json += " }"; json += " ]"; json += "}]";
string encryptedTemplateData = Encrypt(json, EncKey, IV);
string postData = "HASH=" + Uri.EscapeDataString(Hash); postData += "&ANNAEXEC=" + Uri.EscapeDataString(IV); postData += "&Name=" + Uri.EscapeDataString(encryptedTemplateName); postData += "&Namespace=" + Uri.EscapeDataString(encryptedTemplateNamespace); postData += "&TemplateData=" + Uri.EscapeDataString(encryptedTemplateData); byte[] data = Encoding.UTF8.GetBytes(postData);
string url = "https://YOUR_ANNA_URL/aannatemplatenotification.aspx"; WebRequest requisicaoWeb = WebRequest.Create(url); requisicaoWeb.Method = "POST"; requisicaoWeb.ContentType = "application/x-www-form-urlencoded"; requisicaoWeb.ContentLength = data.Length;
Stream dataStream = requisicaoWeb.GetRequestStream();
dataStream.Write(data, 0, data.Length); dataStream.Close();
WebResponse response = requisicaoWeb.GetResponse();
using (dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd();
if (responseFromServer.Contains(IV)) { string newEncryptedIv = responseFromServer.Substring(responseFromServer.IndexOf(IV)); newEncryptedIv = newEncryptedIv.Replace(IV, ""); string encryptedResponse = responseFromServer.Substring(0, responseFromServer.IndexOf(IV));
string newIv = Decrypt(newEncryptedIv, EncKey, IV);
string responseData = Decrypt(encryptedResponse, DecKey, newIv);
response.Close();
return responseData; } else { response.Close(); return responseFromServer; } } }
var decryptionKey = "YOUR_DECRYPTION_KEY"; var encryptionKey = "YOUR_ENCRYPTION_KEY"; var CompanyHash = "YOUR_COMPANY_HASH";
// Generate new IV var auxTdes = TripleDES.Create(); auxTdes.GenerateIV(); byte[] IVArray = auxTdes.IV; string IV = Convert.ToBase64String(IVArray);
string templateName = "TEMPLATE_NAME"; string templateNameEncriptado = Encrypt3DES(templateName, encryptionKey, IV); string templateNamespace = "TEMPLATE_NAMESPACE"; string templateNamespaceEncriptado = Encrypt3DES(templateNamespace, encryptionKey, IV);
var templateData = new List<object> { new { PhoneList = "5511111111111;5522222222222", Prop_Keys = new List<object> { new { PropName = "{{1}}", PropValue = "AnnA" }, new { PropName = "{{2}}", PropValue = "10/07/2021" } }, Prop_Parms = new List<object> { new { PropName = "var", PropValue = "AnnA" } } }, new { PhoneList = "5533333333333", Prop_Keys = new List<object> { new { PropName = "{{1}}", PropValue = "AnnA 2" }, new { PropName = "{{2}}", PropValue = "18/07/2021" } }, Prop_Parms = new List<object> { new { PropName = "var", PropValue = "AnnA 2" } } } };
var templateDataJson = JsonSerializer.Serialize(templateData);
string templateDataEncriptado = Encrypt3DES(templateDataJson, encryptionKey, IV);
var dadosPost = new Dictionary<string, string> { { "HASH", CompanyHash }, { "ANNAEXEC", IV }, { "Name", templateNameEncriptado }, { "Namespace", templateNamespaceEncriptado }, { "TemplateData", templateDataEncriptado } };
var httpClient = new HttpClient(); string url = "https://YOUR_ANNA_URL/aannatemplatenotification.aspx";
var result = await httpClient.PostAsync(url, new FormUrlEncodedContent(dadosPost)); var content = await result.Content.ReadAsStringAsync();
if (content.Contains(IV)) { string novoIVEncriptado = content.Substring(content.IndexOf(IV)); novoIVEncriptado = novoIVEncriptado.Replace(IV, ""); string retornoEncriptado = content.Substring(0, content.IndexOf(IV));
string novoIV = Decrypt3DES(novoIVEncriptado, encryptionKey, IV);
string retorno = Decrypt3DES(retornoEncriptado, decryptionKey, novoIV);
return Ok(retorno); }
return Ok(content);
try { String DecKey = "DECRYPTION_KEY"; String EncKey = "ENCRYPTION_KEY"; String Hash = "COMPANY_HASH";
// Generate new IV byte[] randomBytes = new byte[8]; new Random().nextBytes(randomBytes); final IvParameterSpec IV = new IvParameterSpec(randomBytes); String IVString = new String(Base64.getEncoder().encode(randomBytes));
byte[] decKeyDecoded = Base64.getDecoder().decode(DecKey); byte[] encKeyDecoded = Base64.getDecoder().decode(EncKey);
SecretKey dKey = new SecretKeySpec(decKeyDecoded, "DESede"); SecretKey eKey = new SecretKeySpec(encKeyDecoded, "DESede");
String templateName = "TEMPLATE_NAME"; String templateNameEncriptado = encrypt(templateName, eKey, IV); String templateNamespace = "TEMPLATE_NAMESPACE"; String templateNamespaceEncriptado = encrypt(templateNamespace, eKey, IV);
String json = "[{"; json += "\"PhoneList\":\"950691561;914694745\","; json += "\"Prop_Keys\":"; json += " ["; json += " {"; json += " \"PropName\":\"{{1}}\","; json += " \"PropValue\":\"AnnA\""; json += " },"; json += " {"; json += " \"PropName\":\"{{2}}\","; json += " \"PropValue\":\"10/07/2021\""; json += " }"; json += " ],"; json += "\"Prop_Parms\":"; json += " ["; json += " {"; json += " \"PropName\":\"var\","; json += " \"PropValue\":\"AnnA\""; json += " }"; json += " ]},"; json += " {"; json += "\"PhoneList\":\"977225248;971195982\","; json += "\"Prop_Keys\":"; json += " ["; json += " {"; json += " \"PropName\":\"{{2}}\","; json += " \"PropValue\":\"10/08/2021\""; json += " }"; json += " ],"; json += "\"Prop_Parms\":"; json += " ["; json += " {"; json += " \"PropName\":\"var\","; json += " \"PropValue\":\"AnnA\""; json += " }"; json += " ]"; json += "}]"; String templateDataEncriptado = encrypt(json, eKey, IV);
String dadosPost = "HASH=" + URLEncoder.encode(Hash, StandardCharsets.UTF_8); dadosPost += "&ANNAEXEC=" + URLEncoder.encode(IVString, StandardCharsets.UTF_8); dadosPost += "&Name=" + URLEncoder.encode(templateNameEncriptado, StandardCharsets.UTF_8); dadosPost += "&Namespace=" + URLEncoder.encode(templateNamespaceEncriptado, StandardCharsets.UTF_8); dadosPost += "&TemplateData=" + URLEncoder.encode(templateDataEncriptado, StandardCharsets.UTF_8);
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://YOUR_ANNA_URL/aannatemplatenotification.aspx")) .header("Content-Type", "application/x-www-form-urlencoded") .POST(BodyPublishers.ofString(dadosPost)) .build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); String responseFromServer = response.body();
if (responseFromServer.contains(IVString)) { String novoIVEncriptado = responseFromServer.substring(responseFromServer.indexOf(IVString)); novoIVEncriptado = novoIVEncriptado.replace(IVString, ""); String retornoEncriptado = responseFromServer.substring(0, responseFromServer.indexOf(IVString));
String novoIVString = decrypt(novoIVEncriptado, eKey, IV);
byte[] ivDecoded = Base64.getDecoder().decode(novoIVString); IvParameterSpec novoIV = new IvParameterSpec(ivDecoded);
String retorno = decrypt(retornoEncriptado, dKey, novoIV);
return retorno; } else { return responseFromServer; } } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | InterruptedException | IOException ex) { Logger.getLogger(AnnaTemplateNotification.class.getName()).log(Level.SEVERE, null, ex); return "Error"; }
$DecKey = "DECRYPTION_KEY"; $EncKey = "ENCRYPTION_KEY"; $Hash = "COMPANY_HASH";
// Generate new IV $ivlen = openssl_cipher_iv_length('des-ede3-cbc'); $IV = base64_encode(openssl_random_pseudo_bytes(8));
$templateName = "TEMPLATE_NAME"; $templateNameEncriptado = encrypt3DES($templateName, $EncKey, $IV); $templateNamespace = "TEMPLATE_NAMESPACE"; $templateNamespaceEncriptado = encrypt3DES($templateNamespace, $EncKey, $IV);
$json = "[{"; $json .= "\"PhoneList\":\"950691561;914694745\","; $json .= "\"Prop_Keys\":"; $json .= " ["; $json .= " {"; $json .= " \"PropName\":\"{{1}}\","; $json .= " \"PropValue\":\"AnnA\""; $json .= " },"; $json .= " {"; $json .= " \"PropName\":\"{{2}}\","; $json .= " \"PropValue\":\"10/07/2021\""; $json .= " }"; $json .= " ],"; $json .= "\"Prop_Parms\":"; $json .= " ["; $json .= " {"; $json .= " \"PropName\":\"var\","; $json .= " \"PropValue\":\"AnnA\""; $json .= " }"; $json .= " ]},"; $json .= " {"; $json .= "\"PhoneList\":\"977225248;971195982\","; $json .= "\"Prop_Keys\":"; $json .= " ["; $json .= " {"; $json .= " \"PropName\":\"{{2}}\","; $json .= " \"PropValue\":\"10/08/2021\""; $json .= " }"; $json .= " ],"; $json .= "\"Prop_Parms\":"; $json .= " ["; $json .= " {"; $json .= " \"PropName\":\"var\","; $json .= " \"PropValue\":\"AnnA\""; $json .= " }"; $json .= " ]"; $json .= "}]"; $templateDataEncriptado = encrypt3DES($json, $EncKey, $IV);
$dadosPost = array( 'HASH' => $Hash, 'ANNAEXEC' => $IV, 'Name' => $templateNameEncriptado, 'Namespace' => $templateNamespaceEncriptado, 'TemplateData' => $templateDataEncriptado);
$url = "https://YOUR_ANNA_URL/aannatemplatenotification.aspx"; $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($dadosPost) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context);
if (str_contains($result, $IV)) { $novoIVEncriptado = substr($result, strpos($result, $IV)); $novoIVEncriptado = str_replace($IV, "", $novoIVEncriptado); $retornoEncriptado = substr($result, 0, strrpos($result, $IV));
$novoIV = decrypt3DES($novoIVEncriptado, $EncKey, $IV);
$retorno = decrypt3DES($retornoEncriptado, $DecKey, $novoIV);
echo $retorno; } else { echo $result; }
&DecKey = !'DECRYPTION_KEY' &EncKey = !'ENCRYPTION_KEY' &Hash = !'COMPANY_HASH'
// Generate new IV &CryptoEncrypt = new() &CryptoEncrypt.Algorithm = CryptoEncryptAlgorithm.TripleDES &Result = &CryptoEncrypt.Encrypt(!'DUMMY') &IV = &CryptoEncrypt.IV
&CryptoEncrypt.Key = &EncKey &CryptoEncrypt.IV = &IV &TemplateName = !'TEMPLATE_NAME' &TemplateNameEncriptado = &CryptoEncrypt.Encrypt(&TemplateName) &TemplateNamespace = !'TEMPLATE_NAMESPACE' &TemplateNamespaceEncriptado = &CryptoEncrypt.Encrypt(&TemplateNamespace)
&Json = '[{' &Json += '"PhoneList":"950691561;914694745",' &Json += '"Prop_Keys":' &Json += ' [' &Json += ' {' &Json += ' "PropName":"var1",' &Json += ' "PropValue":"AnnA"' &Json += ' },' &Json += ' {' &Json += ' "PropName":"var2",' &Json += ' "PropValue":"10/07/2021"' &Json += ' }' &Json += ' ],' &Json += '"Prop_Parms":' &Json += ' [' &Json += ' {' &Json += ' "PropName":"var",' &Json += ' "PropValue":"AnnA"' &Json += ' }' &Json += ' ]},' &Json += ' {' &Json += '"PhoneList":"977225248;971195982",' &Json += '"Prop_Keys":' &Json += ' [' &Json += ' {' &Json += ' "PropName":"var2",' &Json += ' "PropValue":"10/08/2021"' &Json += ' }' &Json += ' ],' &Json += '"Prop_Parms":' &Json += ' [' &Json += ' {' &Json += ' "PropName":"var",' &Json += ' "PropValue":"AnnA"' &Json += ' }' &Json += ' ]' &Json += '}]' &TemplateDataEncriptado = &CryptoEncrypt.Encrypt(&Json)
&HttpClient.AddVariable(!'HASH', &Hash) &HttpClient.AddVariable(!'ANNAEXEC', &IV) &HttpClient.AddVariable(!'Name', &TemplateNameEncriptado) &HttpClient.AddVariable(!'Namespace', &TemplateNamespaceEncriptado) &HttpClient.AddVariable(!'TemplateData', &TemplateDataEncriptado)
&Url = !'https://YOUR_ANNA_URL/aannatemplatenotification.aspx' &HttpClient.AddHeader(!'ContentType', !'application/x-www-form-urlencoded') &HttpClient.Execute(!'POST', &Url)
&Result = &HttpClient.ToString()
If &Result.Contains(&IV) &NovoIVEncriptado = &Result.Substring(&Result.IndexOf(&IV)) &NovoIVEncriptado = &NovoIVEncriptado.Replace(&IV, !'') &RetornoEncriptado = &Result.Substring(1, &Result.IndexOf(&IV) - 1)
&CryptoEncrypt.Key = &EncKey &CryptoEncrypt.IV = &IV &NovoIV = &CryptoEncrypt.Decrypt(&NovoIVEncriptado)
&CryptoEncrypt.Key = &DecKey &CryptoEncrypt.IV = &NovoIV &Retorno = &CryptoEncrypt.Decrypt(&RetornoEncriptado)
Msg(&Retorno) Else Msg(&Result) Endif
import requests import json from Crypto.Cipher import AES, DES3, DES from Crypto.Util.Padding import pad, unpad from Crypto.Random import get_random_bytes from base64 import b64encode, b64decode
# Encryption method def encrypt(data, enckey, iv):
enckey = b64decode(enckey) iv = b64decode(iv)
cipher = DES3.new(enckey, DES3.MODE_CBC, iv) ct_bytes = cipher.encrypt( pad(bytes(data, encoding='utf-8'), DES3.block_size)) ciphertext = b64encode(ct_bytes).decode('utf-8')
return ciphertext
# Decryption method def decrypt(data, deckey, iv): try: deckey = b64decode(deckey) iv = b64decode(iv) data = b64decode(data)
cipher = DES3.new(deckey, DES3.MODE_CBC, iv) pt = unpad(cipher.decrypt(data), DES3.block_size)
return pt.decode('utf-8')
except (ValueError, KeyError): return 'Incorrect decryption'
# Creating an IV key = get_random_bytes(8) cipher = DES.new(key, DES3.MODE_CBC) iv = b64encode(cipher.iv).decode('utf-8')
# Integration variables url = 'https://YOUR_ANNA_URL/aannatemplatenotification.aspx' hash = 'COMPANY_HASH' enckey = 'ENCRYPTION_KEY' deckey = 'DECRYPTION_KEY' templateName = 'TEMPLATE_NAME' namespace = 'TEMPLATE_NAMESPACE' returnMode = 'TEMPLATE_RETURN_MODE'
# Encrypting data templateNameEncrypted = encrypt(templateName, enckey, iv) namespaceEncrypted = encrypt(namespace, enckey, iv) returnModeEncrypted = encrypt(returnMode, enckey, iv)
# JSON structure of the template templateData = [ { "DeliveryDate": "", "PhoneList": "5511111111111;5522222222222", "Prop_Keys": [ { "PropName": "var1", "PropValue": "AnnA" }, { "PropName": "var2", "PropValue": "10/07/2021" } ], "Prop_Parms": [ { "PropName": "var", "PropValue": "AnnA" } ] } ]
# Encrypting the JSON structure of the shipment templateDataEncrypted = encrypt(json.dumps(templateData), enckey, iv)
# Creating the submission structure request = { 'HASH': hash, 'ANNAEXEC': iv, 'Name': templateNameEncrypted, 'Namespace': namespaceEncrypted, 'TemplateData': templateDataEncrypted, 'ReturnMode': returnModeEncrypted }
# Making a post for AnnA response = requests.post(url, request)
# Retrieving AnnA's response response = response.text
# Separating the received IV from the AnnA response string responseEncrypted = response.split(iv)
# Decrypting the new IV newIV = decrypt(responseEncrypted[1], enckey, iv)
# Decrypting the content of the reply responseDecrypt = decrypt(responseEncrypted[0], deckey, newIV)
# Log print('\n') print(' -> Server response:\n', response) print(' -> Separating the new IV from the json:\n', responseEncrypted) print(' -> New IV: ', newIV) print(' -> Decrypted return: ', responseDecrypt) print('\n')