Stripe API:获取即将取消的订阅的发票

Stripe API: get upcoming invoice for cancelled Subscription

我使用此代码按比例取消条纹订阅

    $user = User::find(Auth::id());
    $subscription = \Stripe\Subscription::retrieve(
        $user->subscription('main')->stripe_id
    );

    $subscription->delete([
        'prorate' => true
    ]);

在条带仪表板中订阅已取消,并创建了按比例分配的即将到来的发票。 我想按比例退还客户的卡。我尝试使用以下代码按比例分配金额。

    $subscription = \Stripe\Subscription::retrieve($user->subscription('main')->stripe_id);
    $subscription_item = array(
        "id" => $subscription->items->data[0]->id,
        "plan" => $subscription->items->data[0]->plan->id,
        "quantity" => 0,
    );
    $proration_date = time();
    $upcoming_prorated_invoice = \Stripe\Invoice::upcoming([
        "customer" => $subscription->customer,
        "subscription" => $subscription->id,
        "subscription_items" => array($subscription_item),
        "subscription_proration_date" => $proration_date, // optional
    ]);

    dd($upcoming_prorated_invoice);

我收到以下错误消息

Stripe\Exception\InvalidRequestException

You cannot preview the upcoming invoice for a canceled subscription.

更新

    $subscription->delete([
        'prorate' => true,
        'invoice_now' => true
    ]);

    //$latest_invoice = \Stripe\Invoice::retrieve($subscription->latest_invoice);
    //$latest_charge_id = $latest_invoice->charge;

    $invoice = \Stripe\Invoice::retrieve([ 'id' => $subscription->latest_invoice, 'expand' => ['payment_intent.charges'], ]);
    //$charge = $invoice->payment_intent->charges->data[0];
    dd($invoice);

payment_intent return 为 null

终于找到解决办法了。 ref

    $subscription = \Stripe\Subscription::retrieve($user->subscription('main')->stripe_id);

    $proration_date = time();

    $refund = $this->prorate($subscription, $proration_date);

    if ($refund) {
        $latest_invoice = \Stripe\Invoice::retrieve($subscription->latest_invoice);

        if ($latest_invoice) {
            \Stripe\Refund::create([
                'charge' => $latest_invoice->charge,
                'amount' => $refund,
            ]);
        }
    }



public function prorate(\Stripe\Subscription $subscription, $proration_time)
{
    $period_start = $subscription->current_period_start;
    $period_end = $subscription->current_period_end;
    $amount = $subscription->plan->amount;

    $period_length = $period_end - $period_start;

    $elapsed_since_start = $proration_time - $period_start;

    $refund = $amount - floor(($elapsed_since_start / $period_length) * $amount);

    return $refund > 0 ? (int) $refund : 0;
}