{
  "name": "WhatSync: log WhatsApp messages to Google Sheets",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsync-log",
        "responseMode": "onReceived",
        "options": {
          "rawBody": true
        }
      },
      "name": "WhatsApp event",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "id": "c1bff369-8b41-431f-a87a-65c992b2c95d",
      "webhookId": "whatsync-whatsync-log",
      "notes": "Answers WhatSync at once (it waits at most 10 seconds). Raw Body must stay on: the signature is checked on the exact bytes."
    },
    {
      "parameters": {
        "jsCode": "// Checks that the request really came from WhatSync before anything else runs.\n// WhatSync signs every event (Standard Webhooks): HMAC-SHA256 of \"id.timestamp.body\" with your signing secret.\n// Paste the signing secret of your webhook below. It starts with whsec_ and is shown when you add the webhook.\nconst SECRET = 'whsec_PASTE_YOUR_SIGNING_SECRET';\n\nconst item = $input.first();\nconst headers = item.json.headers || {};\nconst id = String(headers['webhook-id'] || '');\nconst timestamp = String(headers['webhook-timestamp'] || '');\nif (SECRET.includes('PASTE_YOUR')) throw new Error('Paste your WhatSync signing secret into the \"Verify signature\" node.');\nif (!id || !/^\\d+$/.test(timestamp)) throw new Error('Rejected: the WhatSync signature headers are missing.');\nif (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error('Rejected: this event is more than 5 minutes old.');\n\n// The exact bytes WhatSync sent. Needs \"Raw Body\" switched on in the Webhook node's options.\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data');\n\n// SHA-256 and HMAC in plain JavaScript: the Code node cannot load Node's crypto module unless the server allows it.\nconst K = [], H0 = [];\nfor (let n = 2; K.length < 64; n++) {\n  let prime = true;\n  for (let d = 2; d * d <= n; d++) if (n % d === 0) { prime = false; break; }\n  if (!prime) continue;\n  if (H0.length < 8) H0.push(Math.floor((Math.sqrt(n) % 1) * 4294967296) | 0);\n  K.push(Math.floor((Math.cbrt(n) % 1) * 4294967296) | 0);\n}\nfunction sha256(bytes) {\n  const length = bytes.length;\n  const padded = Buffer.alloc(((length + 72) >> 6) << 6);\n  Buffer.from(bytes).copy(padded);\n  padded[length] = 0x80;\n  padded.writeUInt32BE(Math.floor(length / 0x20000000), padded.length - 8);\n  padded.writeUInt32BE((length << 3) >>> 0, padded.length - 4);\n  const h = H0.slice(), w = new Array(64);\n  const rotr = (x, n) => (x >>> n) | (x << (32 - n));\n  for (let offset = 0; offset < padded.length; offset += 64) {\n    for (let t = 0; t < 16; t++) w[t] = padded.readInt32BE(offset + t * 4);\n    for (let t = 16; t < 64; t++) {\n      const s0 = rotr(w[t - 15], 7) ^ rotr(w[t - 15], 18) ^ (w[t - 15] >>> 3);\n      const s1 = rotr(w[t - 2], 17) ^ rotr(w[t - 2], 19) ^ (w[t - 2] >>> 10);\n      w[t] = (w[t - 16] + s0 + w[t - 7] + s1) | 0;\n    }\n    let [a, b, c, d, e, f, g, hh] = h;\n    for (let t = 0; t < 64; t++) {\n      const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[t] + w[t]) | 0;\n      const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;\n      hh = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;\n    }\n    [a, b, c, d, e, f, g, hh].forEach((value, i) => { h[i] = (h[i] + value) | 0; });\n  }\n  const out = Buffer.alloc(32);\n  h.forEach((value, i) => out.writeInt32BE(value, i * 4));\n  return out;\n}\nfunction hmacSha256(key, message) {\n  if (key.length > 64) key = sha256(key);\n  const inner = Buffer.alloc(64, 0x36), outer = Buffer.alloc(64, 0x5c);\n  for (let i = 0; i < key.length; i++) { inner[i] ^= key[i]; outer[i] ^= key[i]; }\n  return sha256(Buffer.concat([outer, sha256(Buffer.concat([inner, message]))]));\n}\n\nconst key = Buffer.from(SECRET.replace(/^whsec_/, ''), 'base64');\nconst expected = hmacSha256(key, Buffer.concat([Buffer.from(id + '.' + timestamp + '.'), raw]));\n// While a secret is being rotated WhatSync sends two signatures, separated by a space. Either may match.\nconst valid = String(headers['webhook-signature'] || '').split(' ').some((entry) => {\n  const [version, encoded] = entry.split(',');\n  const actual = Buffer.from(encoded || '', 'base64');\n  if (version !== 'v1' || actual.length !== expected.length) return false;\n  let difference = 0;\n  for (let i = 0; i < expected.length; i++) difference |= actual[i] ^ expected[i];\n  return difference === 0;\n});\nif (!valid) throw new Error('Rejected: the WhatSync signature does not match. Check the signing secret.');\n\n// From here on the item is the event itself: id, type, created_at, data.\nreturn [{ json: item.json.body }];\n"
      },
      "name": "Verify signature",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "id": "e5d95b8d-1404-4b87-a700-4e3e9c58c6b6"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "60250461-7aff-49e0-a332-d1cbea709b14",
              "leftValue": "={{ $json.type }}",
              "rightValue": "^message\\.(received|sent)$",
              "operator": {
                "type": "string",
                "operation": "regex"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "A message?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        0
      ],
      "id": "ff712b26-3c3e-4847-a7c2-1eecff72974c"
    },
    {
      "parameters": {
        "operation": "removeItemsSeenInPreviousExecutions",
        "logic": "removeItemsWithAlreadySeenKeyValues",
        "dedupeValue": "={{ $json.id }}",
        "options": {
          "scope": "workflow",
          "historySize": 10000
        }
      },
      "name": "Skip repeats",
      "type": "n8n-nodes-base.removeDuplicates",
      "typeVersion": 2,
      "position": [
        660,
        0
      ],
      "id": "f6b37a42-4e3b-4f6d-adf9-b9d3cadb2763",
      "notes": "Remembers the last 10,000 event ids across runs and drops an event it has already seen."
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "2f23c9bd-c8df-451e-ad69-c95e361c46ff",
              "name": "Time",
              "value": "={{ $json.data.message.timestamp }}",
              "type": "string"
            },
            {
              "id": "bf226cae-1ed4-4141-aee9-3377276d117d",
              "name": "Direction",
              "value": "={{ $json.data.message.from_me ? 'sent' : 'received' }}",
              "type": "string"
            },
            {
              "id": "6d373560-e03b-4c43-a8f5-43511237bb5c",
              "name": "Chat",
              "value": "={{ $json.data.message.chat_type === 'group' ? ($json.data.message.group.name || $json.data.message.group.id) : $json.data.message.conversation_id.split('@')[0] }}",
              "type": "string"
            },
            {
              "id": "9414b6c5-41e8-4b9b-aacd-fa6bf301f945",
              "name": "From",
              "value": "={{ $json.data.message.from.phone || '' }}",
              "type": "string"
            },
            {
              "id": "82b1475f-468e-4e82-aea6-07b66670942a",
              "name": "Name",
              "value": "={{ $json.data.message.from.name || '' }}",
              "type": "string"
            },
            {
              "id": "9a2a0574-b816-4f81-a4ff-ad83c11fa2b1",
              "name": "Type",
              "value": "={{ $json.data.message.type }}",
              "type": "string"
            },
            {
              "id": "03907f37-3981-49d8-afbb-6bf8da4c064b",
              "name": "Text",
              "value": "={{ $json.data.message.text || '' }}",
              "type": "string"
            },
            {
              "id": "6cf0d76a-63fd-4414-a2a3-3b7b6d4ddf89",
              "name": "Has file",
              "value": "={{ $json.data.message.has_attachment ? 'yes' : 'no' }}",
              "type": "string"
            },
            {
              "id": "89b2c4d9-e7a7-4003-ab59-a1138fd7bc83",
              "name": "Message ID",
              "value": "={{ $json.data.message.stored_message_id }}",
              "type": "string"
            },
            {
              "id": "96b00137-0dc1-4a83-a9a6-efbdb9cf8c94",
              "name": "Event ID",
              "value": "={{ $json.id }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "name": "Row",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        880,
        0
      ],
      "id": "a3ddd0db-ff16-4d2e-a90c-719c54196731",
      "notes": "One column per field. The sheet's first row must use exactly these names: Time, Direction, Chat, From, Name, Type, Text, Has file, Message ID, Event ID."
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "sheetName": {
          "__rl": true,
          "value": "",
          "mode": "list"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "name": "Add row to sheet",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        0
      ],
      "id": "65def5f7-c796-4918-aed5-e37685ffeeeb",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "GOOGLE_SHEETS_CREDENTIAL",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Log every WhatsApp message to Google Sheets\nEach message you receive or send in a saved chat becomes one row. It only reads. It never sends a WhatsApp message.\n\n**Set up**\n1. Make a sheet whose first row is: Time, Direction, Chat, From, Name, Type, Text, Has file, Message ID, Event ID.\n2. Paste your webhook signing secret into **Verify signature**.\n3. In **Add row to sheet**, pick your Google account, the document and the sheet.\n4. Publish, then add the production webhook URL in WhatSync > Developers with the events message.received and message.sent.\n\nAnother CRM or database? Replace the last node. The **Row** node already has clean fields.\nGuide: https://whatsync.app/docs/guides/log-messages-to-google-sheets",
        "height": 280,
        "width": 600,
        "color": 4
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -360
      ],
      "id": "1408ceee-6366-42c2-aa15-2e592e73896a"
    }
  ],
  "connections": {
    "WhatsApp event": {
      "main": [
        [
          {
            "node": "Verify signature",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify signature": {
      "main": [
        [
          {
            "node": "A message?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "A message?": {
      "main": [
        [
          {
            "node": "Skip repeats",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip repeats": {
      "main": [
        [
          {
            "node": "Row",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Row": {
      "main": [
        [
          {
            "node": "Add row to sheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
