Search code examples
phplaravelstripe-paymentslaravel-cashier

Is it possible to decrease the usage in Metered Billing Plan ( using Laravel Cashier - Stripe)


I am creating an appointment application where users billed per appointment, sometime the users will cancel the subscription. In that time we need to decrease the usage, is the right way to do it? if so is there any facility for that in Laravel Cashier?

In the Stripe Documentation, it says about an Action ENUM, Can we use that?


Solution

  • It is possible to use the set instead of increment:

    In the source code we can see the following on a SubscriptionItem#reportUsage:

        public function reportUsage($quantity = 1, $timestamp = null)
        {
            $timestamp = $timestamp instanceof DateTimeInterface ? $timestamp->getTimestamp() : $timestamp;
    
            return $this->subscription->owner->stripe()->subscriptionItems->createUsageRecord($this->stripe_id, [
                'quantity' => $quantity,
                'action' => $timestamp ? 'set' : 'increment',
                'timestamp' => $timestamp ?? time(),
            ]);
        }
    

    which is called by Subscription#reportUsage

        public function reportUsage($quantity = 1, $timestamp = null, $price = null)
        {
            if (! $price) {
                $this->guardAgainstMultiplePrices();
            }
    
            return $this->findItemOrFail($price ?? $this->stripe_price)->reportUsage($quantity, $timestamp);
        }
    

    So if you want to decrement you would just get the current usage and set a new usage, you have to include the timestamp parameter to use set instead of increment:

    // get current usage
    $newUsage = $currentUsage - $decrement;
    
    $user = User::find(1);
    
    $user->subscription('default')->reportUsage($newUsage, time());