You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Cashier Stripe订阅报错:读取null的default_payment_method属性

问题分析与解决方案

错误Attempt to read property "default_payment_method" on null的核心原因是订阅接口中$request->user()返回了null——代码尝试在未认证的用户实例上调用订阅方法,导致后续链式调用失败抛出该错误。

排查与修复步骤

1. 确保订阅接口受认证中间件保护

检查路由配置,确保订阅提交接口被auth中间件保护,仅允许登录用户访问:

// routes/web.php
use App\Http\Controllers\SubscriptionController;

Route::post('/user/subscription', [SubscriptionController::class, 'subscription'])
    ->middleware('auth');

2. 订阅接口代码加固

在接口中先验证用户身份与计划存在性,避免null调用:

public function subscription(Request $request)
{
    // 确认用户已认证
    $user = $request->user();
    if (!$user) {
        return redirect()->back()->withErrors('请先登录');
    }

    $plan = Plan::where('slug', 'standard')->first();
    // 确保订阅计划存在
    if (!$plan) {
        return redirect()->back()->withErrors('订阅计划不存在');
    }

    try {
        $subscription = $user
            ->newSubscription($plan->slug, $plan->stripe_plan)
            ->create($request->paymentMethod);

        $subscription->ends_at = Carbon::now()->addDays(6);
        $subscription->save();

        return redirect()->to('user/payment');
    } catch (\Exception $e) {
        // 捕获错误并返回提示
        return redirect()->back()->withErrors($e->getMessage());
    }
}

3. 前端代码修正笔误

前端错误处理中存在按钮状态设置错误,修正后避免按钮永久禁用:

if(error) {
    cardBtn.disabled = false; // 修正属性名,原代码为disable
} else {
    let token = document.createElement('input')
    token.setAttribute('type', 'hidden')
    token.setAttribute('name', 'paymentMethod')
    token.setAttribute('value', setupIntent.payment_method)
    form.appendChild(token)
    form.submit();
}

4. 额外验证点

  • 确认Plan模型的stripe_plan字段存储的是正确的Stripe计划ID(格式如price_xxxxxx)。
  • 检查.env文件中STRIPE_KEY和STRIPE_SECRET是否与Stripe后台配置一致。

内容的提问来源于stack exchange,提问作者Marco Roys

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:22:39