Previously, we saw how to configure a Laravel app to handle Braintree subscriptions.
This time, we'll talk about how to:
- Prevent users from signing up to the same plan twice
- Add basic flash messaging to our application
- Add the ability to swap plans
- Create middleware to protect some routes based on the subscription status
- Restrict users with basic subscriptions from accessing premium content
- Cancel and resume subscriptions
- Add Braintree notifications to the application's events via webhooks
Double Subscriptions
As it stands, if we visit the plans index
page, we can still see the Choose Plan
button for the plan we are currently subscribed to, and this shouldn't be the case. In the plans index
view. let's add an if conditional
to hide the button based on the user's subscription status:
[...]
@if (!Auth::user()->subscribedToPlan($plan->braintree_plan, 'main'))
<a href="" class="btn btn-default pull-right">Choose Plan</a>
@endif
[...]
But that's not to say users can't access the plan by typing in the URL pointing to the same plan in the address bar. To counter this, let's update the code in the show
action of the PlansController
to this:
[...]
public function show(Request $request, Plan $plan)
{
if ($request->user()->subscribedToPlan($plan->braintree_plan, 'main')) {
return redirect('home')->with('error', 'Unauthorised operation');
}
return view('plans.show')->with(['plan' => $plan]);
}
[...]
Here, we are getting the user from the request object; remember all our routes fall under the auth middleware and thus it's possible to get the authenticated user. Once we get the user, we check if they are already subscribed to the plan. If that's the case, we redirect them to the homepage and display a notification. We will implement basic flash messaging later.
One last precaution is preventing users from submitting the payment form with a different plan ID
value. It's possible to inspect the DOM element and change the value for the hidden input. In our SubscriptionsController
, let's update the store
method to this:
[...]
public function store(Request $request)
{
$plan = Plan::findOrFail($request->plan);
if ($request->user()->subscribedToPlan($plan->braintree_plan, 'main')) {
return redirect('home')->with('error', 'Unauthorised operation');
}
$request->user()->newSubscription('main', $plan->braintree_plan)->create($request->payment_method_nonce);
// redirect to home after a successful subscription
return redirect('home')->with('success', 'Subscribed to '.$plan->braintree_plan.' successfully');
}
[...]
Flash Messaging
Let's now implement some basic flash messaging to display notifications in the app in response certain operations. In the resources/views/layouts/app.blade.php
file, let's insert this block right above our content since flash messages show up at the top before any other content:
Continue reading %Laravel and Braintree: Middleware and Other Advanced Concepts%
by Christopher Vundi via SitePoint
No comments:
Post a Comment