Skip to main content
RedClaw
返回部落格
automation

LINE Messaging API 整合教學:自動回覆、推播、Flex Message

RedClaw Team
2026/3/14
12 min read

LINE Messaging API 整合教學:自動回覆、推播、Flex Message

LINE 官方帳號的後台管理功能已經能滿足基本的行銷需求,但如果你想實現更複雜的自動化流程——例如串接訂單系統自動通知、依用戶行為觸發不同回覆、或建立互動式 Chatbot——就需要整合 LINE Messaging API。

本文將從環境建置開始,帶你完成 Messaging API 的核心功能整合。

前置準備

必要條件

  1. LINE 官方帳號(認證帳號或一般帳號皆可)
  2. LINE Developers 帳號
  3. 伺服器環境(支援 HTTPS 的 Webhook endpoint)
  4. 基本的程式開發能力(本文以 Node.js 為例)

建立 Messaging API Channel

  1. 前往 LINE Developers Console
  2. 建立或選擇一個 Provider
  3. 點擊「Create a Messaging API channel」
  4. 填寫 Channel 資訊:
    • Channel name:你的品牌名稱
    • Channel description:簡短描述
    • Category / Subcategory:選擇產業類別
  5. 取得以下憑證:
    • Channel ID
    • Channel Secret
    • Channel Access Token(長期)

[截圖參考:LINE Developers Console 的 Channel 設定頁面,標示 Channel Secret 和 Access Token 的位置]

安全提醒:Channel Secret 和 Access Token 是高度敏感的憑證,請使用環境變數管理,絕不要寫死在程式碼中或 commit 到版本控制。

環境建置(Node.js)

mkdir line-bot && cd line-bot
npm init -y
npm install @line/bot-sdk express dotenv

建立 .env 檔案:

LINE_CHANNEL_SECRET=your_channel_secret_here
LINE_CHANNEL_ACCESS_TOKEN=your_channel_access_token_here
PORT=3000

基本伺服器架構

// server.js
require('dotenv').config();
const express = require('express');
const line = require('@line/bot-sdk');

const config = {
  channelSecret: process.env.LINE_CHANNEL_SECRET,
  channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN,
};

const client = new line.messagingApi.MessagingApiClient(config);
const app = express();

// Webhook endpoint
app.post('/webhook', line.middleware(config), (req, res) => {
  Promise.all(req.body.events.map(handleEvent))
    .then((result) => res.json(result))
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});

// Event handler
async function handleEvent(event) {
  if (event.type !== 'message' || event.message.type !== 'text') {
    return null;
  }

  return client.replyMessage({
    replyToken: event.replyToken,
    messages: [{
      type: 'text',
      text: `你說的是:${event.message.text}`
    }]
  });
}

const port = process.env.PORT || 3000;
app.listen(port, () => {
  console.log(`LINE Bot server running on port ${port}`);
});

設定 Webhook URL

  1. 在 LINE Developers Console 的 Messaging API 設定中
  2. 填入你的 Webhook URL:https://your-domain.com/webhook
  3. 開啟「Use webhook」
  4. 點擊「Verify」確認連線成功

核心功能一:自動回覆(Reply Message)

Reply Message 是最基本的互動方式:用戶發送訊息 -> Webhook 收到事件 -> 回覆訊息。

文字回覆

async function handleEvent(event) {
  if (event.type !== 'message' || event.message.type !== 'text') {
    return null;
  }

  const userMessage = event.message.text;
  let replyText = '';

  // 關鍵字匹配
  switch (true) {
    case /營業時間/.test(userMessage):
      replyText = '我們的營業時間:\n週一至週五 10:00-20:00\n週六 10:00-18:00\n週日公休';
      break;
    case /價[格目]/.test(userMessage):
      replyText = '請參考我們的價目表:https://example.com/pricing';
      break;
    case /客服|聯繫/.test(userMessage):
      replyText = '請撥打客服專線:02-1234-5678\n或來信:support@example.com';
      break;
    default:
      replyText = '感謝您的訊息!我們的客服人員會盡快回覆您。';
  }

  return client.replyMessage({
    replyToken: event.replyToken,
    messages: [{ type: 'text', text: replyText }]
  });
}

