HƯỚNG DẪN

Cách cảnh báo gửi tin thất bại sau khi bước gửi trả về 200 trong n8n

Ngày đăng · Cập nhật

Mã

js
// Delivery tracking: a 200 from the send step means "queued", not "delivered".
// Status names differ per provider. Adjust these two sets to match yours.
const FAILED = new Set(['failed', 'undelivered', 'bounced', 'rejected']);
const DONE = new Set(['delivered', 'read']);

const isFinal = (status) => FAILED.has(status) || DONE.has(status);

// Workflow 1: call right after the send step.
// store is a plain object keyed by message ID. Persist it in a database table.
function recordSent(store, messageId, recipient, now = Date.now()) {
  if (!messageId) throw new Error('Send step returned no message ID');
  store[messageId] = { recipient, status: 'queued', sentAt: now, updatedAt: now };
  return store[messageId];
}

// Workflow 2: call for every event on the status webhook.
// Returns an alert object, or null when nothing needs attention.
function applyStatus(store, event, now = Date.now()) {
  const messageId = event.messageId;
  const status = String(event.status || '').toLowerCase();
  const row = store[messageId];
  if (!row) {
    return { level: 'warn', messageId, status, reason: 'unknown message ID' };
  }
  if (isFinal(row.status)) return null; // late or duplicate event, already handled
  row.status = status;
  row.updatedAt = now;
  if (FAILED.has(status)) {
    return {
      level: 'error',
      messageId,
      status,
      recipient: row.recipient,
      reason: event.error || 'delivery failed',
    };
  }
  return null;
}

// Workflow 3 (schedule): messages that never reached a final status.
function findStale(store, now = Date.now(), maxAgeMs = 15 * 60 * 1000) {
  return Object.entries(store)
    .filter(([, row]) => !isFinal(row.status) && now - row.sentAt > maxAgeMs)
    .map(([messageId, row]) => ({
      level: 'warn',
      messageId,
      status: row.status,
      recipient: row.recipient,
      reason: 'no final status',
    }));
}

// In an n8n Code node, load `store` from your table, then end with e.g.:
// return $input.all()
//   .map((item) => applyStatus(store, item.json))
//   .filter(Boolean)
//   .map((json) => ({ json }));

Vì sao xảy ra

Gửi một tin nhắn là việc gồm hai giai đoạn. Đầu tiên nhà cung cấp nhận yêu cầu và trả về 200 kèm một ID. Sau đó họ mới thử chuyển tin tới nhà mạng, hộp thư hoặc ứng dụng chat, và lần thử này có thể thất bại. Kết quả thứ hai không bao giờ quay về bước gửi, nên lần chạy workflow vẫn xanh. Nhà cung cấp chỉ báo kết quả đó qua một callback trạng thái riêng.

Các bước

  1. Sau bước gửi, gọi recordSent với message ID lấy từ phản hồi. Lưu dòng đó với trạng thái queued.
  2. Tạo workflow thứ hai với trigger Webhook. Đăng ký URL của nó làm status callback trong phần cài đặt của nhà cung cấp.
  3. Trong workflow đó, chuyển payload của nhà cung cấp về dạng { messageId, status, error } và đưa từng sự kiện vào applyStatus.
  4. Nếu applyStatus trả về một object, gửi nó tới kênh cảnh báo. Nếu trả về null, không làm gì.
  5. Thêm một workflow chạy theo lịch gọi findStale. Nó bắt các tin mà callback không bao giờ tới.
  6. Lưu store đã cập nhật trở lại bảng sau mỗi lần chạy.

Lưu ý

  • Workflow static data không dùng chung giữa các workflow. Hãy để store trong một bảng cơ sở dữ liệu mà cả ba workflow đều đọc được.
  • Tên trạng thái khác nhau giữa các nhà cung cấp, và sự kiện có thể tới trễ, tới hai lần hoặc sai thứ tự. Mã bỏ qua sự kiện khi tin đã có trạng thái cuối.
  • Webhook trạng thái là một URL công khai. Hãy kiểm tra chữ ký của nhà cung cấp hoặc một header bí mật trước khi tin sự kiện, và lưu bí mật đó trong credentials của n8n.
  • Xóa các dòng cũ đã có trạng thái cuối theo lịch, nếu không bảng sẽ lớn mãi.

Thấy trên: n8n Community ·

Dịch vụ liên quan: Workflow tự động n8n, Make, Zapier