🔌 n8n Integrations
n8n có hàng trăm integrations sẵn có. Bài này cover các integrations phổ biến và cách sử dụng hiệu quả.
Popular Integrations
Categories
Diagram
graph TD
I[Integrations] --> C[Communication]
I --> P[Productivity]
I --> D[Data]
I --> AI[AI/ML]
C --> Slack
C --> Email
C --> Discord
P --> Notion
P --> GDocs[Google Docs]
P --> Airtable
D --> MySQL
D --> PostgreSQL
D --> MongoDB
AI --> OpenAI
AI --> AnthropicCommunication Integrations
Slack
Send Message:
Diagram
graph LR
T[Trigger] --> S[Slack: Send Message]Config:
- Channel:
#notifications - Text:
{{ $json.message }} - Blocks: Optional rich formatting
Example: Alert Workflow
JavaScript
1// Code node trước Slack2const items = $input.all();34for (const item of items) {5 item.json.slackMessage = {6 text: `🚨 Alert: ${item.json.alert_type}`,7 blocks: [8 {9 type: "section",10 text: {11 type: "mrkdwn",12 text: `*${item.json.title}*\n${item.json.description}`13 }14 },15 {16 type: "context",17 elements: [18 {19 type: "mrkdwn",20 text: `📅 ${new Date().toLocaleString()}`21 }22 ]23 }24 ]25 };26}2728return items;Email (Gmail/SMTP)
Send Email:
Config:
- To:
{{ $json.email }} - Subject:
{{ $json.subject }} - HTML Body: Rich content
Example: Welcome Email
JavaScript
1// Prepare email content2const items = $input.all();34for (const item of items) {5 item.json.emailContent = `6 <h1>Chào mừng ${item.json.name}! ��</h1>7 <p>Cảm ơn bạn đã đăng ký.</p>8 <ul>9 <li>Account: ${item.json.email}</li>10 <li>Created: ${new Date().toLocaleDateString()}</li>11 </ul>12 <p>Bắt đầu ngay: <a href="${item.json.dashboardUrl}">Dashboard</a></p>13 `;14}1516return items;Productivity Integrations
Notion
Create Database Item:
Diagram
graph LR
T[Webhook] --> N[Notion: Create]
N --> S[Slack: Notify]Config:
- Database ID: Your Notion database
- Properties:
- Title:
{{ $json.title }} - Status:
{{ $json.status }} - Due Date:
{{ $json.dueDate }}
- Title:
Example: Task Sync
JavaScript
1// Transform data for Notion2const items = $input.all();34for (const item of items) {5 item.json.notionProperties = {6 "Task Name": {7 title: [{ text: { content: item.json.title } }]8 },9 "Status": {10 select: { name: item.json.status }11 },12 "Priority": {13 select: { name: item.json.priority }14 },15 "Due Date": {16 date: { start: item.json.dueDate }17 }18 };19}2021return items;Google Sheets
Append Row:
Diagram
graph LR
F[Form Submit] --> G[Google Sheets: Append]Config:
- Spreadsheet ID: From URL
- Sheet Name: "Responses"
- Data: Map fields to columns
Example: Lead Tracker
JavaScript
1// Prepare row data2const items = $input.all();34for (const item of items) {5 item.json.sheetRow = {6 Timestamp: new Date().toISOString(),7 Name: item.json.name,8 Email: item.json.email,9 Company: item.json.company,10 Source: item.json.source || "Direct",11 Score: item.json.leadScore || 012 };13}1415return items;Airtable
Create Record:
Config:
- Base ID: From Airtable
- Table: "Contacts"
- Fields: Map to Airtable columns
Database Integrations
PostgreSQL
Query Database:
SQL
1SELECT * FROM users 2WHERE created_at > {{ $json.startDate }}3ORDER BY created_at DESC4LIMIT 100Insert Data:
SQL
1INSERT INTO logs (event_type, data, created_at)2VALUES (3 '{{ $json.eventType }}',4 '{{ JSON.stringify($json.data) }}',5 NOW()6)MongoDB
Find Documents:
JavaScript
1// Query2{3 "status": "{{ $json.status }}",4 "createdAt": {5 "$gte": "{{ $json.startDate }}"6 }7}Insert Document:
JavaScript
1{2 "name": "{{ $json.name }}",3 "email": "{{ $json.email }}",4 "metadata": {{ JSON.stringify($json.metadata) }},5 "createdAt": "{{ $now.toISOString() }}"6}AI Integrations
OpenAI
Chat Completion:
Diagram
graph LR
T[Trigger] --> O[OpenAI: Chat]
O --> P[Process Response]Config:
- Model: gpt-4o-mini
- Messages:
- System: "Bạn là trợ lý hữu ích"
- User:
{{ $json.question }}
Example: Auto-reply Bot
JavaScript
1// Prepare messages2const items = $input.all();34for (const item of items) {5 item.json.messages = [6 {7 role: "system",8 content: `Bạn là customer support bot cho ${item.json.companyName}.9 Trả lời ngắn gọn, thân thiện bằng tiếng Việt.`10 },11 {12 role: "user",13 content: item.json.customerMessage14 }15 ];16}1718return items;Anthropic (Claude)
Config:
- Model: claude-3-5-sonnet-20241022
- Max Tokens: 1000
- Messages: Similar to OpenAI
Webhook Integration
Receive Webhook
Nhận data từ external services:
Diagram
graph LR
E[External Service] -->|POST| W[Webhook Trigger]
W --> P[Process]
P --> A[Action]Config:
- HTTP Method: POST
- Path:
/webhook/my-endpoint - Authentication: Header Auth / Basic Auth
Example: Stripe Webhook
JavaScript
1// Handle Stripe webhook2const items = $input.all();34for (const item of items) {5 const event = item.json;6 7 // Route based on event type8 item.json.action = null;9 10 switch(event.type) {11 case "checkout.session.completed":12 item.json.action = "create_subscription";13 item.json.customerId = event.data.object.customer;14 break;15 case "invoice.paid":16 item.json.action = "update_payment";17 break;18 case "customer.subscription.deleted":19 item.json.action = "cancel_subscription";20 break;21 }22}2324return items;Send Webhook
POST data to external service:
Diagram
graph LR
T[Trigger] --> H[HTTP Request]Config:
- Method: POST
- URL: External endpoint
- Headers: Authentication
- Body: JSON payload
Building Integration Workflows
Example: Lead Processing Pipeline
Diagram
graph TD
W[Webhook: New Lead] --> E[Enrich: Clearbit]
E --> S[Score Lead]
S --> IF{Score > 50?}
IF -->|Yes| N[Notify Sales]
IF -->|No| M[Add to Nurture]
N --> C[Create CRM Record]
M --> D[Add to Drip Campaign]Implementation:
JavaScript
1// Lead scoring code2const items = $input.all();34for (const item of items) {5 let score = 0;6 7 // Company size8 if (item.json.employees > 100) score += 20;9 if (item.json.employees > 500) score += 10;10 11 // Industry12 if (["Tech", "Finance", "Healthcare"].includes(item.json.industry)) {13 score += 15;14 }15 16 // Email domain17 if (!item.json.email.includes("gmail") && 18 !item.json.email.includes("yahoo")) {19 score += 10; // Business email20 }21 22 // Engagement23 if (item.json.downloadedWhitepaper) score += 20;24 if (item.json.attendedWebinar) score += 25;25 26 item.json.leadScore = score;27 item.json.tier = score > 50 ? "hot" : score > 25 ? "warm" : "cold";28}2930return items;Best Practices
Integration Tips
- Rate Limiting: Respect API limits
- Error Handling: Handle API failures
- Credentials: Use n8n credential manager
- Retry Logic: Implement retries cho transient failures
- Logging: Log API calls cho debugging
- Testing: Test với sandbox/staging APIs
Bài tập thực hành
Hands-on Exercise
Build Integration Workflow:
-
Tạo workflow:
- Webhook trigger
- Process data
- Call external API
- Store to database
- Send notification
-
Implement error handling
-
Add logging
Target: Complete integration pipeline với multiple services