圖片回覆

return client.replyMessage({
  replyToken: event.replyToken,
  messages: [{
    type: 'image',
    originalContentUrl: 'https://example.com/images/product.jpg',
    previewImageUrl: 'https://example.com/images/product-preview.jpg'
  }]
});

多訊息回覆

一次 Reply 最多可發送 5 則訊息:

return client.replyMessage({
  replyToken: event.replyToken,
  messages: [
    { type: 'text', text: '以下是我們的熱門商品:' },
    {
      type: 'image',
      originalContentUrl: 'https://example.com/product1.jpg',
      previewImageUrl: 'https://example.com/product1-thumb.jpg'
    },
    { type: 'text', text: '立即下單享 85 折:https://example.com/order' }
  ]
});

注意:Reply Message 必須在收到 Webhook 事件後的短時間內使用 replyToken 回覆。replyToken 的有效期很短(約 1 分鐘),過期後無法使用。

核心功能二:主動推播(Push Message)

Push Message 可以在任何時間主動發送訊息給用戶,不需要 replyToken。

單一用戶推播

// 發送訊息給特定用戶
await client.pushMessage({
  to: 'USER_ID',  // 用戶的 LINE User ID
  messages: [{
    type: 'text',
    text: '您的訂單 #12345 已出貨!預計明天到達。'
  }]
});

多人推播(Multicast)

一次最多可發送給 500 個用戶:

await client.multicast({
  to: ['USER_ID_1', 'USER_ID_2', 'USER_ID_3'],
  messages: [{
    type: 'text',
    text: '限時優惠:全館 85 折,今天 23:59 截止!'
  }]
});

全員推播(Broadcast)

發送給所有好友(計入訊息費用):

await client.broadcast({
  messages: [{
    type: 'text',
    text: '新品上市通知:春季限定系列已上架!'
  }]
});

窄播(Narrowcast)

結合受眾條件的精準推播:

await client.narrowcast({
  messages: [{
    type: 'text',
    text: '會員專屬:生日月份消費享雙倍點數!'
  }],
  recipient: {
    type: 'audience',
    audienceGroupId: 1234567890  // 預先建立的受眾群組 ID
  }
});

費用注意:Push Message 和 Broadcast 都會計入月訊息費用。務必搭配分眾策略,避免訊息費暴增。

核心功能三:Flex Message

Flex Message 是 LINE 最強大的訊息格式,允許你用 JSON 定義複雜的版面配置,實現類似「卡片」或「小型網頁」的效果。

基本結構

const flexMessage = {
  type: 'flex',
  altText: '商品推薦',
  contents: {
    type: 'bubble',
    hero: {
      type: 'image',
      url: 'https://example.com/product.jpg',
      size: 'full',
      aspectRatio: '20:13',
      aspectMode: 'cover'
    },
    body: {
      type: 'box',
      layout: 'vertical',
      contents: [
        {
          type: 'text',
          text: '春季限定保濕乳液',
          weight: 'bold',
          size: 'xl'
        },
        {
          type: 'text',
          text: 'NT$680',
          size: 'lg',
          color: '#DC2626',
          margin: 'md'
        },
        {
          type: 'text',
          text: '添加天然植物精華,深層保濕不黏膩。限量 500 組。',
          size: 'sm',
          color: '#666666',
          margin: 'md',
          wrap: true
        }
      ]
    },
    footer: {
      type: 'box',
      layout: 'vertical',
      contents: [
        {
          type: 'button',
          style: 'primary',
          color: '#DC2626',
          action: {
            type: 'uri',
            label: '立即購買',
            uri: 'https://example.com/buy/product-1'
          }
        }
      ]
    }
  }
};

Carousel 多張卡片

const carouselMessage = {
  type: 'flex',
  altText: '熱門商品推薦',
  contents: {
    type: 'carousel',
    contents: [
      // Bubble 1
      {
        type: 'bubble',
        hero: { /* 商品圖片 */ },
        body: { /* 商品資訊 */ },
        footer: { /* CTA 按鈕 */ }
      },
      // Bubble 2
      {
        type: 'bubble',
        hero: { /* 商品圖片 */ },
        body: { /* 商品資訊 */ },
        footer: { /* CTA 按鈕 */ }
      },
      // 最多 12 張卡片
    ]
  }
};

