@ajck You generate the Stripe token using the JavaScript library and then post it to a controller action:
Route::post('subscriptions', 'SubscriptionController@store');
class SubscriptionController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'stripe_token' => 'required',
]);
$request->user()->newSubscription('main', 'plan-id-in-stripe')
->create($request->input('stripe_token'));
return redirect('/')->withSuccess('You are now subscribed.');
}
}
You’ll have needed to have created a plan in your Stripe account, and created the database tables as specified in the Cashier docs.
A Stripe payment request can fail with a Stripe\Error\Card instance. This is usually when the card is declined or the user has no funds, so you can catch this exception in your application’s exception handler at app/Exceptions/Handler.php:
use Stripe\Error\Card as CardError;
class Handler extends ExceptionHandler
{
// Snipped...
public function render($request, Exception $exception)
{
if ($exception instanceof CardError) {
if ($request->expectsJson()) {
return response()->json([
'error' => $exception->getMessage(),
], 400);
}
return redirect()->back()
->withInput()
->withError($exception->getMessage());
}
//
return parent::render($request, $exception);
}
}
All this requires you have a User already in your application to assign a subscription too. You could create the user at the same time as the subscription to allow guests to sign up and subscribe in one go:
class SubscriptionController extends Controller
{
public function store(Request $request)
{
$this->validate($request, [
'first_name' => 'filled',
'last_name' => 'filled',
'email' => 'filled|email|max:255|unique:users,email',
'password' => 'filled',
'stripe_token' => 'required',
]);
$user = $this->getUser($request);
$user->newSubscription('main', 'plan-id-in-stripe')
->create($request->input('stripe_token'));
return redirect('/')->withSuccess('You are now subscribed.');
}
protected function getUser(Request $request)
{
if ($user = $request->user()) {
return $user;
}
$user = User::create([
'first_name' => $request->input('first_name'),
'last_name' => $request->input('last_name'),
'email' => $request->input('email'),
'password' => bcrypt($request->input('password')),
]);
Auth::login($user);
return $user;
}
}