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

TimeSocks's avatar

How to override Stripe's API error on card decline?

I'm putting together a simple one off card payment system with Stripe. So far so good - when a successful payment is made. I'm now writing the code to handle card declines etc. Here's the relevant code:

try {
    $charge = \Stripe\Charge::create([
    "amount" => $grandTotal,
    "currency" => 'usd',
    "source" => $request->stripeToken,
    "description" => '$description'
    ]); 
        
} catch (Stripe_CardError $e) {
    return redirect::refresh()->withFlashMessage($e->getMessage());
}

As you can see, I'm just using the code from Jeffery's series on Stripe - refresh the page with a flash message in the session which I can check for and display a message if it's present.

However, before the app gets a chance to do that, Laravel jumps in with a 500 error:

Card in ApiRequestor.php line 101:
Your card was declined.

And my payment page and error message is thus not displayed. How can I fix this? TIA

0 likes
2 replies
TimeSocks's avatar
TimeSocks
OP
Best Answer
Level 4

Ok, solved this one myself. If anyone has the same problem in the future, this was my solution:

try {
            $charge = \Stripe\Charge::create([
                    "amount" => $grandTotal,
                    "currency" => 'usd',
                    "source" => $request->stripeToken,
                    "description" => '$description'
                ]
            ); 
        } catch (\Stripe\Error\Card $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        } catch (\Stripe\Error\InvalidRequest $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        } catch (\Stripe\Error\Authentication $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        } catch (\Stripe\Error\ApiConnection $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        } catch (\Stripe\Error\Base $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        } catch (Exception $e) {
            return redirect::refresh->withFlashMessage($e->getMessage());
        }

Basically there are multiple errors that need to be caught, you need to catch them all. Like Pokemon.

1 like
shivampaw's avatar

Could you just catch the base stripe exception and $e->getMessage() it?

Please or to participate in this conversation.