MinAI - Về trang chủ
Lý thuyết
11/1345 phút
Đang tải...

Lead Generation

Automate lead generation với n8n - Form handling, CRM integration, lead scoring, nurturing workflows

🎯 Lead Generation

Lead Generation

0

🎯 Mục tiêu bài học

TB5 min

Sau bài học này, bạn sẽ:

✅ Xây dựng form submission handler với data validation

✅ Implement lead enrichment và lead scoring system

✅ Tạo CRM integration và email nurture sequences

✅ Thiết kế hot lead alerts và sales handoff workflow

Convert visitors into customers automatically. Bài này hướng dẫn automate entire lead generation funnel từ capture đến conversion.

1

🔍 Lead Generation Automation Overview

TB5 min

The Lead Funnel:

Lead Generation Funnel

🎯Lead Funnel
🧲ATTRACT
Content marketing
Ads & campaigns
Social media
SEO/organic
📋CAPTURE
Landing pages
Forms & pop-ups
Lead magnets
Chatbots
QUALIFY
Lead scoring
Data enrichment
Segmentation
Fit analysis
💌NURTURE
Email sequences
Retargeting
Content delivery
Sales touches
🤝CONVERT
Sales handoff
Demo booking
Proposal
Close

Checkpoint

Lead funnel bao gồm mấy giai đoạn chính?

2

⚡ Workflow 1: Form Submission Handler

TB5 min

Process Lead Forms:

Lead Form Handler

📥Webhook: Form Submission
Validate & Clean Data
🔍Check for Duplicates
🔄Existing → Update & Tag
New → Enrich, Score & CRM
📧Send Confirmation Email
🔔Notify Sales if High Score
💌Start Nurture Sequence

Form Data Processing:

JavaScript
1const formData = $input.item.json;
2
3// Clean and validate
4function cleanData(data) {
5 return {
6 email: data.email?.toLowerCase().trim(),
7 firstName: data.firstName?.trim() || data.name?.split(' ')[0]?.trim(),
8 lastName: data.lastName?.trim() || data.name?.split(' ').slice(1).join(' ')?.trim(),
9 company: data.company?.trim(),
10 phone: data.phone?.replace(/[^\d+]/g, ''),
11 jobTitle: data.jobTitle?.trim(),
12
13 // Form context
14 source: data.source || 'website',
15 formId: data.formId,
16 landingPage: data.pageUrl,
17 utmSource: data.utm_source,
18 utmMedium: data.utm_medium,
19 utmCampaign: data.utm_campaign,
20
21 // Timestamps
22 submittedAt: new Date().toISOString(),
23 ip: data.ip,
24 userAgent: data.userAgent
25 };
26}
27
28// Validate required fields
29function validate(data) {
30 const errors = [];
31
32 if (!data.email || !data.email.includes('@')) {
33 errors.push('Invalid email');
34 }
35
36 if (!data.firstName) {
37 errors.push('First name required');
38 }
39
40 return {
41 isValid: errors.length === 0,
42 errors
43 };
44}
45
46const cleaned = cleanData(formData);
47const validation = validate(cleaned);
48
49return {
50 ...cleaned,
51 ...validation,
52 processingId: `lead_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
53};

Checkpoint

Form submission handler thực hiện validate và clean data như thế nào?

3

🔧 Workflow 2: Lead Enrichment

TB5 min

Enrich Lead Data:

Lead Enrichment

🆕New Lead Created
🔍Clearbit Enrichment
💼LinkedIn Lookup
💾Update Lead Record
📊Recalculate Lead Score

Enrichment Processing:

JavaScript
1const lead = $input.item.json;
2
3// Combine enrichment data from various sources
4const enrichedData = {
5 // From Clearbit or similar
6 company: {
7 name: lead.clearbit?.company?.name || lead.company,
8 domain: lead.clearbit?.company?.domain,
9 industry: lead.clearbit?.company?.category?.industry,
10 employeeCount: lead.clearbit?.company?.metrics?.employees,
11 annualRevenue: lead.clearbit?.company?.metrics?.annualRevenue,
12 founded: lead.clearbit?.company?.foundedYear,
13 location: {
14 city: lead.clearbit?.company?.geo?.city,
15 country: lead.clearbit?.company?.geo?.country
16 },
17 technologies: lead.clearbit?.company?.tech || [],
18 linkedInUrl: lead.clearbit?.company?.linkedin?.handle
19 ? `https://linkedin.com/company/${lead.clearbit.company.linkedin.handle}`
20 : null
21 },
22
23 // Person data
24 person: {
25 fullName: lead.clearbit?.person?.name?.fullName || `${lead.firstName} ${lead.lastName}`,
26 title: lead.clearbit?.person?.employment?.title || lead.jobTitle,
27 seniority: lead.clearbit?.person?.employment?.seniority,
28 linkedInUrl: lead.clearbit?.person?.linkedin?.handle
29 ? `https://linkedin.com/in/${lead.clearbit.person.linkedin.handle}`
30 : null,
31 twitterUrl: lead.clearbit?.person?.twitter?.handle
32 ? `https://twitter.com/${lead.clearbit.person.twitter.handle}`
33 : null,
34 bio: lead.clearbit?.person?.bio
35 },
36
37 // Enrichment metadata
38 enrichedAt: new Date().toISOString(),
39 enrichmentSources: ['clearbit', 'linkedin'].filter(s => lead[s])
40};
41
42return {
43 leadId: lead.id,
44 original: lead,
45 enriched: enrichedData
46};

