DeepLearning101 commited on
Commit
9046eac
·
verified ·
1 Parent(s): 69ccd49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -1
app.py CHANGED
@@ -4,6 +4,12 @@ import pandas as pd
4
  import requests
5
  from supabase import create_client, Client
6
  from datetime import datetime, timedelta, timezone
 
 
 
 
 
 
7
 
8
  # --- 設定時區與環境變數 ---
9
  TAIPEI_TZ = timezone(timedelta(hours=8))
@@ -13,6 +19,11 @@ SUPABASE_KEY = os.getenv("SUPABASE_KEY")
13
  GAS_MAIL_URL = os.getenv("GAS_MAIL_URL")
14
  LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
15
 
 
 
 
 
 
16
  # 改回使用 GitHub Pages 網址,確保客人點擊信件能回到充滿設計感的前台
17
  PUBLIC_SPACE_URL = os.getenv("HF_SPACE_URL", "https://ciecietaipei.github.io/booking.html")
18
 
@@ -149,6 +160,60 @@ def update_booking_status(booking_id, new_status):
149
  except Exception as e:
150
  return f"❌ 狀態更新失敗: {str(e)}"
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  def render_booking_cards():
153
  df = get_bookings()
154
  count_html = f"<div style='color:#bbb; margin-bottom:10px; text-align:right; font-size:14px;'>📊 共 <span style='color:#fff; font-weight:bold;'>{len(df)}</span> 筆資料</div>"
