{
  "name": "ZapTerminal: etiquetar quem escreveu",
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "Recebe os webhooks do ZapTerminal, confere a assinatura e, a cada mensagem recebida, põe a etiqueta \"Respondido pelo n8n\" na conversa pela API (rascunho nenhum: só a etiqueta). Variáveis: ZAPTERMINAL_API_KEY (zt_live_… ou zt_test_… com read:labels e write:labels), ZAPTERMINAL_WEBHOOK_SECRET (whsec_…). Com uma chave de teste, ligue ZAPTERMINAL_ACCEPT_TEST=1 e dispare um evento falso em POST /v1/sandbox/events (sem ela, eventos de teste são ignorados)."
  },
  "nodes": [
    {
      "id": "a1",
      "name": "Webhook ZapTerminal",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "zapterminal",
        "responseMode": "onReceived",
        "responseCode": 200,
        "options": {
          "rawBody": true
        }
      },
      "webhookId": "zapterminal"
    },
    {
      "id": "a2",
      "name": "Conferir assinatura",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "// ZapTerminal: confere a assinatura do webhook (x-zapterminal-signature: t=<unix>,v1=<hex>).\n// Precisa: no n8n, NODE_FUNCTION_ALLOW_BUILTIN=crypto; a variável ZAPTERMINAL_WEBHOOK_SECRET com o segredo whsec_… (mostrado uma vez\n// ao cadastrar o webhook); e o nó Webhook com \"Raw Body\" ligado (a assinatura é dos bytes exatos do corpo).\nconst crypto = require('crypto');\nfunction verify(header, body, secret, nowMs) {\n  const t = /(?:^|,)t=(\\d+)/.exec(header || '')?.[1];\n  const sigs = [...String(header || '').matchAll(/(?:^|,)v1=([0-9a-f]{64})/g)].map((m) => m[1]);\n  if (!t || !sigs.length || Math.abs(nowMs / 1000 - Number(t)) > 300) return false; // (mais de 5 min: recuse: repetição)\n  const want = Buffer.from(crypto.createHmac('sha256', secret).update(t + '.' + body).digest('hex'));\n  return sigs.some((v) => { const got = Buffer.from(v); return got.length === want.length && crypto.timingSafeEqual(got, want); });\n}\nconst item = $input.first();\nconst headers = item.json.headers || {};\nconst raw = item.binary && item.binary.data ? Buffer.from(item.binary.data.data, 'base64').toString('utf8') : JSON.stringify(item.json.body);\nif (!verify(headers['x-zapterminal-signature'], raw, $env.ZAPTERMINAL_WEBHOOK_SECRET, Date.now())) throw new Error('ZapTerminal: assinatura inválida, entrega recusada');\nconst event = JSON.parse(raw);\n// (um evento de teste, com \"test\": true, de uma chave zt_test_, só passa se este fluxo for de teste: ZAPTERMINAL_ACCEPT_TEST=1)\nif (event.test === true && !$env.ZAPTERMINAL_ACCEPT_TEST) return [];\n// (a mesma entrega pode chegar duas vezes, numa repetição ou um \"Reenviar\": use event.id para não fazer nada duas vezes)\nreturn [{ json: event }];\n"
      }
    },
    {
      "id": "a3",
      "name": "É mensagem recebida?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        480,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ $json.event }}",
              "rightValue": "message.received",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ]
        }
      }
    },
    {
      "id": "a4",
      "name": "Etiquetar a conversa",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        720,
        -80
      ],
      "parameters": {
        "method": "POST",
        "url": "=https://app.zapterminal.com/v1/numbers/{{ $json.data.number }}/conversations/{{ $json.data.conversation }}/labels",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.ZAPTERMINAL_API_KEY }}"
            },
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.id }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={ \"label\": \"Respondido pelo n8n\" }",
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "a5",
      "name": "Etiquetas da conversa",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        960,
        -80
      ],
      "parameters": {
        "method": "GET",
        "url": "=https://app.zapterminal.com/v1/numbers/{{ $('Conferir assinatura').item.json.data.number }}/conversations/{{ $('Conferir assinatura').item.json.data.conversation }}/labels",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $env.ZAPTERMINAL_API_KEY }}"
            }
          ]
        },
        "options": {}
      }
    }
  ],
  "connections": {
    "Webhook ZapTerminal": {
      "main": [
        [
          {
            "node": "Conferir assinatura",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Conferir assinatura": {
      "main": [
        [
          {
            "node": "É mensagem recebida?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "É mensagem recebida?": {
      "main": [
        [
          {
            "node": "Etiquetar a conversa",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Etiquetar a conversa": {
      "main": [
        [
          {
            "node": "Etiquetas da conversa",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}