Checkpoint

Lead enrichment thu thập data từ những sources nào?

4

🏗️ Workflow 3: Lead Scoring

TB5 min

Score and Qualify Leads:

Lead Scoring Engine

🔔Lead Created/Updated
🏢Calculate Fit Score
📊Calculate Engagement Score
🧮Combined Score
🔥Hot (80+) → Alert Sales
♨️Warm (50-79) → Priority Nurture
❄️Cold (<50) → Standard Nurture

Lead Scoring Logic:

JavaScript
1const lead = $input.item.json;
2
3// FIT SCORING (max 50 points)
4function calculateFitScore(lead) {
5 let score = 0;
6 const company = lead.enriched?.company || {};
7 const person = lead.enriched?.person || {};
8
9 // Company size (max 15 points)
10 const employees = company.employeeCount || 0;
11 if (employees >= 1000) score += 15;
12 else if (employees >= 200) score += 12;
13 else if (employees >= 50) score += 10;
14 else if (employees >= 10) score += 5;
15 else score += 2;
16
17 // Industry match (max 15 points)
18 const targetIndustries = ['technology', 'software', 'saas', 'finance', 'healthcare'];
19 const industry = (company.industry || '').toLowerCase();
20 if (targetIndustries.some(t => industry.includes(t))) score += 15;
21 else if (company.industry) score += 5;
22
23 // Job title/seniority (max 10 points)
24 const title = (person.title || lead.jobTitle || '').toLowerCase();
25 const seniorTitles = ['ceo', 'cto', 'cfo', 'vp', 'director', 'head', 'chief'];
26 const midTitles = ['manager', 'lead', 'senior'];
27
28 if (seniorTitles.some(t => title.includes(t))) score += 10;
29 else if (midTitles.some(t => title.includes(t))) score += 7;
30 else if (title) score += 3;
31
32 // Geography (max 10 points)
33 const targetCountries = ['united states', 'usa', 'uk', 'australia', 'canada', 'germany'];
34 const country = (company.location?.country || '').toLowerCase();
35 if (targetCountries.some(c => country.includes(c))) score += 10;
36 else if (country) score += 5;
37
38 return score;
39}
40
41// ENGAGEMENT SCORING (max 50 points)
42function calculateEngagementScore(lead) {
43 let score = 0;
44 const activity = lead.activity || {};
45
46 // Page views (max 10 points)
47 const pageViews = activity.pageViews || 0;
48 score += Math.min(pageViews * 0.5, 10);
49
50 // Email engagement (max 15 points)
51 const emailOpens = activity.emailOpens || 0;
52 const emailClicks = activity.emailClicks || 0;
53 score += Math.min(emailOpens, 5);
54 score += Math.min(emailClicks * 2, 10);
55
56 // Content downloads (max 15 points)
57 const downloads = activity.downloads || 0;
58 score += Math.min(downloads * 5, 15);
59
60 // High-intent actions (max 10 points)
61 if (activity.demoRequested) score += 10;
62 else if (activity.pricingViewed) score += 5;
63 else if (activity.contactViewed) score += 3;
64
65 return score;
66}
67
68const fitScore = calculateFitScore(lead);
69const engagementScore = calculateEngagementScore(lead);
70const totalScore = fitScore + engagementScore;
71
72// Determine status
73let status, priority;
74if (totalScore >= 80) {
75 status = 'hot';
76 priority = 'high';
77} else if (totalScore >= 50) {
78 status = 'warm';
79 priority = 'medium';
80} else {
81 status = 'cold';
82 priority = 'low';
83}
84
85return {
86 leadId: lead.id,
87 scoring: {
88 fit: fitScore,
89 engagement: engagementScore,
90 total: totalScore,
91 status,
92 priority,
93 calculatedAt: new Date().toISOString()
94 },
95 action: status === 'hot' ? 'alert_sales' : 'continue_nurture'
96};