訂單通知 Flex Message

const orderNotification = {
  type: 'flex',
  altText: '訂單確認通知',
  contents: {
    type: 'bubble',
    body: {
      type: 'box',
      layout: 'vertical',
      contents: [
        {
          type: 'text',
          text: '訂單確認',
          weight: 'bold',
          size: 'xl',
          color: '#1DB446'
        },
        { type: 'separator', margin: 'lg' },
        {
          type: 'box',
          layout: 'vertical',
          margin: 'lg',
          contents: [
            {
              type: 'box',
              layout: 'horizontal',
              contents: [
                { type: 'text', text: '訂單編號', size: 'sm', color: '#555555', flex: 0 },
                { type: 'text', text: '#20260314001', size: 'sm', color: '#111111', align: 'end' }
              ]
            },
            {
              type: 'box',
              layout: 'horizontal',
              margin: 'md',
              contents: [
                { type: 'text', text: '訂單金額', size: 'sm', color: '#555555', flex: 0 },
                { type: 'text', text: 'NT$1,280', size: 'sm', color: '#DC2626', align: 'end', weight: 'bold' }
              ]
            },
            {
              type: 'box',
              layout: 'horizontal',
              margin: 'md',
              contents: [
                { type: 'text', text: '配送方式', size: 'sm', color: '#555555', flex: 0 },
                { type: 'text', text: '7-11 超商取貨', size: 'sm', color: '#111111', align: 'end' }
              ]
            }
          ]
        }
      ]
    }
  }
};

Flex Message Simulator

LINE 提供 Flex Message Simulator 線上工具,可以用拖拉的方式設計 Flex Message 並產生 JSON 程式碼。強烈建議使用這個工具來設計複雜版面。

[截圖參考:LINE Flex Message Simulator 介面,左側為設計區域,右側為 JSON 預覽]

核心功能四:Rich Menu API 控制

透過 API 可以實現比後台更靈活的 Rich Menu 管理:

建立 Rich Menu

const richMenu = {
  size: { width: 2500, height: 1686 },
  selected: true,
  name: '主選單',
  chatBarText: '選單',
  areas: [
    {
      bounds: { x: 0, y: 0, width: 833, height: 843 },
      action: { type: 'uri', uri: 'https://example.com/products' }
    },
    {
      bounds: { x: 833, y: 0, width: 834, height: 843 },
      action: { type: 'uri', uri: 'https://example.com/events' }
    },
    {
      bounds: { x: 1667, y: 0, width: 833, height: 843 },
      action: { type: 'message', text: '我要客服' }
    },
    // ... 更多區域
  ]
};

const richMenuId = await client.createRichMenu(richMenu);

為特定用戶設定 Rich Menu

// 為 VIP 會員顯示 VIP 專屬選單
await client.linkRichMenuIdToUser('USER_ID', 'VIP_RICH_MENU_ID');

// 解除用戶的個人 Rich Menu(恢復為預設)
await client.unlinkRichMenuIdFromUser('USER_ID');

Rich Menu 切換策略

// 用戶加好友時:顯示「新客歡迎版」Rich Menu
async function handleFollow(event) {
  await client.linkRichMenuIdToUser(
    event.source.userId,
    'NEW_FRIEND_RICH_MENU_ID'
  );
  // 發送歡迎訊息
  await client.replyMessage({
    replyToken: event.replyToken,
    messages: [{ type: 'text', text: '歡迎加入!看看我們為你準備了什麼。' }]
  });
}

// 用戶完成首購後:切換為「會員版」Rich Menu
async function handleFirstPurchase(userId) {
  await client.linkRichMenuIdToUser(userId, 'MEMBER_RICH_MENU_ID');
  await client.pushMessage({
    to: userId,
    messages: [{ type: 'text', text: '恭喜成為會員!你的專屬選單已更新。' }]
  });
}

進階整合:Webhook 事件處理

完整事件處理架構

