{
  "name": "Capture website chatbot leads in Mailchimp with opt-in consent using OpenAI",
  "nodes": [
    {
      "parameters": {
        "content": "## Capture website chatbot leads in Mailchimp with opt-in consent using OpenAI\n\nFor teams that want chatbot leads stored in a Mailchimp audience, without subscribing anyone who has not clearly agreed.\n\n### How it works\n1. A webhook receives the widget message and checks a shared secret.\n2. An OpenAI agent answers from your knowledge text and asks for an email when there is a reason.\n3. The capture lead tool upserts the member with one request. Without consent they are stored as transactional, not subscribed.\n4. After a separate, explicit yes, a second call sets them to subscribed.\n\n### Setup\n- [ ] Edit **Chatbot settings**: company name, your knowledge text and a random `webhook_secret`.\n- [ ] Add your OpenAI credential to **GPT-4.1 mini model**.\n- [ ] Copy each tool section below the main flow into its own new workflow, save it, then select it in the matching tool node.\n- [ ] In each tool workflow, add your Mailchimp credential and fill in **Tool settings**.\n- [ ] Test with a POST to the webhook Test URL (the n8n chat panel needs a Chat Trigger). Then activate and add the production URL to your widget, with the same secret as `metadata.webhook_secret`.\n\n### Requirements\nn8n, an OpenAI API key and a Mailchimp API key, data centre and audience ID.\n\n### Customization tips\nChange merge fields or the prompt wording. Confirm the transactional status behaves as you expect in your account.",
        "width": 480,
        "height": 1104
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -560,
        0
      ],
      "id": "766bb4aa-2f54-4008-a861-8e52cf2cef65",
      "name": "Template overview"
    },
    {
      "parameters": {
        "content": "## 1. Receive and verify the message\nThe webhook takes the widget message. Requests without your secret are rejected.",
        "width": 944,
        "height": 432,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "id": "c158ecc3-42af-4b3c-8349-6629183f063e",
      "name": "Section 1: Receive and verify the message"
    },
    {
      "parameters": {
        "content": "## 2. Answer with the AI agent\nThe agent answers from your settings, remembers the session and calls its tools when needed.",
        "width": 704,
        "height": 512,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        528
      ],
      "id": "9ebcd5f9-eed0-4537-9efb-4e5a09ac41ca",
      "name": "Section 2: Answer with the AI agent"
    },
    {
      "parameters": {
        "content": "## 3. Tool: capture_lead (copy to its own workflow)\nCopy these nodes into a new workflow and save it. Then select that workflow in the capture_lead tool node.",
        "width": 1120,
        "height": 576,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        1136
      ],
      "id": "dc201232-4aa1-4aa3-9c58-f905a2cacf8c",
      "name": "Section 3: Tool: capture_lead (copy to its own workflow)"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "mailchimp-lead-capture",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook",
      "name": "Chat webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        64,
        112
      ],
      "webhookId": "mailchimp-lead-capture-webhook"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "company_name",
              "value": "Your Company",
              "type": "string"
            },
            {
              "id": "c3",
              "name": "consent_wording",
              "value": "Want me to add you to our monthly update email as well? One click to unsubscribe any time.",
              "type": "string"
            },
            {
              "id": "c4",
              "name": "knowledge",
              "value": "PASTE YOUR FAQ OR SERVICES COPY HERE.\n\nThe bot answers only from this text.",
              "type": "string"
            },
            {
              "id": "c5",
              "name": "webhook_secret",
              "value": "CHANGE_ME_TO_A_RANDOM_STRING",
              "type": "string"
            },
            {
              "id": "c6",
              "name": "message",
              "value": "={{ $json.body.chatInput || $json.body.message || '' }}",
              "type": "string"
            },
            {
              "id": "c7",
              "name": "session_id",
              "value": "={{ $json.body.sessionId || 'no-session' }}",
              "type": "string"
            },
            {
              "id": "c8",
              "name": "page_url",
              "value": "={{ $json.body.metadata?.page_url || '' }}",
              "type": "string"
            },
            {
              "id": "c9",
              "name": "sent_secret",
              "value": "={{ $json.body.metadata?.webhook_secret || (typeof $json.body.metadata === 'string' ? ($json.body.metadata.match(/\"webhook_secret\"\\s*:\\s*\"([^\"]*)\"/) || [])[1] : '') || '' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "config",
      "name": "Chatbot settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        304,
        112
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "sec1",
              "leftValue": "={{ $json.sent_secret }}",
              "rightValue": "={{ $json.webhook_secret }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-secret",
      "name": "Request from your widget?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        544,
        112
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ output: 'Sorry, something went wrong. Please try again later.' }) }}",
        "options": {
          "responseCode": 401
        }
      },
      "id": "reject",
      "name": "Reject unknown requests",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        784,
        272
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.message }}",
        "options": {
          "systemMessage": "=You are the assistant on {{ $json.company_name }}'s website. Answer visitor questions accurately and, where appropriate, capture their details.\n\nWHAT YOU KNOW\n{{ $json.knowledge }}\n\nANSWERING\n- Answer only from the information above. Never invent pricing, availability, or capability.\n\nCAPTURING DETAILS\n- Do not ask for an email in your first reply. Answer their question first.\n- Ask only when there is a reason: they cannot be answered, want a demo, or ask to be contacted.\n\nCONSENT - follow this exactly\n- Taking an email so a human can answer their question is one thing. Adding them to the marketing list is separate and needs its own explicit yes.\n- When you have an email and a reason to save it, call capture_lead with consent_given false.\n- Only afterwards, if warranted, ask separately using this wording: \"{{ $json.consent_wording }}\"\n- If and only if they clearly say yes, call capture_lead again with consent_given true.\n- Ambiguity is NOT consent. Never bundle the two asks.\n\nAlways pass session_id \"{{ $json.session_id }}\" and page_url \"{{ $json.page_url }}\".\n\nTONE\n- Short. Plain. No exclamation marks."
        }
      },
      "id": "agent",
      "name": "Answer questions and capture leads",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        64,
        640
      ]
    },
    {
      "parameters": {
        "model": "gpt-4.1-mini",
        "options": {}
      },
      "id": "model",
      "name": "GPT-4.1 mini model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        64,
        880
      ]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Chatbot settings').item.json.session_id }}",
        "contextWindowLength": 20
      },
      "id": "memory",
      "name": "Conversation memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        304,
        880
      ]
    },
    {
      "parameters": {
        "name": "capture_lead",
        "description": "Save a lead to Mailchimp. Call with consent_given false when you first get an email. Call a second time with consent_given true ONLY after a separate explicit yes to marketing.",
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "PASTE_THE_CAPTURE_LEAD_WORKFLOW_ID_HERE",
          "cachedResultName": "capture_lead (Mailchimp)"
        },
        "specifyInputSchema": true,
        "jsonSchemaExample": "{\n  \"email\": \"sam@example.com\",\n  \"first_name\": \"Sam\",\n  \"last_name\": \"\",\n  \"consent_given\": false,\n  \"summary\": \"Asked about X. Wants a callback.\",\n  \"session_id\": \"\",\n  \"page_url\": \"\"\n}"
      },
      "id": "tool-capture",
      "name": "capture_lead",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "typeVersion": 1.2,
      "position": [
        544,
        880
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ output: $json.output }) }}",
        "options": {}
      },
      "id": "respond",
      "name": "Respond to widget",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        544,
        640
      ]
    },
    {
      "parameters": {
        "inputSource": "passthrough"
      },
      "id": "sub-trigger",
      "name": "When called by the agent",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "typeVersion": 1.1,
      "position": [
        64,
        1388
      ]
    },
    {
      "parameters": {
        "jsCode": "// Pure-JS MD5 - no require('crypto'), which is blocked by default in n8n's\n// Code node on most instances (including n8n Cloud) unless an admin has set\n// NODE_FUNCTION_ALLOW_BUILTIN=crypto on the server itself. Verified against\n// Python's hashlib.md5 for correctness before use here.\nfunction md5(str) {\n  function rotl(n, s) { return (n << s) | (n >>> (32 - s)); }\n  function toHex(n) {\n    let s = '';\n    for (let i = 0; i < 4; i++) { s += ((n >> (i * 8)) & 0xff).toString(16).padStart(2, '0'); }\n    return s;\n  }\n  const K = [];\n  for (let i = 0; i < 64; i++) { K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) | 0; }\n  const S = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];\n  const bytes = [];\n  const utf8 = unescape(encodeURIComponent(str));\n  for (let i = 0; i < utf8.length; i++) bytes.push(utf8.charCodeAt(i) & 0xff);\n  const bitLen = bytes.length * 8;\n  bytes.push(0x80);\n  while (bytes.length % 64 !== 56) bytes.push(0);\n  for (let i = 0; i < 8; i++) { bytes.push((bitLen / Math.pow(2, 8 * i)) & 0xff); }\n  let a0 = 0x67452301, b0 = 0xefcdab89, c0 = 0x98badcfe, d0 = 0x10325476;\n  for (let chunkStart = 0; chunkStart < bytes.length; chunkStart += 64) {\n    const M = [];\n    for (let i = 0; i < 16; i++) {\n      M[i] = bytes[chunkStart + i*4] | (bytes[chunkStart + i*4 + 1] << 8) | (bytes[chunkStart + i*4 + 2] << 16) | (bytes[chunkStart + i*4 + 3] << 24);\n    }\n    let A = a0, B = b0, C = c0, D = d0;\n    for (let i = 0; i < 64; i++) {\n      let F, g;\n      if (i < 16) { F = (B & C) | (~B & D); g = i; }\n      else if (i < 32) { F = (D & B) | (~D & C); g = (5*i + 1) % 16; }\n      else if (i < 48) { F = B ^ C ^ D; g = (3*i + 5) % 16; }\n      else { F = C ^ (B | ~D); g = (7*i) % 16; }\n      F = (F + A + K[i] + M[g]) | 0;\n      A = D; D = C; C = B;\n      B = (B + rotl(F, S[i])) | 0;\n    }\n    a0 = (a0 + A) | 0; b0 = (b0 + B) | 0; c0 = (c0 + C) | 0; d0 = (d0 + D) | 0;\n  }\n  return [a0, b0, c0, d0].map(toHex).join('');\n}\n\nconst q = $input.first().json.query ?? $input.first().json;\nconst d = typeof q === 'string' ? JSON.parse(q) : q;\n\nconst email = String(d.email || '').trim().toLowerCase();\nconst valid = /^[^@\\s]+@[^@\\s]+\\.[^@\\s]{2,}$/.test(email);\n\nconst subscriberHash = valid ? md5(email) : '';\n\nreturn [{ json: {\n  valid,\n  email,\n  subscriber_hash: subscriberHash,\n  first_name: d.first_name || '',\n  last_name: d.last_name || '',\n  consent_given: d.consent_given === true || d.consent_given === 'true',\n  summary: d.summary || '',\n  session_id: d.session_id || '',\n  page_url: d.page_url || ''\n} }];"
      },
      "id": "parse-input",
      "name": "Parse and validate",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        284,
        1388
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "v1",
              "leftValue": "={{ $json.valid }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-valid",
      "name": "Valid email?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        504,
        1388
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "e1",
              "name": "response",
              "value": "That email address doesn't look valid. Ask them to confirm it, then try again. Nothing has been saved.",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "invalid-response",
      "name": "Tell the agent it failed",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        724,
        1548
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "s1",
              "name": "mailchimp_datacenter",
              "value": "PASTE_YOUR_DATACENTER_HERE",
              "type": "string"
            },
            {
              "id": "s2",
              "name": "list_id",
              "value": "PASTE_YOUR_LIST_ID_HERE",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "sub-config",
      "name": "Tool settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        504,
        1248
      ]
    },
    {
      "parameters": {
        "method": "PUT",
        "url": "={{ 'https://' + $json.mailchimp_datacenter + '.api.mailchimp.com/3.0/lists/' + $json.list_id + '/members/' + $json.subscriber_hash }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ email_address: $json.email, status_if_new: $json.consent_given ? 'subscribed' : 'transactional', ...( $json.consent_given ? { status: 'subscribed' } : {} ), merge_fields: { FNAME: $json.first_name, LNAME: $json.last_name } }) }}",
        "options": {
          "response": {
            "response": {
              "neverError": true,
              "fullResponse": true
            }
          }
        }
      },
      "id": "upsert-member",
      "name": "Upsert Mailchimp member",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        744,
        1248
      ]
    },
    {
      "parameters": {
        "jsCode": "// [Worth verifying] - 'transactional' as a status_if_new value is a real\n// Mailchimp member status (added for e-commerce contacts who haven't opted\n// into marketing), used here as the pre-consent state. Confirm current\n// allowed values against Mailchimp's docs before relying on this in production.\nconst full = $input.first().json;\nconst statusCode = full.statusCode || 200;\nconst body = full.body || full;\n\nif (statusCode >= 400) {\n  return [{ json: { response: \"Something went wrong saving that. Don't retry silently - let the visitor know a human will follow up by email instead.\" } }];\n}\n\nconst consentGiven = $('Parse and validate').first().json.consent_given;\n\nreturn [{ json: {\n  response: consentGiven\n    ? 'Saved and subscribed to the marketing list with consent recorded.'\n    : 'Saved. NOT subscribed to any marketing list.'\n} }];"
      },
      "id": "format-response",
      "name": "Format response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        964,
        1248
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Chat webhook": {
      "main": [
        [
          {
            "node": "Chatbot settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chatbot settings": {
      "main": [
        [
          {
            "node": "Request from your widget?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Request from your widget?": {
      "main": [
        [
          {
            "node": "Answer questions and capture leads",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reject unknown requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Answer questions and capture leads": {
      "main": [
        [
          {
            "node": "Respond to widget",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4.1 mini model": {
      "ai_languageModel": [
        [
          {
            "node": "Answer questions and capture leads",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Conversation memory": {
      "ai_memory": [
        [
          {
            "node": "Answer questions and capture leads",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "capture_lead": {
      "ai_tool": [
        [
          {
            "node": "Answer questions and capture leads",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "When called by the agent": {
      "main": [
        [
          {
            "node": "Parse and validate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse and validate": {
      "main": [
        [
          {
            "node": "Valid email?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Valid email?": {
      "main": [
        [
          {
            "node": "Tool settings",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Tell the agent it failed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tool settings": {
      "main": [
        [
          {
            "node": "Upsert Mailchimp member",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upsert Mailchimp member": {
      "main": [
        [
          {
            "node": "Format response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "tags": []
}