Checkpoint

Lead scoring system tính total score từ mấy thành phần?

5

📊 Workflow 4: CRM Integration

TB5 min

Sync to CRM:

CRM Sync

Lead Qualified
🗺️Map to CRM Fields
🔍Check Existing in CRM
✏️Update Contact & Add Note
🆕Create Contact & Company
👤Assign to Sales Rep
📋Create Follow-up Task

CRM Field Mapping:

JavaScript
1const lead = $input.item.json;
2
3// Map to HubSpot format (adapt for Salesforce, Pipedrive, etc.)
4const hubspotContact = {
5 properties: {
6 // Basic info
7 email: lead.email,
8 firstname: lead.firstName,
9 lastname: lead.lastName,
10 phone: lead.phone,
11 jobtitle: lead.enriched?.person?.title || lead.jobTitle,
12 company: lead.enriched?.company?.name || lead.company,
13
14 // Company details
15 company_size: lead.enriched?.company?.employeeCount?.toString(),
16 industry: lead.enriched?.company?.industry,
17 website: lead.enriched?.company?.domain
18 ? `https://${lead.enriched.company.domain}`
19 : null,
20
21 // Lead source
22 hs_lead_status: lead.scoring?.status?.toUpperCase(),
23 leadsource: lead.source,
24 original_source: lead.utmSource,
25 original_campaign: lead.utmCampaign,
26
27 // Scoring
28 lead_score: lead.scoring?.total,
29 lead_fit_score: lead.scoring?.fit,
30 lead_engagement_score: lead.scoring?.engagement,
31
32 // Social
33 linkedin_profile: lead.enriched?.person?.linkedInUrl,
34 twitter_profile: lead.enriched?.person?.twitterUrl,
35
36 // Metadata
37 first_conversion_date: lead.submittedAt,
38 landing_page_url: lead.landingPage
39 }
40};
41
42// Create task for sales follow-up
43const task = {
44 subject: `Follow up with ${lead.firstName} ${lead.lastName}`,
45 taskType: 'TODO',
46 priority: lead.scoring?.priority === 'high' ? 'HIGH' : 'MEDIUM',
47 status: 'NOT_STARTED',
48 notes: `
49Lead Score: ${lead.scoring?.total}
50Company: ${lead.company}
51Source: ${lead.source}
52 `.trim()
53};
54
55return {
56 contact: hubspotContact,
57 task: task,
58 company: lead.enriched?.company?.name ? {
59 properties: {
60 name: lead.enriched.company.name,
61 domain: lead.enriched.company.domain,
62 industry: lead.enriched.company.industry,
63 numberofemployees: lead.enriched.company.employeeCount,
64 annualrevenue: lead.enriched.company.annualRevenue
65 }
66 } : null
67};

Checkpoint

CRM sync map fields tới HubSpot format bao gồm những gì?

6

💡 Workflow 5: Email Nurture Sequence

TB5 min

Automated Drip Campaigns:

Lead Nurture Sequence

📋Lead Added to Sequence
👋Day 0: Welcome Email
📩Day 3: Value Content #1
👀Opened → Day 6: Case Study
🔄No Open → Day 6: Re-send
🎯Day 10: Product Demo CTA
🤝Clicked → Sales Handoff
📦No Click → Final Push & Archive

