{
  "name": "WhatSync: safe send",
  "nodes": [
    {
      "parameters": {
        "content": "## WhatSync: safe send\nSends one WhatsApp message and tells you for sure what happened.\n\n**Input** (from an Execute Sub-workflow node)\n- `tool`: `send_message` or `send_group_message`\n- `body`: the tool's JSON body, for example `{\"conversationId\":\"...\",\"text\":\"...\"}`\n- `idempotencyKey`: one stable key per message, for example the webhook event id\n\n**Output**: `outcome` is `sent`, `delivered`, `not_sent`, `undelivered` or `unknown`, plus `ok`, `needs_human`, `retry_later`, `code` and `message`.\n\n**Set up**: pick your **WhatSync API key** credential in the **Send** and **Get send status** nodes, then publish.\nGuide: https://whatsync.app/docs/guides/safe-send",
        "height": 330,
        "width": 560,
        "color": 4
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -620,
        -420
      ],
      "id": "dc9e72dd-9c21-4e08-a853-2255a5093296"
    },
    {
      "parameters": {
        "inputSource": "workflowInputs",
        "workflowInputs": {
          "values": [
            {
              "name": "tool"
            },
            {
              "name": "body",
              "type": "object"
            },
            {
              "name": "idempotencyKey"
            }
          ]
        }
      },
      "name": "Start",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        -620,
        0
      ],
      "id": "dd0bfc5b-b212-41dc-a03f-12d6a0cd0750"
    },
    {
      "parameters": {},
      "name": "Try it by hand",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -620,
        200
      ],
      "id": "c135bbe1-9cd2-4d32-a4be-c6b9c37e636d"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "bce50eab-df95-4d86-a12e-0d455b363a70",
              "name": "tool",
              "value": "send_message",
              "type": "string"
            },
            {
              "id": "34728906-e72d-43b8-a195-823f979cc750",
              "name": "body",
              "value": "={{ { \"channel\": \"qr\", \"phoneNumber\": \"15550000001\", \"text\": \"Test from n8n at \" + $now.toFormat(\"HH:mm:ss\") } }}",
              "type": "object"
            },
            {
              "id": "d9f10498-3e6b-4176-aa8d-c8847b552d8b",
              "name": "idempotencyKey",
              "value": "=manual-test-{{ $execution.id }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "name": "Test input",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -400,
        200
      ],
      "id": "1821f90b-8baf-4c46-ad4e-2ff2c203b6f6"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "fd6d7546-de46-4a4c-a30f-03b89e5ef555",
              "name": "whatsyncUrl",
              "value": "https://whatsync.app",
              "type": "string"
            },
            {
              "id": "82ecb6d5-dd59-4112-a20f-efaeead13e56",
              "name": "maxTries",
              "value": 5,
              "type": "number"
            },
            {
              "id": "903fa546-ed01-4a29-a80c-6886b2072a9d",
              "name": "maxChecks",
              "value": 6,
              "type": "number"
            },
            {
              "id": "900e6772-74e8-4d1d-a978-6c8638d3d4a3",
              "name": "tool",
              "value": "={{ $json.tool || \"send_message\" }}",
              "type": "string"
            },
            {
              "id": "cb5cc70e-d88c-459f-a5d1-d4609e56d087",
              "name": "body",
              "value": "={{ $json.body }}",
              "type": "object"
            },
            {
              "id": "d401883f-8db6-45dc-af55-f15a48ebebc1",
              "name": "key",
              "value": "={{ $json.idempotencyKey }}",
              "type": "string"
            },
            {
              "id": "85660d4d-9bd4-4aea-af64-63a5848fd228",
              "name": "original_key",
              "value": "={{ $json.idempotencyKey }}",
              "type": "string"
            },
            {
              "id": "659a7ee6-099d-4153-a67b-eb9a96e8a486",
              "name": "tries",
              "value": 1,
              "type": "number"
            },
            {
              "id": "6158003a-58e1-46da-a792-995bb780fbb2",
              "name": "new_keys",
              "value": 0,
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -180,
        0
      ],
      "id": "5ad386f1-9b59-4c62-a50b-aae975e414f3"
    },
    {
      "parameters": {},
      "name": "Attempt",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        40,
        0
      ],
      "id": "4de61c61-c97e-4b9f-adb1-64da4047e82f"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.whatsyncUrl }}/api/v1/tools/{{ $json.tool }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Idempotency-Key",
              "value": "={{ $json.key }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      },
      "name": "Send",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        260,
        0
      ],
      "id": "9a627add-8707-4079-aeab-00c18d3a3614",
      "credentials": {
        "httpHeaderAuth": {
          "id": "WHATSYNC_API_KEY",
          "name": "WhatSync API key"
        }
      },
      "onError": "continueRegularOutput",
      "notes": "POST /api/v1/tools/send_message with the Idempotency-Key header. A timeout or network error does not stop the workflow: the next node decides."
    },
    {
      "parameters": {
        "jsCode": "// Reads WhatSync's answer to the send and picks the next step. This node sends nothing.\nconst state = $('Attempt').last().json;\nconst res = $input.first().json;\nconst status = Number(res.statusCode) || 0; // 0 means no answer at all: a timeout or a network error\nlet body = res.body;\nif (typeof body === 'string') { try { body = JSON.parse(body); } catch (e) { body = {}; } }\nbody = body || {};\nconst err = body.error && typeof body.error === 'object' ? body.error : {};\nconst code = err.code || (status === 0 ? 'no_answer' : status < 300 ? 'accepted' : 'http_' + status);\nlet message = String(err.message || '');\n// A refused group send carries its reason as JSON text inside message.\nif (message.trim().startsWith('{')) {\n  try { const inner = JSON.parse(message); message = (inner.result && inner.result.error) || inner.error || message; } catch (e) {}\n}\nconst retryAfter = Number((res.headers || {})['retry-after'] || err.retry_after) || 0;\nconst ids = {\n  intent_id: body.intent_id || err.intent_id || state.intent_id || null,\n  operation_id: body.operation_id || err.operation_id || state.operation_id || null,\n};\nconst result = (outcome, extra = {}) => [{ json: {\n  next: 'done', outcome, ok: outcome === 'sent' || outcome === 'delivered',\n  needs_human: false, retry_later: false, code, message, http_status: status, retry_after: retryAfter || null,\n  ...ids, status: body.status || null, delivery_status: body.delivery_status || null, delivery_errors: body.delivery_errors || [],\n  channel: body.channel || null, idempotency_key: state.key, tries: state.tries, ...extra,\n} }];\nconst retry = (wait, newKey) => [{ json: { ...state, ...ids, next: 'retry', wait, tries: state.tries + 1,\n  key: newKey || state.key, new_keys: state.new_keys + (newKey ? 1 : 0) } }];\nconst check = (wait) => [{ json: { ...state, ...ids, next: 'check', wait, checks: 0 } }];\nconst canRetry = state.tries < state.maxTries;\n\nif (status >= 200 && status < 300) {\n  if (!body.intent_id) return result('sent'); // group and file sends answer with operation_id and status completed\n  // A personal number gets no delivery receipts, so \"accepted\" is the final answer. A Business number goes on to check delivery.\n  if (body.status === 'accepted' && body.channel !== 'business') return result('sent');\n  return check(2);\n}\nif (status === 0 || status >= 500) {\n  // No answer, or the server failed. The message may or may not have gone, so ask again with the SAME key:\n  // WhatSync answers with the first send's result instead of sending twice.\n  if (canRetry) return retry([5, 15, 30, 60][Math.min(state.tries - 1, 3)]);\n  return result('unknown', { needs_human: true, message: message || 'No answer from WhatSync after ' + state.tries + ' tries with the same key.' });\n}\nif (code === 'outcome_unknown') {\n  // WhatSync has the send on record but not its result yet. Never a new key here. Look the send up instead.\n  if (ids.intent_id || ids.operation_id) return check(3);\n  return result('unknown', { needs_human: true });\n}\nif (code === 'rate_limited') {\n  // Too fast (5 sends a minute per number). Nothing was sent. Same key again after the wait.\n  if (canRetry && retryAfter <= 65) return retry((retryAfter || 30) + 1);\n  return result('not_sent', { retry_later: true });\n}\nif (code === 'new_people_limit') {\n  // Nothing was sent, and this key is now used up. A short wait (30 seconds between new people) is worth waiting for.\n  if (canRetry && retryAfter && retryAfter <= 65) return retry(retryAfter + 1, state.original_key.slice(0, 120) + '.r' + (state.new_keys + 1));\n  return result('not_sent', { retry_later: true, needs_human: true });\n}\nif (code === 'daily_limit_reached') return result('not_sent', { retry_later: true, needs_human: true });\n// sending_off, whatsapp_not_connected, from_number_required, tool_error, invalid_input, invalid_api_key, plan_required,\n// insufficient_permission: nothing was sent and waiting will not fix it. A person has to look.\nreturn result('not_sent', { needs_human: true });\n"
      },
      "name": "Decide",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        0
      ],
      "id": "b7d9a0f0-6fee-4125-a0ab-cc72ef891db9"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "b96235ca-ff69-42f8-a43a-d70fba793b97",
              "leftValue": "={{ $json.next }}",
              "rightValue": "retry",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Send again?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        700,
        0
      ],
      "id": "422d1384-f71a-485e-a560-97d4313a9636"
    },
    {
      "parameters": {
        "amount": "={{ $json.wait }}",
        "unit": "seconds"
      },
      "name": "Wait before sending again",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        700,
        -220
      ],
      "id": "d6fb9cae-1f77-4588-ae08-bf28b9d78f57",
      "webhookId": "a7f0c1d2-safe-send-retry"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "85a40188-9eae-4b9b-a7ab-fc9fbd594a3e",
              "leftValue": "={{ $json.next }}",
              "rightValue": "check",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Check delivery?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        920,
        100
      ],
      "id": "39deb31e-65bc-466b-a3e9-b8c2e2cb3f97"
    },
    {
      "parameters": {
        "amount": "={{ $json.wait }}",
        "unit": "seconds"
      },
      "name": "Wait before checking",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        1140,
        0
      ],
      "id": "75248b87-4531-4a79-aba5-f1f3fd772944",
      "webhookId": "a7f0c1d2-safe-send-check"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.whatsyncUrl }}/api/v1/tools/{{ $json.intent_id ? \"get_send_status\" : \"get_operation\" }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.intent_id ? { intentId: $json.intent_id } : { operationId: $json.operation_id }) }}",
        "options": {
          "timeout": 30000,
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true
            }
          }
        }
      },
      "name": "Get send status",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1360,
        0
      ],
      "id": "1ab4b29e-2b0d-4b5d-a1df-dfb599887215",
      "credentials": {
        "httpHeaderAuth": {
          "id": "WHATSYNC_API_KEY",
          "name": "WhatSync API key"
        }
      },
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Reads get_send_status (or get_operation) and decides: finished, or look again in a moment.\nconst state = $('Wait before checking').last().json;\nconst res = $input.first().json;\nconst status = Number(res.statusCode) || 0;\nlet body = res.body;\nif (typeof body === 'string') { try { body = JSON.parse(body); } catch (e) { body = {}; } }\nbody = body || {};\nconst checks = state.checks + 1;\nconst waits = [2, 4, 8, 15, 30, 60];\nconst result = (outcome, extra = {}) => [{ json: {\n  next: 'done', outcome, ok: outcome === 'sent' || outcome === 'delivered',\n  needs_human: false, retry_later: false, code: outcome === 'sent' || outcome === 'delivered' ? 'accepted' : (body.status || 'unknown'),\n  message: '', http_status: status, retry_after: null, intent_id: state.intent_id, operation_id: state.operation_id,\n  status: body.status || null, delivery_status: body.delivery_status || null, delivery_errors: body.delivery_errors || [],\n  channel: body.channel || null, idempotency_key: state.key, tries: state.tries, status_checks: checks, ...extra,\n} }];\nconst again = () => checks < state.maxChecks ? [{ json: { ...state, next: 'check', checks, wait: waits[Math.min(checks, waits.length - 1)] } }] : null;\n\nif (status !== 200) return again() || result('unknown', { needs_human: true, message: 'Could not read the send status.' });\n\nif (state.intent_id) {\n  const delivery = body.delivery_status || null;\n  if (body.status === 'accepted') {\n    if (body.channel !== 'business') return result('sent');\n    if (delivery === 'delivered' || delivery === 'read') return result('delivered');\n    if (delivery === 'failed') return result('undelivered', { needs_human: true, code: 'delivery_failed',\n      message: ((body.delivery_errors || [])[0] || {}).title || body.next_action || 'Meta reported a delivery failure.' });\n    // Accepted, and Meta has not confirmed delivery yet. After the last look it counts as sent; message.status events tell the rest.\n    return again() || result('sent');\n  }\n  if (body.status === 'sending' || body.status === 'pending') return again() || result('unknown', { needs_human: true, message: 'The send is still in progress.' });\n  if (['failed', 'expired', 'cancelled'].includes(body.status)) return result('not_sent', { needs_human: true, message: body.error || 'The send ' + body.status + '.' });\n  return result('unknown', { needs_human: true, message: body.note || 'The outcome is uncertain. Do not send it again.' });\n}\n// A group or file send: get_operation\nif (body.status === 'completed') return result('sent');\nif (body.status === 'running') return again() || result('unknown', { needs_human: true, message: 'The action is still running.' });\nif (body.status === 'failed') return result('not_sent', { needs_human: true, message: (body.result || {}).error || 'The action failed.' });\nif (body.status === 'retryable') return result('not_sent', { retry_later: true, message: (body.result || {}).error || '' });\nreturn result('unknown', { needs_human: true, message: 'The outcome is uncertain. Do not send it again.' });\n"
      },
      "name": "Decide from status",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1580,
        0
      ],
      "id": "5d3ef328-46e4-4415-a840-076dd3174a10"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "720eede6-00fc-4f3d-a9ab-4b6b25a58162",
              "leftValue": "={{ $json.next }}",
              "rightValue": "check",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Check again?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1800,
        0
      ],
      "id": "cbf50fb7-7e68-49c6-aecb-4133d28e5f0c"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": []
        },
        "includeOtherFields": true,
        "include": "except",
        "excludeFields": "next",
        "options": {}
      },
      "name": "Result",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2020,
        200
      ],
      "id": "89bb8205-a1bc-4fdd-ac65-bca680880c9d"
    }
  ],
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Attempt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Attempt": {
      "main": [
        [
          {
            "node": "Send",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send": {
      "main": [
        [
          {
            "node": "Decide",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide": {
      "main": [
        [
          {
            "node": "Send again?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Try it by hand": {
      "main": [
        [
          {
            "node": "Test input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Test input": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send again?": {
      "main": [
        [
          {
            "node": "Wait before sending again",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Check delivery?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait before sending again": {
      "main": [
        [
          {
            "node": "Attempt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check delivery?": {
      "main": [
        [
          {
            "node": "Wait before checking",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait before checking": {
      "main": [
        [
          {
            "node": "Get send status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get send status": {
      "main": [
        [
          {
            "node": "Decide from status",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Decide from status": {
      "main": [
        [
          {
            "node": "Check again?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check again?": {
      "main": [
        [
          {
            "node": "Wait before checking",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
