In order to catch any errors like the one you're seeing from Stripe when a charge fails you will need to wrap your charge request in a try/catch block. For example:
try {
$charge = StripeCharge::create([
'amount' => '2499',
'currency' => 'usd',
'description' => 'Deactivation Letter',
'source' => $token,
]);
} catch(StripeExceptionCardException $e) {
// Since it's a decline, StripeExceptionCardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '
';
echo 'Type is:' . $e->getError()->type . '
';
echo 'Code is:' . $e->getError()->code . '
';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '
';
echo 'Message is:' . $e->getError()->message . '
';
} catch (StripeExceptionRateLimitException $e) {
// Too many requests made to the API too quickly
} catch (StripeExceptionInvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (StripeExceptionAuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (StripeExceptionApiConnectionException $e) {
// Network communication with Stripe failed
} catch (StripeExceptionApiErrorException $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
Within each catch block you can add logic to return a helpful error message to the user with relevant next steps. The Stripe docs provide a full example of these errors and how to handle them in this section:
https://stripe.com/docs/api/errors/handling?lang=php
You can also use the following test card/token to test for the case of insufficient funds:
raw card number
4000000000009995
test token string
tok_chargeDeclinedInsufficientFunds
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…