{
  "name": "Wafly - safe text send and message status (native HTTP)",
  "active": false,
  "nodes": [
    {
      "id": "manual",
      "name": "Run one authorized operation",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "config",
      "name": "Configure one operation",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        0
      ],
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "action",
              "name": "action",
              "value": "send",
              "type": "string"
            },
            {
              "id": "instance",
              "name": "instance",
              "value": "YOUR_INSTANCE_ID",
              "type": "string"
            },
            {
              "id": "instanceToken",
              "name": "instanceToken",
              "value": "YOUR_INSTANCE_TOKEN",
              "type": "string"
            },
            {
              "id": "phone",
              "name": "phone",
              "value": "YOUR_AUTHORIZED_NUMBER_WITH_COUNTRY_CODE",
              "type": "string"
            },
            {
              "id": "message",
              "name": "message",
              "value": "My own Wafly safe HTTP integration test.",
              "type": "string"
            },
            {
              "id": "authorizedRecipient",
              "name": "authorizedRecipient",
              "value": false,
              "type": "boolean"
            },
            {
              "id": "operationKey",
              "name": "operationKey",
              "value": "YOUR_UNIQUE_OPERATION_KEY",
              "type": "string"
            },
            {
              "id": "firstAttemptAt",
              "name": "firstAttemptAt",
              "value": "FIXED_FIRST_ATTEMPT_UTC_ISO_ENDING_IN_Z",
              "type": "string"
            },
            {
              "id": "messageId",
              "name": "messageId",
              "value": "PASTE_ORIGINAL_MESSAGE_ID_FOR_STATUS",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "review",
      "name": "Review one operation",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        450,
        0
      ],
      "parameters": {
        "jsCode": "const items = $input.all();\nif (items.length !== 1) throw new Error('Use exactly one operation, never a recipient list.');\nconst c = items[0].json;\nif (!['send', 'status'].includes(c.action)) throw new Error('action must be send or status.');\nif (!/^[A-Za-z0-9_-]{1,128}$/.test(c.instance || '') || c.instance === 'YOUR_INSTANCE_ID') throw new Error('Configure your own instance.');\nif (!/^[A-Za-z0-9_-]{8,256}$/.test(c.instanceToken || '') || c.instanceToken === 'YOUR_INSTANCE_TOKEN') throw new Error('Configure the instance token privately.');\nif (c.action === 'send') {\n  if (!/^[1-9][0-9]{9,14}$/.test(c.phone || '')) throw new Error('Configure an authorized recipient with country code and digits only.');\n  if (c.authorizedRecipient !== true) throw new Error('Confirm recipient authorization before enabling a send.');\n  if (typeof c.message !== 'string' || !c.message.trim() || c.message.length > 500) throw new Error('Use a test text from 1 to 500 characters.');\n  if (!/^[A-Za-z0-9._:-]{8,128}$/.test(c.operationKey || '') || c.operationKey === 'YOUR_UNIQUE_OPERATION_KEY') throw new Error('Set one unique operationKey. Reuse it with the same body to recover this operation.');\n  if (typeof c.firstAttemptAt !== 'string' || !/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?Z$/.test(c.firstAttemptAt)) throw new Error('Set firstAttemptAt to a fixed UTC ISO time recorded before the first attempt, ending in Z. Do not use a changing expression.');\n  const first = Date.parse(c.firstAttemptAt);\n  const age = Date.now() - first;\n  if (!Number.isFinite(first) || age < 0 || age >= 23 * 60 * 60 * 1000) throw new Error('The starter send window is 23 hours from firstAttemptAt. Do not renew the date to retry an old operation; reconcile the result instead.');\n}\nreturn [{ json: c }];"
      }
    },
    {
      "id": "action",
      "name": "Send or status",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        680,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "send-mode",
              "leftValue": "={{ $json.action }}",
              "rightValue": "send",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "send",
      "name": "Send one keyed text",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        900,
        -80
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ 'https://wafly.com.br/api-bridge-whats/instances/' + encodeURIComponent($('Review one operation').first().json.instance) + '/token/' + encodeURIComponent($('Review one operation').first().json.instanceToken) + '/send-text' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.operationKey }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({phone:$json.phone,message:$json.message}) }}",
        "options": {
          "timeout": 15000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "responseFormat": "json",
              "neverError": true
            }
          }
        }
      },
      "disabled": true,
      "retryOnFail": false,
      "onError": "continueRegularOutput"
    },
    {
      "id": "receipt",
      "name": "Keep the original message ID",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1130,
        -80
      ],
      "parameters": {
        "jsCode": "const r = $input.first().json;\nconst cfg = $('Review one operation').first().json;\nconst status = Number(r.statusCode);\nconst codes = {409:'The same key was used with another body. Restore the original request; do not generate a new key to recover it.',410:'The receipt expired. Reconcile the result before deciding on another operation.',404:'Instance, owner or receipt not found. Check both credentials and the instance.',400:'Invalid request or key. Check the configuration.',402:'Access requires review in your Wafly account.',503:'Confirmation is temporarily unavailable. Do not replace the operation key.'};\nif (!Number.isFinite(status)) throw new Error('The send is disabled or its result is unknown after a transport error. Enable it only after setup. For timeout recovery within the window, reuse the SAME key, body and firstAttemptAt.');\nif (status < 200 || status >= 300) throw new Error(codes[status] || 'Request not confirmed. Keep the same operation key and reconcile; do not resend with a new key.');\nconst b = r.body;\nif (!b || b.instance !== cfg.instance || !/^[a-f0-9]{24}$/.test(b.messageId || '') || b.automaticRetry !== false || !Number.isFinite(Date.parse(b.expiresAt))) throw new Error('Unexpected API receipt. Stop and reconcile; no automatic resend.');\nif (Date.parse(b.expiresAt) <= Date.now()) throw new Error('Receipt expired. Do not repeat the old send.');\nreturn [{ json: {messageId:b.messageId} }];"
      }
    },
    {
      "id": "query",
      "name": "Validate message ID",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1350,
        80
      ],
      "parameters": {
        "jsCode": "const items = $input.all();\nif (items.length !== 1 || !/^[a-f0-9]{24}$/.test(items[0].json.messageId || '')) throw new Error('For action=status, paste the messageId from the original keyed send. Status lookup never sends a message.');\nreturn [{json:{messageId:items[0].json.messageId}}];"
      }
    },
    {
      "id": "status",
      "name": "Read message status",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1580,
        80
      ],
      "parameters": {
        "method": "GET",
        "url": "={{ 'https://wafly.com.br/api-bridge-whats/instances/' + encodeURIComponent($('Review one operation').first().json.instance) + '/token/' + encodeURIComponent($('Review one operation').first().json.instanceToken) + '/messages/' + encodeURIComponent($json.messageId) + '/status' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {
          "timeout": 15000,
          "redirect": {
            "redirect": {
              "followRedirects": false
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "responseFormat": "json",
              "neverError": true
            }
          }
        }
      },
      "disabled": true,
      "retryOnFail": false,
      "onError": "continueRegularOutput"
    },
    {
      "id": "summary",
      "name": "Understand the result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1810,
        80
      ],
      "parameters": {
        "jsCode": "const r = $input.first().json;\nconst status = Number(r.statusCode);\nif (!Number.isFinite(status)) throw new Error('Enable and configure Read message status. A disabled request or transport error is not delivery evidence. Retry only this GET later.');\nif (status === 404) throw new Error('Receipt not found for this instance/owner. It may be expired or from a legacy send without a key. Do not send again automatically.');\nif (status === 410) throw new Error('Receipt expired. Reconcile the old operation; do not repeat its send.');\nif (status < 200 || status >= 300) throw new Error('Status is temporarily unavailable or access was refused. Check credentials and retry only the status lookup later. No message was sent by this lookup.');\nconst b = r.body;\nconst cfg = $('Review one operation').first().json;\nconst expected = $('Validate message ID').first().json.messageId;\nconst labels = {PROCESSING:'Operation reserved; result still pending.',QUEUED:'Forwarded by the bridge; native acceptance not yet observed.',ACCEPTED:'Native acceptance confirmed; handset delivery not observed.',DELIVERED:'Correlated delivery callback confirmed.',FAILED:'Native failure recorded.',UNKNOWN:'Result uncertain. Do not resend with a new key.'};\nif (!b || b.messageId !== expected || b.instance !== cfg.instance || !Object.hasOwn(labels,b.state) || b.automaticRetry !== false || !Number.isFinite(Date.parse(b.expiresAt))) throw new Error('Unexpected or mismatched status response. Stop and reconcile.');\nif (b.state === 'DELIVERED' && b.delivery !== 'confirmed') throw new Error('Inconsistent delivery proof. Stop and reconcile.');\nreturn [{json:{messageId:b.messageId,instance:b.instance,state:b.state,delivery:b.state==='DELIVERED'?'confirmed':'not_observed',explanation:labels[b.state],expiresAt:b.expiresAt,automaticRetry:false,nextAction:['PROCESSING','QUEUED','UNKNOWN'].includes(b.state)?'Set action=status and keep this messageId for a later manual lookup. Do not generate another key.':'Inspect the result. A new business intent needs a new key; never infer reading from delivery.'}}];"
      }
    },
    {
      "id": "setup",
      "name": "Setup - configure before enabling",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -50,
        -740
      ],
      "parameters": {
        "width": 900,
        "height": 620,
        "color": 7,
        "content": "# Wafly: safe text send + status / envio seguro + consulta\n\nPT: Configure uma instância sua e um destinatário autorizado. Nenhuma mensagem é enviada ao importar: workflow inativo e duas chamadas HTTP desativadas.\n\n1. Preencha Configure one operation. action=send para uma intenção de envio; action=status para consultar um messageId conhecido.\n2. Use uma operationKey exclusiva (ex.: UUID) e uma firstAttemptAt UTC FIXA antes da primeira tentativa. Não use expressão $now que muda a cada execução. Nunca mude chave, corpo ou data para recuperar o mesmo envio.\n3. Crie UMA credencial Header Auth com Name=Client-Token e Value=token privado do proprietário. Selecione a mesma credencial nos DOIS HTTP Requests.\n4. Habilite Send one keyed text e Read message status só depois da revisão; execute manualmente uma vez.\n\nEN: Fill your own instance and one authorized recipient. Select the SAME private Client-Token Header Auth credential on BOTH HTTP nodes. Keep one unique key, identical body and fixed original UTC time for timeout recovery. Enable requests only after review.\n\nTokens na URL/configuração são privados: restrinja acesso ao projeto; remova valores e credenciais antes de exportar/compartilhar. Histórico de execução não é salvo por este starter. n8n e Wafly têm custos/condições próprios."
      }
    },
    {
      "id": "recover",
      "name": "Recovery and retention",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        900,
        -720
      ],
      "parameters": {
        "width": 780,
        "height": 570,
        "color": 7,
        "content": "# Recuperação / recovery\n\nTimeout sem messageId? Dentro da janela, recupere com a MESMA chave, corpo e firstAttemptAt. Não existe retry automático.\n\nJá tem messageId? Mude action para status e cole esse ID no campo messageId. O caminho status faz apenas GET, sem envio.\n\nA API guarda o recibo por 24h a partir da primeira chamada. Este starter bloqueia envios com 23h desde a hora fixa informada, como margem conservadora. Não renove a data para reenviar uma operação antiga. Guarde o expiresAt e o ID retornados no seu sistema.\n\nDepois da janela, a chave pode ter sido removida e um POST pode duplicar a mensagem: reconcilie antes de qualquer nova intenção. Chaves distintas permitem mensagens intencionais distintas, inclusive de texto igual.\n\nFor an old/uncertain operation, do not generate a new key or refresh its original time. After the API 24h window, reconcile instead of repeating POST. Status mode never sends."
      }
    },
    {
      "id": "proof",
      "name": "What this result proves",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1550,
        280
      ],
      "parameters": {
        "width": 720,
        "height": 370,
        "color": 7,
        "content": "# O que foi comprovado?\n\nPROCESSING/QUEUED = processamento/fila. ACCEPTED = aceite nativo, sem prova de entrega. DELIVERED + delivery=confirmed = callback de entrega correlacionado, não leitura. FAILED = falha nativa registrada. UNKNOWN = incerto; não reenviar automaticamente.\n\nO starter faz UMA consulta após o envio, sem loop, timer ou polling contínuo. Se ainda estiver pendente, use action=status manualmente depois.\n\nThe result is scoped to the same owner and instance. Missing callbacks remain not_observed. A successful import is not evidence of a real WhatsApp delivery. API Flex não oficial da Meta, sujeita a restrições do número."
      }
    }
  ],
  "connections": {
    "Run one authorized operation": {
      "main": [
        [
          {
            "node": "Configure one operation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Configure one operation": {
      "main": [
        [
          {
            "node": "Review one operation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Review one operation": {
      "main": [
        [
          {
            "node": "Send or status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send or status": {
      "main": [
        [
          {
            "node": "Send one keyed text",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Validate message ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send one keyed text": {
      "main": [
        [
          {
            "node": "Keep the original message ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep the original message ID": {
      "main": [
        [
          {
            "node": "Validate message ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate message ID": {
      "main": [
        [
          {
            "node": "Read message status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read message status": {
      "main": [
        [
          {
            "node": "Understand the result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "none",
    "saveDataSuccessExecution": "none",
    "saveManualExecutions": false,
    "saveExecutionProgress": false
  },
  "pinData": {},
  "tags": []
}
