To handle scheduled downgrades with Laravel Cashier and Stripe, you can take advantage of Stripe's subscription scheduling features. While Cashier doesn't directly support scheduling downgrades out of the box, you can achieve this by using Stripe's API directly in combination with Cashier.
Here's a step-by-step approach to implement this:
-
Retrieve the Current Subscription: First, get the user's current subscription using Cashier.
-
Use Stripe's Subscription Schedule: Create a subscription schedule using Stripe's API. This allows you to specify when the downgrade should take effect.
-
Set the End of Current Period for Downgrade: Schedule the downgrade to occur at the end of the current billing cycle.
Here's a code example to illustrate this process:
use Stripe\Stripe;
use Stripe\SubscriptionSchedule;
// Set your Stripe secret key
Stripe::setApiKey(env('STRIPE_SECRET'));
// Retrieve the current subscription
$subscription = $user->subscription('default');
// Create a subscription schedule
$schedule = SubscriptionSchedule::create([
'customer' => $user->stripe_id,
'start_date' => $subscription->asStripeSubscription()->current_period_end,
'end_behavior' => 'release',
'phases' => [
[
'items' => [
[
'price' => 'price_id_of_new_plan', // Replace with the price ID of the lower plan
'quantity' => 1,
],
],
'start_date' => $subscription->asStripeSubscription()->current_period_end,
],
],
]);
// Optionally, you can store the schedule ID in your database if you need to reference it later
$user->update(['stripe_schedule_id' => $schedule->id]);
Key Points:
- Stripe API: You need to use Stripe's PHP library to interact with the subscription schedule API.
- End of Current Period: The
start_datefor the new phase is set to thecurrent_period_endof the existing subscription, ensuring the downgrade happens after the current billing cycle. - Price ID: Replace
'price_id_of_new_plan'with the actual price ID of the plan you want to downgrade to.
Additional Considerations:
- Testing: Make sure to test this thoroughly in a test environment to ensure it behaves as expected.
- Stripe Webhooks: Consider setting up webhooks to handle any events related to subscription changes, such as successful downgrades or errors.
By following these steps, you can effectively schedule downgrades using Stripe's capabilities alongside Laravel Cashier.