Skip to content

建立 2026-09-14 更新 2026-09-14

Python 收款

用 Python 寫金流,本質上是三個 HTTP 端點加上正確的金額計算:

  1. 建立付款POST /create-checkout-sessionPOST /create-payment-intent
  2. 給顧客付款畫面:導向 Stripe 或在自己的頁面掛 Payment Element
  3. 履約POST /webhook 驗證簽章後改訂單狀態

其餘都是這三步的變化(訂閱改 mode、退款呼叫 Refund API)。

最小後端長什麼樣子

import os
import stripe
from flask import Flask, redirect, request

app = Flask(__name__)
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]

@app.post("/buy")
def buy():
    session = stripe.checkout.Session.create(
        mode="payment",
        line_items=[{"price": "price_你的價格ID", "quantity": 1}],
        success_url="http://localhost:4242/success",
        cancel_url="http://localhost:4242/cancel",
    )
    return redirect(session.url, code=303)

這已經是一筆能收測試款的程式。缺的是 webhook:沒有它,你無法可靠地知道顧客付了沒有。

這一節的閱讀順序

  1. Checkout 託管頁 — 先做這個,最快、也最不容易踩 PCI
  2. Webhook 履約 — 與 Checkout 成套,不要跳過
  3. PaymentIntent 自訂表單 — 需要留在自己網站時再做
  4. 訂閱mode="subscription"
  5. 本 repo 範例 — 說明根目錄現成的 Flask + Payment Element

官方逐步影片見 官方影音,Python Checkout 與 Payment Element 兩支都已嵌入。