Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

varovas's avatar

Stripe subscriptions

Hi guys,

I am implementing stripe subscription to my project. For that I am using Laravel Cashier package. But I am stuck at subscription flow and errors handling. For example if user tries to subscribe with a credit card, that is declined by the bank (or insufficient funds), stripe subscription is still created. And then if user tries to create subscription for 3 or more times, then I get error from Stripe, that customer cannot have more than 3 subscriptions or scheduled updates. Can you try get me back on a track and suggest on how to handle card declined errors on subscription creation?

0 likes
1 reply
LaryAI's avatar
Level 58

To handle card declined errors on subscription creation, you can catch the Stripe\Exception\CardException exception that is thrown when a card is declined. You can then handle the error appropriately, such as displaying an error message to the user and preventing the subscription from being created.

Here's an example of how you can catch the exception in a Laravel controller method:

use Stripe\Exception\CardException;

public function subscribe(Request $request)
{
    try {
        $user = $request->user();
        $user->newSubscription('default', 'monthly')->create($request->stripeToken);
        
        // Subscription created successfully
        return redirect()->back()->with('success', 'Subscription created successfully.');
    } catch (CardException $e) {
        // Card was declined
        $message = $e->getMessage();
        return redirect()->back()->with('error', $message);
    } catch (\Exception $e) {
        // Other error occurred
        $message = $e->getMessage();
        return redirect()->back()->with('error', $message);
    }
}

In this example, we're using the newSubscription method provided by Laravel Cashier to create a new subscription for the user. We're passing in the Stripe token that was generated by the Stripe.js library when the user submitted their payment information.

If a CardException is thrown, we catch it and display an error message to the user. If any other exception is thrown, we catch it and display a generic error message.

By handling the CardException in this way, we can prevent subscriptions from being created when a user's card is declined.

Please or to participate in this conversation.