Skip to main content

概觀

Laravel Cashier (Stripe) 是官方套件,讓你可以在 Laravel 中操作 Stripe 的計費功能。你可以透過統一的 API 實作訂閱的建立、狀態確認、取消、一次性付款、發票下載與 Webhook 處理。

安裝與設定

首先安裝 Cashier 並建立必要的資料表。
接著在 App\Models\User 等計費對象模型加入 Billable trait。
.env 中設定 Stripe 金鑰。

顧客管理

若尚未建立 Stripe Customer,可以使用 createOrGetStripeCustomer()
若要明確建立,使用 createAsStripeCustomer()

訂閱

建立新訂閱

透過 newSubscription()create() 開始訂閱。 $paymentMethodId 請傳入透過 Stripe.js 等取得的 Payment Method ID。
price_monthly 只是範例。實作時請指定你在 Stripe Dashboard 中建立的實際 Price ID。

狀態確認

可透過 subscribed() 檢查訂閱是否有效。

取消與恢復

一次性付款 (Charge)

透過 charge() 可以進行一次性扣款。金額請以幣別的最小單位傳入(例如 USD 時,100 代表 $1.00)。 此處的 $paymentMethodId 同樣使用在 Stripe 建立的 Payment Method ID。
若扣款失敗,charge() 會拋出例外。

Payment Element

使用 Stripe 的 Payment Element,可以統一處理信用卡、Apple Pay、Google Pay、iDEAL 等多種付款方式。

用於訂閱

建立 Setup Intent 並傳入視圖。
在 Blade 視圖中掛載 Payment Element,並傳入 Setup Intent 的 client_secret
Stripe 的重新導向網址會附加 setup_intent 參數。可透過它取得 Payment Method ID 並建立訂閱。

用於一次性付款

在一次性付款中透過 pay() 建立 Payment Intent。Order 模型需要 user_idamountstatusstripe_payment_intent_id 欄位。
掛載 Payment Element 並確認付款。
重新導向後,透過 payment_intent 參數找出對應的 Order,確認 Payment Intent 屬於已認證使用者且狀態為 succeeded,再確定訂單。

發票

發票清單可透過 invoices() 取得。
如需 PDF 下載,請安裝 dompdf/dompdf 並使用 downloadInvoice()$invoiceId 請傳入透過 invoices() 取得的發票 ID。

設定 Webhook

Cashier 會自動註冊 Stripe Webhook 專用的路由,預設使用 /stripe/webhook。請於 Stripe Dashboard 設定此 URL。 可透過 cashier:webhook 建立 Webhook。
請將 stripe/* 排除於 CSRF 保護之外。
.env 中設定 STRIPE_WEBHOOK_SECRET,Cashier 的簽章驗證中介軟體便可驗證 Webhook 請求。
最後修改於 2026年8月2日