Search code examples
laravel-5stripe-paymentslaravel-cashier

Laravel Cashier (Stripe) get subscription cost or coupon used?


I'm using Laravel Cashier with Stripe.

In my account panel I want to show users how much their monthly subscription is costing them.

Users can have a normal plan without a coupon or the same plan with a coupon that makes it half price.

Is there anyway Cashier can tell me how much the monthly subscription is costing them or if they signed up using a coupon? Or is this something I have to store in my own database at the time they subscribe?


Solution

  • I created a coupon trait that I use on my User Model. Hope that helps.

    <?php
    
    namespace App\Traits;
    
    use Carbon\Carbon;
    
    trait Coupon 
    {
        public function getSubscriptions()
        {
            return $this->asStripeCustomer()->subscriptions->data;
        }
    
        public function getSubscription()
        {
            foreach ($this->getSubscriptions() as $subscription) {
                if ($subscription->status === 'active') {
                    return $subscription;
                }
            }
        }
    
        public function discount()
        {
            return $this->getSubscription()->discount;
        }
    
        public function discountCustomerId()
        {
            return $this->discount()->customer;
        }
    
        public function discountSubscriptionId()
        {
            return $this->discount()->subscription;
        }
    
        public function discountStartDate()
        {
            return Carbon::createFromTimestamp($this->discount()->start);
        }
    
        public function discountEndDate()
        {
             return Carbon::createFromTimestamp($this->discount()->end);
        }
    
        public function discountDaysLeft()
        {
            return $this->discountEndDate()
                ->diffInDays($this->discountStartDate());
        }
    
        public function coupon()
        {
            return $this->discount()->coupon;
        }
    
        public function couponIsValid()
        {
             return $this->coupon()->valid;
        }
    }