Nurture Email Generator:

JavaScript
1const lead = $input.item.json;
2const sequenceStep = lead.sequenceStep || 1;
3
4const emailSequence = {
5 1: {
6 subject: `Welcome ${lead.firstName}! Here's what's next`,
7 template: 'welcome',
8 delay: 0
9 },
10 2: {
11 subject: '3 ways to [solve problem]',
12 template: 'value_content_1',
13 delay: 3 * 24 * 60 // 3 days in minutes
14 },
15 3: {
16 subject: 'How [similar company] achieved [result]',
17 template: 'case_study',
18 delay: 6 * 24 * 60
19 },
20 4: {
21 subject: 'See it in action? Quick 15-min demo',
22 template: 'demo_cta',
23 delay: 10 * 24 * 60
24 },
25 5: {
26 subject: "Last chance: Your exclusive resource",
27 template: 'final_push',
28 delay: 14 * 24 * 60
29 },
30 6: {
31 subject: "Should I stop sending these?",
32 template: 'breakup',
33 delay: 21 * 24 * 60
34 }
35};
36
37const currentEmail = emailSequence[sequenceStep];
38
39// Personalization tokens
40const personalization = {
41 firstName: lead.firstName,
42 company: lead.company || 'your company',
43 industry: lead.enriched?.company?.industry || 'your industry',
44 painPoint: determinePainPoint(lead),
45 relevantCaseStudy: selectCaseStudy(lead.enriched?.company?.industry)
46};
47
48function determinePainPoint(lead) {
49 // Logic based on lead source or behavior
50 const source = lead.source?.toLowerCase() || '';
51 if (source.includes('productivity')) return 'saving time on repetitive tasks';
52 if (source.includes('automation')) return 'automating manual workflows';
53 if (source.includes('integration')) return 'connecting your tools';
54 return 'streamlining your operations';
55}
56
57function selectCaseStudy(industry) {
58 const caseStudies = {
59 'technology': 'TechCorp',
60 'finance': 'FinanceInc',
61 'healthcare': 'HealthOrg',
62 'default': 'a company like yours'
63 };
64 return caseStudies[industry?.toLowerCase()] || caseStudies.default;
65}
66
67return {
68 leadId: lead.id,
69 email: currentEmail,
70 personalization,
71 nextStep: sequenceStep + 1,
72 sendAt: new Date(Date.now() + currentEmail.delay * 60 * 1000).toISOString()
73};

Checkpoint

Email nurture sequence bao gồm bao nhiêu emails?

7

🌟 Workflow 6: Sales Handoff

TB5 min

Hot Lead Alert:

Sales Alert & Handoff

🔥Lead Score >= 80
👤Assign Sales Rep (Round-robin)
💬Send Slack Alert
📋Create CRM Task
Auto-Follow-up if no action in 24h

Sales Alert Message:

