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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| import express from "express"; import axios from "axios"; import crypto from "crypto"; import mysql from "mysql2/promise";
const router = express.Router();
const pool = mysql.createPool({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME, });
function validateSignature(body, signature) { const hash = crypto .createHmac("SHA256", process.env.LINE_CHANNEL_SECRET) .update(JSON.stringify(body)) .digest("base64"); return hash === signature; }
router.post("/webhook", async (req, res) => { const signature = req.headers["x-line-signature"]; if (!validateSignature(req.body, signature)) { return res.status(401).send("Invalid signature"); }
const events = req.body.events; for (const event of events) { if (event.type === "message" && event.message.type === "text") { const userText = event.message.text.trim(); const userName = event.source.userId || "LINE使用者";
let replyMessage = "";
if (userText.startsWith("商品")) { const itemCode = userText.replace("商品", "").trim(); const [rows] = await pool.query( "SELECT name, price, description FROM products WHERE id = ?", [itemCode] );
if (rows.length > 0) { const p = rows[0]; replyMessage = `📦 商品名稱:${p.name}\n💲 價格:${p.price}\n📝 說明:${p.description}\n\n若要下單,請輸入:購買 ${itemCode}`; } else { replyMessage = "查無此商品,請確認代號是否正確。"; } }
else if (userText.startsWith("購買")) { const itemCode = userText.replace("購買", "").trim();
const [rows] = await pool.query( "SELECT name, price FROM products WHERE id = ?", [itemCode] );
if (rows.length === 0) { replyMessage = "找不到該商品,請確認代號。"; } else { await pool.query( `INSERT INTO orders (user_name, product_id, quantity, status, created_at) VALUES (?, ?, 1, '新訂單', NOW())`, [userName, itemCode] );
const product = rows[0]; replyMessage = `✅ 已建立訂單:${product.name}\n💲 價格:${product.price}\n📦 狀態:新訂單`; } }
else { replyMessage = "您好!請輸入:\n「商品 1」查詢商品\n或「購買 1」直接下單。"; }
await axios.post( "https://api.line.me/v2/bot/message/reply", { replyToken: event.replyToken, messages: [{ type: "text", text: replyMessage }], }, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.LINE_CHANNEL_ACCESS_TOKEN}`, }, } ); } }
res.status(200).end(); });
export default router;
|