async function handleEvent(event) {
  switch (event.type) {
    case 'message':
      return handleMessage(event);
    case 'follow':
      return handleFollow(event);      // 用戶加好友
    case 'unfollow':
      return handleUnfollow(event);    // 用戶封鎖
    case 'postback':
      return handlePostback(event);    // Postback 動作
    case 'memberJoined':
      return handleMemberJoined(event); // 加入群組
    default:
      return null;
  }
}

// 追蹤好友事件
async function handleFollow(event) {
  const userId = event.source.userId;
  // 取得用戶 Profile
  const profile = await client.getProfile(userId);
  // 儲存到資料庫
  await saveUserToDatabase({
    lineUserId: userId,
    displayName: profile.displayName,
    pictureUrl: profile.pictureUrl,
    followedAt: new Date()
  });
  // 發送歡迎訊息 + 設定 Rich Menu
  // ...
}

// 封鎖事件
async function handleUnfollow(event) {
  const userId = event.source.userId;
  await updateUserStatus(userId, 'blocked');
  // 記錄封鎖原因分析用
}

// Postback 事件(來自 Flex Message 按鈕或 Rich Menu)
async function handlePostback(event) {
  const data = new URLSearchParams(event.postback.data);
  const action = data.get('action');

  switch (action) {
    case 'check_order':
      const orderId = data.get('orderId');
      const order = await getOrderFromDatabase(orderId);
      // 回覆訂單狀態
      break;
    case 'book_appointment':
      const date = event.postback.params?.date;
      // 處理預約
      break;
  }
}

安全性注意事項

Webhook 簽章驗證

LINE Bot SDK 會自動驗證 Webhook 請求的簽章,確保請求來自 LINE 伺服器。如果你使用自訂中介層,務必驗證 X-Line-Signature header:

const crypto = require('crypto');

function validateSignature(body, signature, channelSecret) {
  const hash = crypto
    .createHmac('SHA256', channelSecret)
    .update(body)
    .digest('base64');
  return hash === signature;
}

速率限制

  • Reply Message:無限制(只要有有效的 replyToken)
  • Push Message:依方案不同有不同的速率限制
  • API 呼叫:每分鐘最多 2,000 次

用戶資料保護

  • 不要在日誌中記錄用戶的完整 User ID
  • 用戶 Profile 資料僅用於服務目的
  • 遵守 LINE Platform 的使用條款和隱私政策

常見問題與除錯

Q1:Webhook 收不到事件?

  1. 確認 Webhook URL 是 HTTPS
  2. 確認「Use webhook」已開啟
  3. 確認伺服器回傳 HTTP 200
  4. 檢查 LINE Developers Console 的 Webhook 測試結果

Q2:Reply 訊息沒有送出?

  1. replyToken 可能已過期(超過 1 分鐘)
  2. 一個 replyToken 只能使用一次
  3. 確認 Channel Access Token 正確

Q3:Push Message 發送失敗?

  1. 確認 User ID 格式正確(U 開頭的 33 字元字串)
  2. 確認用戶沒有封鎖帳號
  3. 檢查月訊息餘額是否用完

結語

LINE Messaging API 提供了強大的自動化能力,從基本的關鍵字回覆到複雜的 Chatbot 流程,都能透過 API 實現。關鍵是從簡單的功能開始,逐步增加複雜度,並持續監控用戶互動數據來優化體驗。

如果你需要專業的 LINE Bot 開發或 Messaging API 整合服務,歡迎聯繫 RedClaw 團隊。我們擁有豐富的 LINE 技術整合經驗,能幫助你建立高效的自動化行銷系統。


本文由 RedClaw 團隊撰寫。更多 LINE 技術整合與自動化行銷內容,請持續關注我們的部落格。


了解我們的行銷自動化服務 →

分享:

讓你的廣告預算發揮最大效益

從帳號養成到數據追蹤,一站式搞定。

  • 專屬客戶經理,即時優化投放策略
  • 完整追蹤架構,每一分錢花得明明白白
  • 跨平台投放經驗,Meta / Google / TikTok

免費獲取您的廣告健檢報告

讓我們的專家分析您的廣告帳戶,找出浪費預算的關鍵問題。

100% 免費48 小時內回覆無綁約

📬 訂閱電子報

每週一封,投放實戰、產業趨勢、工具教學。不灌水,純乾貨。

我們不會分享你的 Email。隨時可以取消訂閱。