使用 Laravel Cashier & Stripe 管理订阅变更

Jam*_*ley 7 php laravel stripe-payments laravel-cashier

我目前正在将 Laravel Cashier(使用 Stripe)集成到一个小型应用程序中,该应用程序具有以下三层帐户;

\n\n
    \n
  • 自由的
  • \n
  • 基本(例如 \xc2\xa31.99/月)
  • \n
  • 高级版(例如 \xc2\xa34.99/月)
  • \n
\n\n

当前的流程是,当用户在注册后确认其电子邮件地址时,他们就会以免费计划(无卡)注册 Stripe。然后他们可以随时选择升级到付费计划。

\n\n

我的困惑在于管理用户订阅的更改,其代码如下所示:

\n\n
// Check if the user has a subscription\n$activeSubscription = $user->subscriptions()->first();\n\nif ($activeSubscription instanceof Subscription) {\n    return $activeSubscription->swap($targetPlan);\n}\n\n// No active plan (new registration) - create a new one\nreturn $user->newSubscription($targetPlan, $targetPlan)->create();\n
Run Code Online (Sandbox Code Playgroud)\n\n

当使用该swap方法将用户的套餐从免费更改为基本时stripe_idsubscriptions会更新以反映,这很好,因为用户实质上获得了更多功能。然而,如果用户决定从高级降级到基本,则该表中没有记录表明用户应保留高级功能直到该计费周期结束,因为它会再次更新上表中的单行。

\n\n

这里应该发生什么过程?如何管理此层次结构并确保正确的计划在其计费周期结束之前一直处于“活动”状态?

\n\n
\n\n

编辑

\n\n

经过思考,我认为使用swap应该仅用于直接交换适用的情况(例如,从每月计划到同等年度计划)。那么执行上述操作的最佳方法是什么?我的猜测是取消现有目标并订阅新目标,但是如何将后者的开始延迟到第一个周期结束?

\n\n
\n\n

这是完整的subscribe方法,以防有帮助;

\n\n
public function subscribe(User $user, string $targetPlan, string $token = null)\n{\n    $activeSubscription = $user->subscriptions()->first();\n\n    if ($targetPlan !== self::FREE_PLAN) {\n        if (null === $token && !$user->hasCardOnFile()) {\n            throw new SubscriptionException(\'No card token provided for paid subscription\');\n        }\n\n        $user->updateCard($token);\n    }\n\n    // If the current user is in the cancellation grace period of the selected plan, resume that subscription\n    $existingSubscription = $user->subscription($targetPlan);\n\n    if ($existingSubscription instanceof Subscription && $existingSubscription->onGracePeriod()) {\n        return $existingSubscription->resume();\n    }\n\n    // If the user has an active subscription, and the target plan is different, swap to that plan    \n    if ($activeSubscription instanceof Subscription) {\n        $activeSubscription->name = $targetPlan;\n        return $activeSubscription->swap($targetPlan);\n    }\n\n    return $user->newSubscription($targetPlan, $targetPlan)->create();\n}\n
Run Code Online (Sandbox Code Playgroud)\n