Minh họa workflow n8n xử lý hóa đơn tự động từ Gmail

Xử lý hóa đơn từ Gmail

Hướng dẫn N8N – Tự động xử lý Invoice từ Gmail đến Notion

🧾 Tự động xử lý Invoice từ Gmail đến Notion với N8N

1. 🎯 Tổng quan Workflow

Workflow này giúp bạn tự động hóa hoàn toàn quy trình xử lý hóa đơn (invoice) từ email Gmail, sử dụng AI để trích xuất thông tin và lưu trữ vào Notion database.

Workflow làm gì?

  1. Theo dõi Gmail – Tự động phát hiện email có file PDF đính kèm
  2. Lưu file lên Google Drive – Backup file PDF vào thư mục chỉ định
  3. Trích xuất nội dung PDF – Đọc text từ file PDF
  4. AI kiểm tra – Xác định xem có phải invoice không
  5. AI phân tích – Trích xuất thông tin: tên invoice, công ty, tổng tiền, chi tiết từng mục
  6. Lưu vào Notion – Tạo record trong database với đầy đủ thông tin

📊 Sơ đồ Workflow

📧 Gmail Trigger
→
📁 Google Drive
→
📄 Extract PDF
→
🤖 AI Check
→
🧠 AI Extract
→
📝 Notion

2. 📋 Yêu cầu chuẩn bị

Tài khoản cần thiết

Dịch vụ Mục đích Loại kết nối
Gmail Nhận email có invoice OAuth2
Google Drive Lưu trữ file PDF OAuth2
OpenAI AI phân tích invoice API Key
Notion Lưu trữ dữ liệu Integration Token

Chuẩn bị Notion Database

Bạn cần tạo 2 database trong Notion:

Database 1: Invoice Tracking Database

Tên cột Loại Mô tả
Subject Title Tiêu đề email
Email Rich Text Email người gửi
Invoice URL URL Link file trên Drive
Amount Number Tổng tiền invoice

Database 2: Invoice Line Items

Tên cột Loại Mô tả
Invoice Subject Title Tiêu đề invoice
Invoice Item Rich Text Mô tả item
Amount Number Số tiền từng item
💡 Mẹo

Tạo một thư mục riêng trên Google Drive để lưu invoice, ví dụ: “Invoices From Gmail”. Ghi lại Folder ID để cấu hình trong workflow.

3. 🏗️ Cấu trúc Workflow

Workflow được chia thành 4 phần chính:

📦 Phần 1: Get & Prepare Documents

Nhận email, xử lý attachments và upload lên Google Drive.

  • Gmail Trigger – Theo dõi email mới có PDF
  • Edit Fields – Lấy danh sách attachments
  • Split Out – Tách từng attachment
  • Merge – Kết hợp data
  • Upload file – Upload lên Google Drive
  • Download file – Download để xử lý
  • Extract from File – Trích xuất text từ PDF

🔍 Phần 2: Check for Invoice

Sử dụng AI để xác định có phải invoice không.

  • Invoice Controller (AI Agent) – Kiểm tra nội dung
  • If – Điều kiện: nếu là invoice → tiếp tục, nếu không → xóa file
  • Delete a file – Xóa file không phải invoice

🧠 Phần 3: Extract & Save Information

AI trích xuất thông tin chi tiết và lưu vào Notion.

  • Basic LLM Chain – Phân tích và trích xuất data
  • Create a database page – Tạo record trong Notion

📝 Phần 4: Save Subitems

Lưu chi tiết từng line item của invoice.

  • Edit Fields1 – Chuẩn bị data line items
  • Split Out1 – Tách từng item
  • Loop Over Items – Lặp qua từng item
  • Create a database page1 – Tạo record cho mỗi item

4. 📝 Hướng dẫn từng bước

1 Cấu hình Gmail Trigger

Node này theo dõi email mới có file PDF đính kèm.

