# LIFF：在 LINE 裡開網頁

LIFF（LINE Front-end Framework）讓你的網頁在 LINE App 裡面開啟，而且能取得使用者的 LINE 名稱與大頭貼、替使用者在聊天室送出訊息。訊息介面不適合做的事，例如填寫多欄表單、選購物車、看會員資料，就交給 LIFF 網頁處理，完成後再回到聊天室。本頁做一個「活動報名表單」：使用者從 Bot 打開表單、填完送出，報名資訊會以訊息出現在聊天室，Bot 再接手處理。

## LIFF 的運作方式

```
sequenceDiagram
    participant U as 使用者
    participant B as Bot（聊天室）
    participant L as LIFF 網頁
    B->>U: 傳送「我要報名」按鈕（https://liff.line.me/LIFF_ID）
    U->>L: 點按鈕，在 LINE 內開啟網頁
    L->>L: liff.init() → liff.getProfile() 取得名稱
    U->>L: 填寫表單、送出
    L->>B: liff.sendMessages() 以使用者身分送出「報名：…」
    L->>L: liff.closeWindow() 回到聊天室
    B->>U: Webhook 收到訊息，回覆報名成功
```

## 把網頁放上 HTTPS

LIFF 網頁必須是 **HTTPS**。最簡單的免費做法是 **GitHub Pages**：

1. 在 GitHub 建立一個 repo，例如 `liff-demo`。
2. 上傳 `index.html`（內容見步驟 3，先上傳也可以，之後再改 LIFF ID）。
3. repo 的 **Settings \> Pages**，Source 選 `main` 分支，儲存。
4. 幾分鐘後得到網址 `https://你的帳號.github.io/liff-demo/`。

Netlify、Vercel、Cloudflare Pages，或你部署 Flask 的同一台伺服器也都可以。

## 建立 LIFF App

LIFF App 要建在 **LINE Login channel** 底下（不是 Messaging API channel）：