@@ -351,8 +416,8 @@ with gr.Blocks(title="Cié Cié Admin", css=custom_css, theme=gr.themes.Monochro
351
  with gr.Row():
352
  send_btn = gr.Button("🚀 發信/LINE", variant="primary", scale=1)
353
  update_status_btn = gr.Button("💾 變更狀態", variant="secondary", scale=1)
 
354
  noshow_btn = gr.Button("🚫 標記 No-Show", variant="stop", scale=1)
355
- revert_noshow_btn = gr.Button("✅ 撤銷 No-Show", scale=1)
356
  refresh_btn = gr.Button("🔄 刷新列表", scale=1)
357
 
358
  log_output = gr.Textbox(label="執行結果日誌", lines=1)
@@ -366,6 +431,8 @@ with gr.Blocks(title="Cié Cié Admin", css=custom_css, theme=gr.themes.Monochro
366
  outputs=log_output
367
  ).then(render_booking_cards, outputs=booking_display)
368
 
 
 
369
  # 其餘按鈕事件
370
  refresh_btn.click(render_booking_cards, outputs=booking_display)
371
  send_btn.click(send_confirmation_hybrid, inputs=id_input, outputs=log_output).then(render_booking_cards, outputs=booking_display)
 
4
  import requests
5
  from supabase import create_client, Client
6
  from datetime import datetime, timedelta, timezone
7
+ import json
8
+ import base64
9
+ import hashlib
10
+ import hmac
11
+ import uuid
12
+ import urllib.parse
13
 
14
  # --- 設定時區與環境變數 ---
15
  TAIPEI_TZ = timezone(timedelta(hours=8))
 
19
  GAS_MAIL_URL = os.getenv("GAS_MAIL_URL")
20
  LINE_ACCESS_TOKEN = os.getenv("LINE_ACCESS_TOKEN")
21
 
22
+ # --- 新增:LINE Pay 查詢用金鑰 ---
23
+ LINE_PAY_CHANNEL_ID = os.getenv("LINE_PAY_CHANNEL_ID", "")
24
+ LINE_PAY_CHANNEL_SECRET = os.getenv("LINE_PAY_CHANNEL_SECRET", "")
25
+ LINE_PAY_BASE_URL = "https://sandbox-api-pay.line.me"
26
+
27
  # 改回使用 GitHub Pages 網址,確保客人點擊信件能回到充滿設計感的前台
28
  PUBLIC_SPACE_URL = os.getenv("HF_SPACE_URL", "https://ciecietaipei.github.io/booking.html")
29
 
 
160
  except Exception as e:
161
  return f"❌ 狀態更新失敗: {str(e)}"
162
 
163
+ # 🌟 新增:向 LINE Pay 總部查詢真實付款狀態 🌟
164
+ def check_linepay_status(booking_id):
165
+ if not booking_id: return "❌ 請輸入訂單 ID"
166
+ if not LINE_PAY_CHANNEL_SECRET: return "⚠️ 系統未設定 LINE Pay 金鑰,無法查詢"
167
+
168
+ try:
169
+ # 1. 從資料庫抓取這筆訂單的備註,找出專屬訂單號 (ORDER-XXXX)
170
+ res = supabase.table("bookings").select("*").eq("id", booking_id).execute()
171
+ if not res.data: return f"❌ 找不到訂單 ID: {booking_id}"
172
+
173
+ remarks = res.data[0].get('remarks', '')
174
+ order_id = None
175
+ for line in remarks.split('\n'):
176
+ if "訂單號:" in line:
177
+ order_id = line.split(":")[-1].strip()
178
+
179
+ if not order_id:
180
+ return "⚠️ 此筆訂單沒有 LINE Pay 訂單號 (可能為免訂金或舊訂單)"
181
+
182
+ # 2. 生成 LINE Pay V3 查詢專用加密簽章
183
+ uri = "/v3/payments"
184
+ query_string = urllib.parse.urlencode({"orderId": order_id})
185
+ nonce = str(uuid.uuid4())
186
+ message = LINE_PAY_CHANNEL_SECRET + uri + query_string + nonce
187
+ signature = base64.b64encode(hmac.new(LINE_PAY_CHANNEL_SECRET.encode(), message.encode(), hashlib.sha256).digest()).decode()
188
+
189
+ headers = {
190
+ "Content-Type": "application/json",
191
+ "X-LINE-ChannelId": LINE_PAY_CHANNEL_ID,
192
+ "X-LINE-Authorization-Nonce": nonce,
193
+ "X-LINE-Authorization": signature
194
+ }
195
+
196
+ # 3. 發送查詢請求
197
+ r = requests.get(f"{LINE_PAY_BASE_URL}{uri}?{query_string}", headers=headers)
198
+ res_data = r.json()
199
+
200
+ # 4. 解析 LINE Pay 回傳的結果
201
+ if res_data.get("returnCode") == "0000":
202
+ info = res_data.get("info", [])
203
+ if not info:
204
+ return f"ℹ️ LINE Pay 回報:此訂單尚未有交易紀錄 (客人可能未掃碼或已關閉結帳網頁)"
205
+
206
+ tx = info[0]
207
+ status_map = { "AUTHORIZATION": "授權中", "PAYMENT": "✅ 付款成功", "CANCELED": "🚫 已取消", "FAIL": "❌ 付款失敗" }
208
+ status_text = status_map.get(tx.get("transactionType"), tx.get("transactionType"))
209
+ amount = tx.get("payInfo", [{}])[0].get("amount", 0)
210
+
211
+ return f"🔍 LINE Pay 查詢結果: [{status_text}] 金額: ${amount} (交易序號: {tx.get('transactionId')})"
212
+ else:
213
+ return f"❌ 查詢失敗: {res_data.get('returnMessage')}"
214
+ except Exception as e:
215
+ return f"❌ 系統錯誤: {str(e)}"
216
+
217
  def render_booking_cards():
218
  df = get_bookings()
219
  count_html = f"<div style='color:#bbb; margin-bottom:10px; text-align:right; font-size:14px;'>📊 共 <span style='color:#fff; font-weight:bold;'>{len(df)}</span> 筆資料</div>"
 
416
  with gr.Row():
417
  send_btn = gr.Button("🚀 發信/LINE", variant="primary", scale=1)
418
  update_status_btn = gr.Button("💾 變更狀態", variant="secondary", scale=1)
419
+ check_lp_btn = gr.Button("🔍 查 LINE Pay", variant="secondary", scale=1)
420
  noshow_btn = gr.Button("🚫 標記 No-Show", variant="stop", scale=1)
 
421
  refresh_btn = gr.Button("🔄 刷新列表", scale=1)
422
 
423
  log_output = gr.Textbox(label="執行結果日誌", lines=1)
 
431
  outputs=log_output
432
  ).then(render_booking_cards, outputs=booking_display)
433
 
434
+ check_lp_btn.click(check_linepay_status, inputs=[id_input], outputs=log_output)
435
+
436
  # 其餘按鈕事件
437
  refresh_btn.click(render_booking_cards, outputs=booking_display)
438
  send_btn.click(send_confirmation_hybrid, inputs=id_input, outputs=log_output).then(render_booking_cards, outputs=booking_display)