laravellaravel-cashier

Laravel Cashier - Restore Usage limits when subscription is renewed


I created a Saas application with usage limits.

For example if user subscribe "Premium Membership" they can do 10 task in a month.

I couldn't manage to find a solution to reset their usage limits when subscription period is renewed.

In my users table;

id tokens_left
1 5
2 9

I haven't figure any solutions yet. I tried to retrieve subscription information from the stripe but any fields aren't helpful.


Solution

  • Stripe can notify your application of a variety of events via webhooks. By default, a route that points to Cashier's webhook controller is automatically registered by the Cashier service provider. This controller will handle all incoming webhook requests.

    By default, the Cashier webhook controller will automatically handle cancelling subscriptions that have too many failed charges (as defined by your Stripe settings), customer updates, customer deletions, subscription updates, and payment method changes; however, as we'll soon discover, you can extend this controller to handle any Stripe webhook event you like.

    If you have additional webhook events you would like to handle, you may do so by listening to the following events that are dispatched by Cashier:

    Laravel\Cashier\Events\WebhookReceived
    Laravel\Cashier\Events\WebhookHandled
    

    Both events contain the full payload of the Stripe webhook. For example, if you wish to handle the customer.subscription.updated webhook, you may register a listener that will handle the event:

    <?php
     
    namespace App\Listeners;
     
    use Laravel\Cashier\Events\WebhookReceived;
     
    class StripeEventListener
    {
        /**
         * Handle received Stripe webhooks.
         */
        public function handle(WebhookReceived $event): void
        {
            if ($event->payload['type'] === 'customer.subscription.updated') {
                // Handle the incoming event...
            }
        }
    }
    

    In this listener, you can reset everything you want in the database. This is the way I recommend you to follow, however there could be other ways by measuring the tasks that were created since the subscription was created.

    You can read more information in the official Laravel Cashier documentation.