1. 到 [LINE Developers Console](<https://developers.line.biz/console/>)，選擇**和 Bot 相同的 Provider**。
2. **Create a new channel \> LINE Login**，填寫名稱等資料，App types 勾選 **Web app**。
3. 進入新 channel 的 **LIFF** 分頁，點 **Add**：

| 欄位 | 設定 |
| --- | --- |
| LIFF app name | 活動報名 |
| Size | **Tall**（`Full` 全螢幕、`Tall` 約 80%、`Compact` 約 50%） |
| Endpoint URL | 步驟 1 的 GitHub Pages 網址 |
| Scopes | 勾選 `profile`、`chat_message.write`（`sendMessages` 需要） |
| Bot link feature | **On (Normal)**：登入時提示加 Bot 好友 |

1. 建立後複製 **LIFF ID**（格式像 `1234567890-AbcdEfgh`），LIFF 網址是 `https://liff.line.me/LIFF_ID`。

> [!NOTE]
>
> **為什麼要同一個 Provider？**
>
> LINE 的 user ID 是以 Provider 為單位產生的。LINE Login channel 和 Messaging API channel 在同一個 Provider 底下，LIFF 取得的 `userId` 才會和 Bot webhook 收到的一致，兩邊的資料才能對起來。

## 撰寫 LIFF 網頁

把 `LIFF_ID` 換成自己的，上傳到 GitHub Pages：

index.html

```
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>活動報名</title>
  <style>
    body { font-family: system-ui, sans-serif; margin: 0; padding: 24px; background: #f5f5f5; }
    .card { background: #fff; border-radius: 12px; padding: 20px; max-width: 420px; margin: auto; }
    .profile { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; }
    .profile img { width: 48px; height: 48px; border-radius: 50%; }
    label { display: block; margin: 12px 0 4px; font-weight: 600; }
    input, select { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 8px; box-sizing: border-box; }
    button { width: 100%; margin-top: 20px; padding: 12px; font-size: 16px; border: 0; border-radius: 8px; background: #06C755; color: #fff; }
    #status { color: #c00; margin-top: 12px; }
  </style>
</head>
<body>
  <div class="card">
    <div class="profile">
      <img id="avatar" alt="">
      <div>你好，<strong id="name">…</strong></div>
    </div>
    <form id="form">
      <label for="session">場次</label>
      <select id="session">
        <option>12/20（六）上午場</option>
        <option>12/20（六）下午場</option>
      </select>
      <label for="people">人數</label>
      <input id="people" type="number" min="1" max="5" value="1">
      <button type="submit">送出報名</button>
    </form>
    <p id="status"></p>
  </div>

  <script charset="utf-8" src="https://static.line-scdn.net/liff/edge/2/sdk.js"></script>
  <script>
    const LIFF_ID = '請換成你的 LIFF ID'; // 例如 1234567890-AbcdEfgh
    const status = document.getElementById('status');

    liff.init({ liffId: LIFF_ID })
      .then(async () => {
        // 在外部瀏覽器開啟時需要先登入；在 LINE App 內開啟會自動登入
        if (!liff.isLoggedIn()) {
          liff.login();
          return;
        }
        const profile = await liff.getProfile();
        document.getElementById('name').textContent = profile.displayName;
        document.getElementById('avatar').src = profile.pictureUrl || '';
      })
      .catch((err) => { status.textContent = 'LIFF 初始化失敗：' + err.message; });

    document.getElementById('form').addEventListener('submit', async (e) => {
      e.preventDefault();
      const session = document.getElementById('session').value;
      const people = document.getElementById('people').value;

      // sendMessages 只能在「從聊天室開啟的 LIFF」使用，且 LIFF 要勾選 chat_message.write
      if (!liff.isInClient()) {
        status.textContent = '請從 LINE 聊天室中開啟此頁面';
        return;
      }
      try {
        await liff.sendMessages([{ type: 'text', text: `報名：${session}，${people} 人` }]);
        liff.closeWindow(); // 送出後關閉 LIFF，回到聊天室
      } catch (err) {
        status.textContent = '送出失敗：' + err.message;
      }
    });
  </script>
</body>
</html>
```

LIFF SDK 常用 API：

| API | 說明 |
| --- | --- |
| `liff.init({ liffId })` | 初始化，**一定要先呼叫**，其他 API 都要在它完成後使用 |
| `liff.isInClient()` | 是否在 LINE App 內開啟 |
| `liff.isLoggedIn()`／`liff.login()` | 檢查登入、導向 LINE 登入（外部瀏覽器才需要） |
| `liff.getProfile()` | 取得 `userId`、`displayName`、`pictureUrl` |
| `liff.sendMessages([...])` | 以使用者身分在聊天室送出訊息（需 `chat_message.write`，且要從聊天室開啟） |
| `liff.shareTargetPicker([...])` | 讓使用者挑選好友或群組分享訊息 |
| `liff.scanCodeV2()` | 開啟 QR code 掃描器 |
| `liff.closeWindow()` | 關閉 LIFF 視窗 |
| `liff.getIDToken()` | 取得 ID token，送到後端驗證使用者身分 |

## 從 Bot 打開 LIFF

用 `uri` Action 指向 LIFF 網址，按鈕可以放在 Flex、Template 或圖文選單：

```
from linebot.v3.messaging import ButtonsTemplate, TemplateMessage, URIAction

LIFF_URL = "https://liff.line.me/1234567890-AbcdEfgh"

signup = TemplateMessage(
    alt_text="活動報名",
    template=ButtonsTemplate(
        title="12/20 LINE Bot 工作坊",
        text="名額有限，請填寫報名表",
        actions=[URIAction(label="我要報名", uri=LIFF_URL)],
    ),
)
```

## Bot 接手處理報名訊息

使用者送出表單後，聊天室會出現「報名：12/20（六）上午場，2 人」，Bot 在文字訊息處理函式裡解析它即可：

```
import re

m = re.match(r"^報名：(.+)，(\d+) 人$", text)
if m:
    session, people = m[1], int(m[2])
    # 存進資料庫或試算表……
    reply(event, TextMessage(text=f"報名成功！{session}，共 {people} 人"))
```

> [!WARNING]
>
> **sendMessages 的內容可以被偽造**
>
> 使用者也能自己打字送出「報名：…」，所以這種做法只適合不涉及金錢或權限的情境。重要資料應該讓 LIFF 網頁直接呼叫你的後端 API，並附上 `liff.getIDToken()`，由後端向 LINE 驗證 ID token 確認身分後再寫入資料庫。

## 測試

1. 把 LIFF 按鈕加進 Bot（例如輸入「報名」時回覆上面的 `signup`），重新部署或重啟程式。
2. 在手機 LINE 點按鈕，表單會從畫面下方滑出，並顯示你的 LINE 名稱與大頭貼。
3. 送出後視窗關閉，聊天室出現報名訊息，Bot 回覆報名成功。

除錯時可以在電腦瀏覽器直接打開 LIFF 網址，會先導向 LINE 登入；但 `sendMessages` 只能在 LINE App 內測試。

## 相關資料

- [LIFF 文件](<https://developers.line.biz/en/docs/liff/overview/>)
- [LIFF API reference](<https://developers.line.biz/en/reference/liff/>)
- [Developing a LIFF app](<https://developers.line.biz/en/docs/liff/developing-liff-apps/>)
