I have a website built on the PHP Laravel Framework. I use Stripe to process recurring subscription fees for the service via Laravel Cashier. This is the code for the SubscriptionController.php:
class SubscriptionController extends Controller
{
function __construct()
{
$this->middleware('auth');
}
public function payment()
{
$availablePlans =[
'monthly-4_99' => "Monthly",
'yearly' => "Yearly"
];
$data = [
'intent' => auth()->user()->createSetupIntent(),
'plans'=> $availablePlans
];
return view('user.subscribe')->with($data);
}
public function subscribe(Request $request)
{
$user = auth()->user();
$paymentMethod = $request->payment_method;
$planId = $request->plan;
$coupon = $request->coupon;
if ($coupon == 'Free60') {
$user->newSubscription('plan', $planId)->trialDays(60)->create($paymentMethod);
} else if ($coupon == '1YrEA') {
$planId = 'monthly-4_99';
$user->newSubscription('plan', 'monthly-4_99')->trialDays(365)->create($paymentMethod);
} else if ($coupon == 'LAT-44') {
$planId = 'monthly-4_99';
$user->newSubscription('plan', 'monthly-4_99')->withCoupon($coupon)->create($paymentMethod);
} else {
$user->newSubscription('plan', $planId)->create($paymentMethod);
}
if ($planId == 'monthly-4_99') {
return response([
'success_url'=> redirect()->intended('memorials')->with('success', 'You are now subscribed to a monthly plan.')->getTargetUrl()
]);
} else if ($planId == 'yearly') {
$user = auth()->user();
User::find($user->id)->update(['free_qrplaque' => 'yes']);
return response([
'success_url'=> redirect()->intended('memorials')->with('success', 'You are now subscribed to a ' . $planId . ' plan.')->getTargetUrl()
]);
}
}
}
This works as it should, but there is one problem I just discovered. When a user's payment information is no longer valid, the user remains subscribed and has access to all premium features of the service. When I try to cancel the subscription by clicking the "Unsubscribe" button, the website gives me a 500 Server Error. Here is the code for canceling a subscription:
public function cancel()
{
$user = auth()->user();
$user->subscription('plan')->cancel();
return redirect()->back()->with("success", "Your subscription has been canceled.");
}
When the user logs in and views the dashboard, I have some code that checks if they are subscribed. If they are not, I process the changes to reflect a free user's capabilities (not being able to publish memorials). Here is the code:
public function index()
{
$user = auth()->user();
if (!$user->subscribed('plan') && $user->memorials->count() > 0) {
foreach ($user->memorials as $memorial) {
$memorial->update(['status' => 'unpublished']);
}
}
return view('memorials');
}
I'm assuming this code is not targeting the correct variable to check if the user is still subscribed, or if I need to add additional code for when a user's payment method is declined to make the necessary changes in the database to reflect being unsubscribed.
If anyone can help me fix this issue, it would be greatly appreciated.