Laravel Cashier: Handling Coupons and Discounts
Laravel Cashier is a powerful billing and subscription management library that simplifies handling payments and subscriptions in Laravel applications. One essential feature of any billing system is the ability to apply and manage coupons and discounts. In this guide, we'll explore how to handle coupons and discounts using Laravel Cashier.
1. Installation and Configuration
Start by installing Laravel Cashier and configuring it with your preferred payment gateway (e.g., Stripe, Braintree). Follow the official Laravel Cashier documentation to set up the package and configure your API keys.
2. Creating Coupons
Create coupons in your payment gateway's dashboard (e.g., Stripe Dashboard) or programmatically using Laravel Cashier's API. Coupons can offer fixed amount discounts or percentage-based discounts.
use Laravel\Cashier\Cashier;
$coupon = Cashier::coupon('your-coupon-code');
3. Applying Coupons to Subscriptions
To apply a coupon to a subscription, simply pass the coupon code when creating or updating a subscription. Laravel Cashier will handle the coupon redemption and calculate the discounted amount.
use Laravel\Cashier\SubscriptionBuilder;
$user->newSubscription('default', 'your-plan')
->withCoupon('your-coupon-code')
->create($paymentMethod);
4. Validating Coupons
Before applying a coupon, you can validate it to ensure it's valid and still active. Laravel Cashier provides methods to check the coupon's validity.
if ($coupon->valid()) {
// Coupon is valid, proceed with applying it to the subscription.
} else {
// Coupon is invalid or expired, handle accordingly.
}
5. Managing Coupons
You can also manage coupons, such as retrieving coupon details, listing available coupons, and deleting coupons if needed.
$coupon = Cashier::coupon('your-coupon-code');
$couponDetails = $coupon->details();
$availableCoupons = $coupon->list();
$coupon->delete();
6. Displaying Discounts to Users
When displaying subscription details to users, be sure to show the applied coupon and the discounted amount, so users are aware of the savings they are receiving.
Subscription: Premium Plan
Discount: 25% off (Coupon: YOURCOUPON)
Total Amount: $15/month
7. Testing Coupons
During development, you can test coupon functionality using test cards provided by your payment gateway. Stripe, for example, offers test coupon codes that you can use for testing discount scenarios without actual charges.
Conclusion
Laravel Cashier simplifies the process of handling coupons and discounts in your Laravel application's billing system. By following these steps, you can easily create, apply, and manage coupons, providing your customers with discounts and promotions while maintaining a robust billing system.