JavaScript
1const lead = $input.item.json;
2
3// Round-robin assignment
4const salesReps = [
5 { name: 'Alice', slackId: 'U123', territories: ['us', 'canada'] },
6 { name: 'Bob', slackId: 'U456', territories: ['uk', 'europe'] },
7 { name: 'Charlie', slackId: 'U789', territories: ['asia', 'default'] }
8];
9
10function assignRep(lead) {
11 const country = lead.enriched?.company?.location?.country?.toLowerCase() || 'default';
12
13 for (const rep of salesReps) {
14 if (rep.territories.some(t => country.includes(t) || t === 'default')) {
15 return rep;
16 }
17 }
18 return salesReps[0];
19}
20
21const assignedRep = assignRep(lead);
22
23const slackMessage = {
24 channel: '#sales-alerts',
25 text: `🔥 Hot Lead Alert!`,
26 blocks: [
27 {
28 type: 'header',
29 text: { type: 'plain_text', text: '🔥 Hot Lead Alert!' }
30 },
31 {
32 type: 'section',
33 fields: [
34 { type: 'mrkdwn', text: `*Name:*\n${lead.firstName} ${lead.lastName}` },
35 { type: 'mrkdwn', text: `*Company:*\n${lead.company}` },
36 { type: 'mrkdwn', text: `*Title:*\n${lead.jobTitle || 'Unknown'}` },
37 { type: 'mrkdwn', text: `*Lead Score:*\n${lead.scoring?.total}/100` }
38 ]
39 },
40 {
41 type: 'section',
42 text: {
43 type: 'mrkdwn',
44 text: `*Score Breakdown:*\n• Fit: ${lead.scoring?.fit}/50\n• Engagement: ${lead.scoring?.engagement}/50`
45 }
46 },
47 {
48 type: 'section',
49 text: {
50 type: 'mrkdwn',
51 text: `*Recent Activity:*\n${formatRecentActivity(lead.activity)}`
52 }
53 },
54 {
55 type: 'section',
56 text: {
57 type: 'mrkdwn',
58 text: `*Assigned to:* <@${assignedRep.slackId}>`
59 }
60 },
61 {
62 type: 'actions',
63 elements: [
64 {
65 type: 'button',
66 text: { type: 'plain_text', text: '📞 Call Now' },
67 url: `tel:${lead.phone}`,
68 style: 'primary'
69 },
70 {
71 type: 'button',
72 text: { type: 'plain_text', text: '✉️ Email' },
73 url: `mailto:${lead.email}`
74 },
75 {
76 type: 'button',
77 text: { type: 'plain_text', text: '📊 View in CRM' },
78 url: `https://crm.example.com/leads/${lead.id}`
79 }
80 ]
81 }
82 ]
83};
84
85function formatRecentActivity(activity) {
86 if (!activity) return 'No recent activity';
87
88 const items = [];
89 if (activity.demoRequested) items.push('✅ Requested demo');
90 if (activity.pricingViewed) items.push('👀 Viewed pricing page');
91 if (activity.downloads?.length) items.push(`📥 Downloaded ${activity.downloads.length} resource(s)`);
92 if (activity.emailClicks) items.push(`🔗 Clicked ${activity.emailClicks} email link(s)`);
93
94 return items.length > 0 ? items.join('\n') : 'Browse only';
95}
96
97return {
98 slackMessage,
99 assignedRep,
100 followUpDeadline: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
101};

Checkpoint

Sales handoff assign rep theo round-robin hay territory?

8

📈 Lead Generation Metrics

TB5 min
Key Metrics to Track

Funnel Metrics:

  • Visitors → Leads (Conversion Rate)
  • Leads → MQLs (Marketing Qualified)
  • MQLs → SQLs (Sales Qualified)
  • SQLs → Opportunities
  • Opportunities → Customers

Per-Lead Metrics:

  • Cost per Lead (CPL)
  • Lead Score accuracy
  • Time to qualification
  • Nurture engagement rate
  • Sales acceptance rate

Checkpoint

Những funnel metrics nào cần track?

9

📋 Best Practices

TB5 min
Lead Gen Automation Tips

DO:

  • ✅ Respond to leads quickly (under 5 min ideal)
  • ✅ Personalize based on lead data
  • ✅ Score leads consistently
  • ✅ Clean and validate data
  • ✅ Get consent (GDPR/privacy)

DON'T:

  • ❌ Spam or over-email
  • ❌ Ignore lead source in scoring
  • ❌ Delay sales handoff for hot leads
  • ❌ Forget to track conversions
  • ❌ Buy email lists

Checkpoint

Thời gian response lý tưởng cho leads là bao lâu?

10

📝 Bài Tập Thực Hành

TB5 min
Lead Generation Challenge

Build your lead machine:

  1. Create form submission workflow
  2. Implement lead scoring system
  3. Set up CRM sync (HubSpot/Airtable)
  4. Build 5-email nurture sequence
  5. Configure hot lead alerts

Start converting! 🎯

Checkpoint

Bạn đã hoàn thành những challenges nào trong bài tập?

11

🧠 Key Takeaways

TB5 min
Remember
  • 🎯 Score intelligently - Fit + Engagement
  • Speed matters - Fast response = higher conversion
  • 🔄 Nurture consistently - Stay top of mind
  • 📊 Measure everything - Optimize based on data
  • 🤝 Align sales & marketing - Clear handoff criteria

Checkpoint

Tại sao Speed matters - Fast response = higher conversion?

🚀 Bài tiếp theo

Complex Multi-Step Workflows — Advanced patterns combining everything you've learned.