Laravel Cashier cancel()抛出BadMethodCallException

时间:2018-06-03 10:14:41

标签: php laravel laravel-5.5 laravel-cashier

我使用Laravel Cashier来处理我的用户订阅,但是当我尝试执行基本取消$user->subscription('main')->cancel()时,会抛出异常

  

BadMethodCallException:在

中调用未定义的方法Illuminate \ Database \ Query \ Builder :: asStripeCustomer()      

\试\厂商\ laravel \框架\ SRC \照亮\数据库\查询\ Builder.php:2483

堆栈追踪:

  

\try\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php(1470): Illuminate\Database\Eloquent\Builder->__call('asStripeCustome...', Array)

     

\try\vendor\laravel\cashier\src\Subscription.php(345): Illuminate\Database\Eloquent\Model->__call('asStripeCustome...', Array)

     

\try\vendor\laravel\cashier\src\Subscription.php(256): Laravel\Cashier\Subscription->asStripeSubscription()

我正确设置了模型并且使用了Billable特性,所以我真的不知道是什么造成了这个错误

应用\ user.php的

use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;

class User extends Authenticatable{
   use Billable;

   ...
}

应用\ HTTP \控制器\ UserController.php

public function cancelSubscription(Request $request)
{
    $user = $request->user();

    try {
        if ($user->subscription('main')->onTrial()) {
            $user->subscription('main')->cancelNow();
        } else {
            $user->subscription('main')->cancel();
        }
    } catch (\Exception $e) {
        \Log::error($e);
        return [
            'success' => 0,
            'message' => "Something went wrong while trying cancel your subscription. Please try again later."
        ];
    }

非常感谢任何帮助和提示,提前感谢!

2 个答案:

答案 0 :(得分:1)

我的不好,我发现它实际上是/config/services.php上的条带配置,因为我的用户有两个模型(因为我还使用了除laravel-cashier以外的其他包来处理通过Authorize.net付款,我最终创建了不同的模型供他们工作)

'stripe' => [
    // 'model' => App\AnetUser::class, => this actually caused the error as
               // ->asStripeCustomer() doesn't exists on an Authorize.net's Billable trait 
    'model' => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

我觉得很蠢。 XD

答案 1 :(得分:0)

您好我之前从未与Laravel Cashier合作过,但我认为问题的根源可能是您从请求中访问用户,因此它不是用户实例,因为它触发了未定义的原因方法错误。

因此,创建用户实例应该可以为您解决:

注意:我不知道$ request->用户是主键还是整个用户实例,所以我添加了不同的解决方案

public function cancelSubscription(Request $request)
{
    // if $request->user is the user instance you can do this:
    $user = App\User::findOrFail($request->user->id);

    // if $request->user was any other field from user you could retrieve
    // the user using something like-> 
   // App\User::where('fieldName', 'LIKE', $request->user)->firstOrFail();


    try {
        if ($user->subscription('main')->onTrial()) {
            $user->subscription('main')->cancelNow();
        } else {
            $user->subscription('main')->cancel();
        }
    } catch (\Exception $e) {
        \Log::error($e);
        return [
            'success' => 0,
            'message' => "Something went wrong while trying cancel your subscription. Please try again later."
        ];
    }
}