2025-06-27 Line 訂單系統-階段C

2025-06-27 Line 訂單系統-階段C

🅲 階段 C:LINE Webhook 整合

🎯 目標

建立能與 LINE Bot 通訊的 Webhook,並寫入 MySQL 訂單。


🔧 步驟

1️⃣ 設定 LINE Messaging API

  1. LINE Developers Console

  2. 建立 Provider & Channel(Messaging API)

  3. 取得:

    • Channel Secret
    • Channel Access Token

2️⃣ 安裝 LINE SDK

1
npm install @line/bot-sdk

3️⃣ 新增 webhook 路由(backend/routes/line.js)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import express from 'express';
import { middleware, Client } from '@line/bot-sdk';
import dotenv from 'dotenv';
dotenv.config();

const router = express.Router();

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

const client = new Client(config);

router.post('/webhook', middleware(config), async (req, res) => {
const events = req.body.events;
for (const event of events) {
if (event.type === 'message' && event.message.type === 'text') {
const msg = event.message.text;
if (msg === '我要點餐') {
await client.replyMessage(event.replyToken, {
type: 'text',
text: '請選擇商品:拿鐵、黑咖啡、抹茶拿鐵',
});
}
}
}
res.status(200).end();
});

export default router;

4️⃣ 修改 index.js

1
2
import lineRouter from './routes/line.js';
app.use('/line', lineRouter);

5️⃣ 用 ngrok 測試

1
ngrok http 3000

複製 ngrok URL,例如 https://abcd1234.ngrok.io/line/webhook
貼到 LINE Developers → Webhook URL。


🧪 Checkpoint

✅ 手機傳「我要點餐」→ LINE 回覆「請選擇商品」
✅ Webhook 可觸發


💡 延伸

  • 將訊息內容寫入 MySQL。
  • 建立商品 carousel message。