Laravel Cashier:同一用户不同角色能否设置不同订阅?
问题解答
1. 能否为同一用户的不同角色设置不同订阅?需要在UserProfile加Billable trait吗?
完全可以给同一用户的不同角色设置独立订阅,推荐在UserProfile模型上使用Billable trait。
因为你的user_profile表中每条记录对应一个角色,把Billable绑定到UserProfile上,就能让每个角色拥有独立的订阅周期、套餐和状态。需要注意的是,要给UserProfile模型指定唯一的billableKey,避免和User模型的标识冲突,比如用profile_id作为支付服务商(如Stripe)的客户标识。
2. 支付方式按用户保存,选User还是UserProfile模型?
推荐将支付方式存在User模型,订阅绑定到UserProfile模型,兼顾业务逻辑和用户体验:
- 用户只需要维护一套支付方式,不用为不同角色重复添加;
- 订阅和角色强绑定,符合你按角色区分服务的需求;
- 实现上可以让两个模型配合工作:
User管理支付方式,UserProfile管理订阅,订阅创建时调用User的支付方式。
代码示例
User模型(管理支付方式)
use Laravel\Cashier\Billable; class User extends Authenticatable { use Billable; // 关联用户的所有角色profile public function profiles() { return $this->hasMany(UserProfile::class); } }
UserProfile模型(管理订阅)
use Laravel\Cashier\Billable; class UserProfile extends Model { use Billable; // 定义唯一的billable标识,避免和User的id冲突 public function billableKey(): string { return (string) $this->id; } // 关联所属用户 public function user() { return $this->belongsTo(User::class); } // 用用户的支付方式创建订阅 public function createSubscriptionWithUserPayment(string $plan, string $paymentMethodId) { return $this->newSubscription('role_subscription', $plan) ->create($paymentMethodId, [ 'email' => $this->user->email, ]); } }
额外注意事项
- 确保支付服务商(如Stripe)中,
User和UserProfile的客户记录是区分开的,通过billableKey避免标识冲突; - 订阅的账单通知可以关联到用户邮箱,但订阅数据归属到对应的
UserProfile; - 给
user_profiles表添加Cashier所需的字段(如stripe_id、pm_type、pm_last_four等),可以通过Cashier的迁移或者自定义迁移实现。
内容的提问来源于stack exchange,提问作者Vince
相关产品推荐
相关产品推荐

