-
-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Added SubscriptionController for managing su
- Loading branch information
1 parent
417d576
commit 195b75b
Showing
1 changed file
with
69 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
<?php | ||
|
||
namespace App\Http\Controllers; | ||
|
||
use Illuminate\Http\Request; | ||
use Illuminate\Support\Facades\Auth; | ||
use Laravel\Cashier\Exceptions\IncompletePayment; | ||
use Stripe\Stripe; | ||
use Stripe\Plan; | ||
|
||
class SubscriptionController extends Controller | ||
{ | ||
public function __construct() | ||
{ | ||
Stripe::setApiKey(env('STRIPE_SECRET')); | ||
} | ||
|
||
public function viewAvailableSubscriptions() | ||
{ | ||
$plans = Plan::all(); | ||
return response()->json(['plans' => $plans]); | ||
} | ||
|
||
public function subscribeToPlan(Request $request) | ||
{ | ||
$request->validate([ | ||
'plan' => 'required|string', | ||
'payment_method' => 'required|string', | ||
]); | ||
|
||
$user = Auth::user(); | ||
|
||
try { | ||
$user->newSubscription('default', $request->plan) | ||
->create($request->payment_method); | ||
return response()->json(['success' => true]); | ||
} catch (IncompletePayment $exception) { | ||
return response()->json(['success' => false, 'error' => $exception->getMessage()], 402); | ||
} | ||
} | ||
|
||
public function changePlan(Request $request) | ||
{ | ||
$request->validate([ | ||
'plan' => 'required|string', | ||
]); | ||
|
||
$user = Auth::user(); | ||
|
||
try { | ||
$user->subscription('default')->swap($request->plan); | ||
return response()->json(['success' => true]); | ||
} catch (\Exception $exception) { | ||
return response()->json(['success' => false, 'error' => $exception->getMessage()], 400); | ||
} | ||
} | ||
|
||
public function cancelSubscription() | ||
{ | ||
$user = Auth::user(); | ||
|
||
try { | ||
$user->subscription('default')->cancel(); | ||
return response()->json(['success' => true]); | ||
} catch (\Exception $exception) { | ||
return response()->json(['success' => false, 'error' => $exception->getMessage()], 400); | ||
} | ||
} | ||
} |