Lý thuyết
30 phút
Bài 4/7

n8n Integrations

Kết nối n8n với các services và APIs phổ biến

🔌 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 --> Anthropic

Communication 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 Slack
2const items = $input.all();
3
4for (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}
27
28return items;

Email (Gmail/SMTP)

Send Email:

Config:

  • To: {{ $json.email }}
  • Subject: {{ $json.subject }}
  • HTML Body: Rich content

Example: Welcome Email

JavaScript
1// Prepare email content
2const items = $input.all();
3
4for (const item of items) {
5 item.json.emailContent = `
6 <h1>Chào mng ${item.json.name}! </h1>
7 <p>Cm ơn bn đã đăng ký.</p>
8 <ul>
9 <li>Account: ${item.json.email}</li>
10 <li>Created: ${new Date().toLocaleDateString()}</li>
11 </ul>
12 <p>Bt đu ngay: <a href="${item.json.dashboardUrl}">Dashboard</a></p>
13 `;
14}
15
16return 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 }}

Example: Task Sync

JavaScript
1// Transform data for Notion
2const items = $input.all();
3
4for (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}
20
21return 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 data
2const items = $input.all();
3
4for (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 || 0
12 };
13}
14
15return 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 DESC
4LIMIT 100

Insert 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// Query
2{
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 messages
2const items = $input.all();
3
4for (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 li ngn gn, thân thin bng tiếng Vit.`
10 },
11 {
12 role: "user",
13 content: item.json.customerMessage
14 }
15 ];
16}
17
18return 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 webhook
2const items = $input.all();
3
4for (const item of items) {
5 const event = item.json;
6
7 // Route based on event type
8 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}
23
24return 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 code
2const items = $input.all();
3
4for (const item of items) {
5 let score = 0;
6
7 // Company size
8 if (item.json.employees > 100) score += 20;
9 if (item.json.employees > 500) score += 10;
10
11 // Industry
12 if (["Tech", "Finance", "Healthcare"].includes(item.json.industry)) {
13 score += 15;
14 }
15
16 // Email domain
17 if (!item.json.email.includes("gmail") &&
18 !item.json.email.includes("yahoo")) {
19 score += 10; // Business email
20 }
21
22 // Engagement
23 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}
29
30return items;

Best Practices

Integration Tips
  1. Rate Limiting: Respect API limits
  2. Error Handling: Handle API failures
  3. Credentials: Use n8n credential manager
  4. Retry Logic: Implement retries cho transient failures
  5. Logging: Log API calls cho debugging
  6. Testing: Test với sandbox/staging APIs

Bài tập thực hành

Hands-on Exercise

Build Integration Workflow:

  1. Tạo workflow:

    • Webhook trigger
    • Process data
    • Call external API
    • Store to database
    • Send notification
  2. Implement error handling

  3. Add logging

Target: Complete integration pipeline với multiple services


Tài liệu tham khảo