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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
| import express from "express"; import { middleware, Client } from "@line/bot-sdk"; import dotenv from "dotenv"; import { pool } from "../db.js";
dotenv.config();
const router = express.Router();
const config = { channelAccessToken: process.env.LINE_CHANNEL_ACCESS_TOKEN, channelSecret: process.env.LINE_CHANNEL_SECRET, }; const client = new Client(config);
router.post("/webhook", middleware(config), async (req, res) => { try { const events = req.body.events || [];
for (const event of events) { if (event.type === "message" && event.message.type === "text") { const text = event.message.text.trim(); if (text === "我要點餐" || text === "點餐") { const [products] = await pool.query( "SELECT id, name, price, description, image_url FROM products LIMIT 10" );
const bubbles = products.map((p) => ({ type: "bubble", hero: p.image_url ? { type: "image", url: p.image_url, size: "full", aspectRatio: "20:13", aspectMode: "cover", } : undefined, body: { type: "box", layout: "vertical", contents: [ { type: "text", text: p.name, weight: "bold", size: "lg" }, { type: "text", text: `價格:$${p.price}`, size: "sm" }, { type: "text", text: p.description || "", size: "sm", wrap: true }, ], }, footer: { type: "box", layout: "vertical", contents: [ { type: "button", style: "primary", action: { type: "postback", label: "購買", data: `action=buy&productId=${p.id}&qty=1`, }, }, ], }, }));
const flex = { type: "carousel", contents: bubbles.length ? bubbles : [ { type: "bubble", body: { type: "box", layout: "vertical", contents: [{ type: "text", text: "目前無商品" }], }, }, ], };
await client.replyMessage(event.replyToken, { type: "flex", altText: "商品列表", contents: flex, }); continue; }
await client.replyMessage(event.replyToken, { type: "text", text: "請輸入「我要點餐」開始下單流程。", }); }
else if (event.type === "postback") { const qs = new URLSearchParams(event.postback.data); const action = qs.get("action"); if (action === "buy") { const productId = parseInt(qs.get("productId")); const qty = parseInt(qs.get("qty") || "1"); const userId = event.source.userId;
const [[prod]] = await pool.query( "SELECT id, name, price FROM products WHERE id = ?", [productId] ); if (!prod) { await client.replyMessage(event.replyToken, { type: "text", text: "找不到該商品,請稍後再試。", }); continue; }
const conn = await pool.getConnection(); try { await conn.beginTransaction();
const subtotal = Number(prod.price) * qty; const orderNo = `L${Date.now().toString().slice(-6)}`;
const [r] = await conn.query( "INSERT INTO orders (order_no, user_line_id, total_price) VALUES (?, ?, ?)", [orderNo, userId, subtotal] ); const orderId = r.insertId;
await conn.query( "INSERT INTO order_items (order_id, product_id, product_name, qty, unit_price, subtotal) VALUES (?, ?, ?, ?, ?, ?)", [orderId, prod.id, prod.name, qty, prod.price, subtotal] );
await conn.commit();
await client.replyMessage(event.replyToken, { type: "text", text: `✅ 已建立訂單\n編號:${orderNo}\n商品:${prod.name}\n數量:${qty}\n金額:$${subtotal}`, });
if (process.env.ADMIN_LINE_ID) { await client.pushMessage(process.env.ADMIN_LINE_ID, { type: "text", text: `📦 新訂單:${orderNo}\n商品:${prod.name} x${qty}`, }); } } catch (err) { await conn.rollback(); console.error("Create order failed:", err); await client.replyMessage(event.replyToken, { type: "text", text: "建立訂單失敗,請稍後再試。", }); } finally { conn.release(); } } } }
res.status(200).send("OK"); } catch (err) { console.error("Webhook error:", err); res.status(500).end(); } });
export default router;
|