Cấu hình:

  • Poll Times: Mặc định (mỗi phút)
  • Simple: false (lấy đầy đủ thông tin)
  • Filters → Q: filename:pdf has:attachment
  • Options → Download Attachments: true
📌 Quan trọng

Bạn cần kết nối tài khoản Gmail qua OAuth2. Vào Credentials → Create New → Gmail OAuth2 và làm theo hướng dẫn.

2 Cấu hình Edit Fields (Lấy danh sách attachments)

Trích xuất danh sách file đính kèm từ email.

Assignments:

attachments = {{ Object.keys($binary) }}  (Type: Array)
message_id = {{ $json.id }}  (Type: String)
3 Cấu hình Split Out

Tách mỗi attachment thành item riêng biệt.

Cấu hình:

  • Field To Split Out: attachments
  • Include: All Other Fields
4 Cấu hình Merge Node

Kết hợp data từ Split Out với data gốc từ Gmail Trigger.

Cấu hình:

  • Mode: Combine
  • Merge By Fields:
    • Field 1: message_id
    • Field 2: id
5 Cấu hình Upload file (Google Drive)

Upload file PDF lên Google Drive.

Cấu hình:

  • Operation: Upload (mặc định)
  • Input Data Field Name: ={{ $json.attachments }}
  • File Name: ={{ $('Gmail Trigger').item.json.headers.subject }}_{{ $json.attachments }}
  • Drive: My Drive
  • Folder: Chọn thư mục bạn đã tạo (VD: “Invoices From Gmail”)
💡 Mẹo

File sẽ được đặt tên theo format: [Tiêu đề email]_[Tên file gốc] để dễ tìm kiếm sau này.

6 Cấu hình Download file

Download file vừa upload để xử lý.

Cấu hình:

  • Operation: Download
  • File ID: ={{ $json.id }}
7 Cấu hình Extract from File

Trích xuất text từ file PDF.

Cấu hình:

  • Operation: PDF
  • Binary Property Name: data
8 Cấu hình Invoice Controller (AI Agent)

AI kiểm tra xem nội dung có phải invoice không.

Prompt:

Based on the text decide if the text is about an invoice or not: {{ $json.text }}

If yes return "yes", if no return "no". 
Don't provide any additional information. 
Use only small letters

Sub-nodes:

  • OpenAI Chat Model: gpt-4.1-mini (hoặc model khác)
  • Structured Output Parser:
    {
      "status": ""
    }
9 Cấu hình If Node

Điều kiện rẽ nhánh dựa trên kết quả AI.

Condition:

  • Value 1: ={{ $json.output.status }}
  • Operation: Equals
  • Value 2: yes

True (là invoice): → Tiếp tục đến Basic LLM Chain

False (không phải invoice): → Xóa file trên Drive

10 Cấu hình Basic LLM Chain (Trích xuất thông tin)

AI phân tích và trích xuất thông tin chi tiết từ invoice.

Prompt:

Task Overview
You'll receive raw text extracted from PDF invoices. 
Your job is to identify the key details listed below 
and return them in a structured JSON object.

Information to Capture:
- invoice_name – the identifier or title of the invoice
- company_name – the name of the business that issued the invoice
- total_invoice_amount – the grand total shown on the invoice
- line_items – an array where each entry includes:
  • description – the item or service label
  • amount – the cost for that item

Output Format (example):
{
  "invoice_name": "Invoice ABC-123",
  "company_name": "Acme Corp",
  "total_invoice_amount": 1000,
  "line_items": [
    { "description": "Consulting services", "amount": 100 },
    { "description": "Software license", "amount": 800 },
    { "description": "Sales tax", "amount": 100 }
  ]
}

Guidelines:
- If any detail is missing or unclear, make your best estimate or use null.
- Provide the most specific line-item labels available.
- Verify that the line-item amounts add up to the total invoice amount.

Text: {{ $json.text }}

Structured Output Parser Schema:

{
  "invoice_name": "Invoice ABC-123",
  "company_name": "Acme Corp",
  "total_invoice_amount": 1000,
  "line_items": [
    { "description": "Consulting services", "amount": 100 },
    { "description": "Software license", "amount": 800 },
    { "description": "Sales tax", "amount": 100 }
  ]
}
11 Cấu hình Create Database Page (Notion – Main)

Tạo record chính trong Notion database.

Cấu hình:

  • Resource: Database Page
  • Database: Chọn “Invoice Tracking Database”
  • Properties:
    • Subject (Title): ={{ $('Gmail Trigger').item.json.subject }}
    • Email (Rich Text): ={{ $('Gmail Trigger').item.json.from.value[0].address }}
    • Invoice URL (URL): ={{ $('Upload file').item.json.webViewLink }}
    • Amount (Number): ={{ $json.output.total_invoice_amount }}
12 Cấu hình Loop và Line Items

Lưu chi tiết từng item của invoice.

Edit Fields1:

line_items = {{ $('Basic LLM Chain').item.json.output.line_items }}  (Type: Array)
subject_id = {{ $json.id }}  (Type: String)

Split Out1:

  • Field To Split Out: line_items

Loop Over Items:

  • Sử dụng mặc định, batch size = 1

Create Database Page1 (Line Items):

  • Database: Chọn “Invoice Line Items”
  • Properties:
    • Invoice Subject (Title): ={{ $('Gmail Trigger').item.json.subject }}
    • Invoice Item (Rich Text): ={{ $json.line_items.description }}
    • Amount (Number): ={{ $json.line_items.amount }}

5. 🔧 Xử lý lỗi thường gặp

❌ Lỗi: “No row was found with ID”

Nguyên nhân: Reference đến node không tồn tại hoặc không có data.

Giải pháp: Kiểm tra lại tên node trong expression, đảm bảo node đã chạy thành công.

❌ Lỗi: Gmail không trigger

Nguyên nhân: Filter query không đúng hoặc không có email mới.

Giải pháp:

  • Kiểm tra query: filename:pdf has:attachment
  • Test bằng cách gửi email mới có file PDF
  • Kiểm tra OAuth2 credentials

❌ Lỗi: AI trả về kết quả sai format

Nguyên nhân: Prompt không rõ ràng hoặc PDF không đọc được.

Giải pháp:

  • Kiểm tra output của “Extract from File” có text không
  • Thử với PDF khác (text-based, không phải scan)
  • Điều chỉnh prompt cho phù hợp

❌ Lỗi: Notion không tạo được page

Nguyên nhân: Database ID sai hoặc thiếu quyền.

Giải pháp:

  • Kiểm tra Integration đã được share với database chưa
  • Verify tên các properties đúng với database
  • Kiểm tra data type (Number, Text, URL…)
💡 Debug Tips
  • Sử dụng Execute Node để test từng node riêng lẻ
  • Kiểm tra Output của mỗi node để xem data
  • Bật Always Output Data để debug dễ hơn

🎉 Kết luận

Bạn đã hoàn thành việc thiết lập workflow tự động xử lý invoice! Workflow này sẽ:

  • ✅ Tự động phát hiện email có invoice PDF
  • ✅ Backup file lên Google Drive
  • ✅ Sử dụng AI để kiểm tra và trích xuất thông tin
  • ✅ Lưu trữ có tổ chức trong Notion
  • ✅ Xóa file không phải invoice để tiết kiệm dung lượng
🚀 Bước tiếp theo

Bạn có thể mở rộng workflow này bằng cách:

  • Thêm notification qua Slack/Telegram khi có invoice mới
  • Tự động phân loại invoice theo công ty
  • Tạo báo cáo tổng hợp hàng tháng
  • Kết nối với phần mềm kế toán

📝 Bài viết được tạo cho N8N Blog

Có thắc mắc? Liên hệ qua email hoặc comment bên dưới!

Để lại một bình luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *