AutomationFlowsMarketing & Ads › Segment Woocommerce Customers for Targeted Marketing with Rfm Analysis

Segment Woocommerce Customers for Targeted Marketing with Rfm Analysis

ByMohammadreza azari @mrazari on n8n.io

This workflow is designed for eCommerce store owners and marketing teams who use WooCommerce. It helps segment customers based on their purchasing behavior using the RFM (Recency, Frequency, Monetary) model. By identifying high-value customers, new buyers, and at-risk segments,…

Cron / scheduled trigger★★★★☆ complexity7 nodesStartWooCommerce
Marketing & Ads Trigger: Cron / scheduled Nodes: 7 Complexity: ★★★★☆ Added:

This workflow corresponds to n8n.io template #4880 — we link there as the canonical source.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "5db1ea37-aa49-4081-8fd0-fa9416cbcff4",
      "name": "Manual Start",
      "type": "n8n-nodes-base.start",
      "position": [
        0,
        0
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "c6c0b7d2-e1d4-442d-aff5-b206426411bc",
      "name": "Weekly Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        0,
        200
      ],
      "parameters": {
        "rule": {
          "interval": [
            {}
          ]
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "e00baa15-fd2c-444b-9c31-189d6b9986c7",
      "name": "Fetch Orders From WooCommerce",
      "type": "n8n-nodes-base.wooCommerce",
      "position": [
        200,
        0
      ],
      "parameters": {
        "options": {
          "after": "={{ $now.minus(1, 'year').toISO() }}",
          "status": "completed"
        },
        "resource": "order",
        "operation": "getAll",
        "returnAll": true
      },
      "credentials": {
        "wooCommerceApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "ef5905d0-4db8-4e57-bc4e-44b72d3bf4a6",
      "name": "Compute RFM Segmentation",
      "type": "n8n-nodes-base.code",
      "position": [
        480,
        0
      ],
      "parameters": {
        "jsCode": "// Group orders by customer and calculate RFM\nconst orders = $input.all();\nconst customers = {};\nconst today = new Date();\n\n// Process orders\norders.forEach(order => {\n  const customerId = order.json.customer_id || order.json.billing.email;\n  if (!customerId) return;\n  \n  if (!customers[customerId]) {\n    customers[customerId] = {\n      customerId: customerId,\n      customerName: `${order.json.billing.first_name} ${order.json.billing.last_name}`,\n      email: order.json.billing.email,\n      orders: [],\n      totalSpent: 0,\n      orderCount: 0\n    };\n  }\n  \n  const orderDate = new Date(order.json.date_created);\n  customers[customerId].orders.push({\n    date: orderDate,\n    total: parseFloat(order.json.total)\n  });\n  customers[customerId].totalSpent += parseFloat(order.json.total);\n  customers[customerId].orderCount++;\n});\n\n// Calculate RFM values\nconst customerData = Object.values(customers).map(customer => {\n  // Recency: Number of days since last purchase\n  const lastOrderDate = Math.max(...customer.orders.map(o => o.date));\n  const recency = Math.floor((today - new Date(lastOrderDate)) / (1000 * 60 * 60 * 24));\n  \n  // Frequency: Number of orders\n  const frequency = customer.orderCount;\n  \n  // Monetary: Total spent\n  const monetary = customer.totalSpent;\n  \n  return {\n    customerId: customer.customerId,\n    customerName: customer.customerName,\n    email: customer.email,\n    recency: recency,\n    frequency: frequency,\n    monetary: monetary,\n    lastOrderDate: new Date(lastOrderDate).toISOString().split('T')[0]\n  };\n});\n\n// Sort for quartile calculations\nconst sortedByRecency = [...customerData].sort((a, b) => a.recency - b.recency);\nconst sortedByFrequency = [...customerData].sort((a, b) => b.frequency - a.frequency);\nconst sortedByMonetary = [...customerData].sort((a, b) => b.monetary - a.monetary);\n\n// Quartile calculation helper\nfunction getQuartile(sortedArray, value, field, ascending = false) {\n  const index = sortedArray.findIndex(item => item[field] === value);\n  const quartile = Math.ceil((index + 1) / sortedArray.length * 4);\n  return ascending ? quartile : 5 - quartile;\n}\n\n// Assign RFM scores\nconst rfmScores = customerData.map(customer => {\n  const rScore = getQuartile(sortedByRecency, customer.recency, 'recency', true);\n  const fScore = getQuartile(sortedByFrequency, customer.frequency, 'frequency');\n  const mScore = getQuartile(sortedByMonetary, customer.monetary, 'monetary');\n  \n  const rfmScore = `${rScore}${fScore}${mScore}`;\n  \n  // Determine segment\n  let segment = '';\n  if (rScore >= 4 && fScore >= 4 && mScore >= 4) {\n    segment = 'Champions';\n  } else if (rScore >= 3 && fScore >= 3 && mScore >= 4) {\n    segment = 'Loyal Customers';\n  } else if (rScore >= 3 && fScore >= 1 && mScore >= 3) {\n    segment = 'Potential Loyalists';\n  } else if (rScore >= 4 && fScore <= 2) {\n    segment = 'New Customers';\n  } else if (rScore >= 3 && fScore >= 3 && mScore <= 2) {\n    segment = 'Promising';\n  } else if (rScore <= 2 && fScore >= 3) {\n    segment = 'Need Attention';\n  } else if (rScore <= 2 && fScore <= 2 && mScore >= 3) {\n    segment = 'About to Sleep';\n  } else if (rScore <= 2 && fScore >= 3 && mScore >= 3) {\n    segment = 'At Risk';\n  } else if (rScore <= 2 && fScore <= 2 && mScore <= 2) {\n    segment = 'Lost';\n  } else {\n    segment = 'Others';\n  }\n  \n  return {\n    ...customer,\n    rScore,\n    fScore,\n    mScore,\n    rfmScore,\n    segment,\n    avgOrderValue: customer.monetary / customer.frequency\n  };\n});\n\nreturn rfmScores;\n"
      },
      "typeVersion": 2
    },
    {
      "id": "5702ae22-50a8-4a53-9fef-593a9e4c8001",
      "name": "Generate Segment Summary",
      "type": "n8n-nodes-base.code",
      "position": [
        840,
        0
      ],
      "parameters": {
        "jsCode": "const items = $input.all();\n\n// Segment translation and priority definitions\nconst segmentDetails = {\n  'Champions': { fa: 'Champions', priority: 1, action: 'Send VIP offer and exclusive discount code' },\n  'Loyal Customers': { fa: 'Loyal Customers', priority: 2, action: 'Invite to loyalty club and introduce new products' },\n  'Potential Loyalists': { fa: 'Potential Loyalists', priority: 3, action: 'Encourage more interaction and suggest complementary products' },\n  'New Customers': { fa: 'New Customers', priority: 4, action: 'Send welcome message and encourage second purchase' },\n  'Promising': { fa: 'Promising', priority: 5, action: 'Send product reminders and additional education' },\n  'Need Attention': { fa: 'Need Attention', priority: 6, action: 'Investigate reasons for inactivity and send comeback campaign' },\n  'About to Sleep': { fa: 'About to Sleep', priority: 7, action: 'Send new products and return incentives' },\n  'At Risk': { fa: 'At Risk', priority: 8, action: 'Send personalized message with heavy discount' },\n  'Lost': { fa: 'Lost', priority: 9, action: 'Offer return deal and \"We Miss You\" campaign' },\n  'Others': { fa: 'Others', priority: 10, action: 'Manual review for behavior analysis' },\n};\n\n// Count customers per segment\nconst segmentCounts = {};\n\nfor (const item of items) {\n  const seg = item.json.segment || 'Others';\n  if (!segmentCounts[seg]) segmentCounts[seg] = 0;\n  segmentCounts[seg]++;\n}\n\n// Build HTML table\nlet html = `\n<h2 style=\"text-align: center;\">RFM Summary Report - ${new Date().toISOString().split('T')[0]}</h2>\n<table border=\"1\" cellpadding=\"8\" cellspacing=\"0\" style=\"width:90%; margin:auto; border-collapse:collapse; font-family:sans-serif;\">\n  <thead style=\"background:#e6f2ff;\">\n    <tr>\n      <th>Segment</th>\n      <th>Customer Count</th>\n      <th>Marketing Suggestion</th>\n    </tr>\n  </thead>\n  <tbody>\n`;\n\nObject.entries(segmentCounts)\n  .map(([key, count]) => ({\n    key,\n    count,\n    priority: segmentDetails[key]?.priority || 999,\n    label: segmentDetails[key]?.fa || key,\n    action: segmentDetails[key]?.action || '-'\n  }))\n  .sort((a, b) => a.priority - b.priority)\n  .forEach(({ label, count, action }) => {\n    html += `\n      <tr>\n        <td>${label}</td>\n        <td>${count}</td>\n        <td>${action}</td>\n      </tr>\n    `;\n  });\n\nhtml += `\n  </tbody>\n</table>\n`;\n\nreturn [{ json: { html } }];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "4b4993f8-25d0-4109-bec7-41902c065eb3",
      "name": "Build Report Page",
      "type": "n8n-nodes-base.html",
      "position": [
        1120,
        0
      ],
      "parameters": {
        "html": "<head>\n  <meta charset=\"UTF-8\">\n  <style>\n    body {\n      font-family: sans-serif;\n      background-color: #f7f7f7;\n      padding: 20px;\n    }\n    h2 {\n      text-align: center;\n      color: #333;\n    }\n    table {\n      width: 100%;\n      border-collapse: collapse;\n      margin-top: 20px;\n      background-color: #fff;\n    }\n    th, td {\n      border: 1px solid #ccc;\n      padding: 8px 12px;\n      font-size: 14px;\n      text-align: center;\n    }\n    th {\n      background-color: #e6f2ff;\n    }\n    tr:nth-child(even) {\n      background-color: #f9f9f9;\n    }\n    .segment {\n      font-weight: bold;\n      color: #2e7d32;\n    }\n  </style>\n</head>\n{{ $json.html }}\n"
      },
      "typeVersion": 1.2
    },
    {
      "id": "76665a4f-a27d-42a2-81dd-4e62411a7129",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        -460
      ],
      "parameters": {
        "width": 740,
        "height": 440,
        "content": "## \ud83d\udee0\ufe0f Setup Instructions for This Workflow\n\nBefore running this workflow, make sure to do the following:\n\n1. **Connect Your WooCommerce Store**  \n   Go to the `Fetch Orders From WooCommerce` node and replace the placeholder credentials with your own WooCommerce API credentials.\n\n2. **(Optional) Customize RFM Logic**  \n   If needed, update the segmentation rules inside the `Compute RFM Segmentation` node.\n\n3. **(Optional) Edit Marketing Suggestions**  \n   You can change the text of recommended actions in the `Generate Segment Summary` node.\n\nOnce configured, use the `Manual Start` for testing or enable the `Weekly Trigger` for automation.\n\nEnjoy your customer insights! \ud83c\udfaf\n"
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "Manual Start": {
      "main": [
        [
          {
            "node": "Fetch Orders From WooCommerce",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Weekly Trigger": {
      "main": [
        [
          {
            "node": "Fetch Orders From WooCommerce",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compute RFM Segmentation": {
      "main": [
        [
          {
            "node": "Generate Segment Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Segment Summary": {
      "main": [
        [
          {
            "node": "Build Report Page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Orders From WooCommerce": {
      "main": [
        [
          {
            "node": "Compute RFM Segmentation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

This workflow is designed for eCommerce store owners and marketing teams who use WooCommerce. It helps segment customers based on their purchasing behavior using the RFM (Recency, Frequency, Monetary) model. By identifying high-value customers, new buyers, and at-risk segments,…

Source: https://n8n.io/workflows/4880/ — original creator credit. Request a take-down →

More Marketing & Ads workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

Marketing & Ads

Workflow A — WhatsApp Lead Intake & Qualification. Uses postgres, httpRequest, errorTrigger. Scheduled trigger; 67 nodes.

Postgres, HTTP Request, Error Trigger
Marketing & Ads

Build authentic Reddit presence and generate qualified leads through AI-powered community engagement that provides genuine value without spam or promotion.

HTTP Request, Reddit
Marketing & Ads

This workflow runs on scheduled weekly and monthly triggers to generate unified marketing performance reports. It processes multiple websites by collecting analytics data, paid ads performance, and CR

Gmail, Google Sheets, Google Analytics +3
Marketing & Ads

Fetch Multiple Google Analytics GA4 metrics daily, post to Discord, update previous day’s entry as GA data finalizes over seven days. Automates daily traffic reporting Maintains single message per day

Google Analytics, Discord, HTTP Request
Marketing & Ads

This workflow automates the daily backfill of Google Analytics 4 (GA4) data into BigQuery. It fetches 13 essential pre-processed reports (including User Acquisition, Traffic, and E-commerce) and uploa

Google Analytics, Google BigQuery, Telegram