概述
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 后台创建的 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 并传给视图。client_secret。
setup_intent 参数。使用它获取 Payment Method ID,然后创建订阅。
在单次支付中使用
对于单次支付,使用pay() 创建 Payment Intent。Order 模型需要包含 user_id、amount、status、stripe_payment_intent_id 字段。
payment_intent 参数查找 Order,并在确认 Payment Intent 属于当前已认证用户且状态为 succeeded 之后再完成订单。
发票
使用invoices() 可以获取发票列表。
dompdf/dompdf,然后使用 downloadInvoice()。$invoiceId 传入通过 invoices() 得到的发票 ID。
Webhook 配置
Cashier 会自动为 Stripe Webhook 注册路由,默认使用/stripe/webhook。请在 Stripe 后台中配置该 URL。
可以通过 cashier:webhook 命令创建 Webhook。
stripe/* 从 CSRF 保护中排除。
.env 中配置 STRIPE_WEBHOOK_SECRET 后,Cashier 的签名校验中间件就能对 Webhook 请求进行校验。