Laravel 收银员 - 终身订阅

时间:2020-12-23 16:30:24

标签: php laravel stripe-payments laravel-cashier

我正在尝试按月、按年和终身订阅,其中按月和按年订阅工作正常。我如何进行终身/永久订阅?每当我将计划名称和计划 ID 传递给 $user->newSubscription() 时,我都会收到一个错误:

You passed a non-recurring price but this field only accepts recurring prices.

以下是我的订阅代码:

$paymentMethod = $user->defaultPaymentMethod();

        if ($period == 'yearly') {
            $selectedPlan = $plan->plan_year;
        } elseif($period=='monthly') {
            $selectedPlan = $plan->plan_month;
        }
        else{
            $selectedPlan = $plan->plan_lifetime;
        }   

        $subscription = $user->newSubscription($plan->name, $selectedPlan);

1 个答案:

答案 0 :(得分:0)

假设您使用的是 prices 而不是计划,您应该创建发票而不是订阅:

if ($period == 'yearly') {
    $subscription = $user->newSubscription($plan->name, $plan->plan_year);
} elseif($period=='monthly') {
    $subscription = $user->newSubscription($plan->name, $plan->plan_month);
} else {
    // Create an invoice item with the lifetime price
    StripeInvoiceItem::create([
        'customer' => $user->stripeId(),
        'price' => $plan->plan_lifetime,
    ], $user->stripeOptions());

    // create the invoice with the lifetime item and finalize it automatically after 1 hour
    $user->invoice(['auto_advance' => true]);
}

接下来,通过扩展 WebhookController 将 invoice.paid 添加到您的 webhooks 和您需要侦听此通知。您将在此处找到匹配的发票并检查发票项目是否与 $plan->lifetime_plan 具有相同的 ID。如果是这样,您可以更新客户模型上的列以设置终身订阅:

public function handleInvoicePaid(array $payload)
{
    if ($user = $this->getUserByStripeId($payload['data']['object']['customer'])) {
        $data = $payload['data']['object'];

        $invoice = $user->findInvoice($data['id']);

        if (isset($invoice)) {
            $plan = ...

            if ($invoice->invoiceItems()->contains(function (InvoiceLineItem $item) use ($plan) {
                return $item->price->id === $plan->lifetime_plan;
            })) {
                $user->update(['has_lifetime_subscription' => true]);
            }
        }
    }

    return $this->successMethod();
}

在您的应用程序中,您可以检查用户是终身订阅还是普通订阅:

if ($user->has_lifetime_subscription || $user->subscribed()) {
    // ...
}