mightyspaj3
mightyspaj3

Reputation: 471

Stripe how to handle InvalidRequest error

I want to handle this error, however I can't get it to work in my catch. I've tried using multiple error phrases such as Stripe\Error\InvalidRequest and invalid_request_error, but none of them work.

Note: I have only included the necessary code, my payment system works fine.

Here's my code:

try {
        $charge = \Stripe\Charge::create(array(
          'customer' => $customer->id,
          'amount'   => $amount,
          'currency' => strtolower($active_user->currency->currency_id)
        ));
    }
catch (Stripe\Error\InvalidRequest $e) {
        $msg = "Sorry, you cannot make the same payment twice.";
    }

Upvotes: 4

Views: 8820

Answers (3)

danchik
danchik

Reputation: 181

Example from stripe: Are your responses set to return json, If so, in your } catch (... $e) {

  $body = $e->getJsonBody();
  $err  = $body['error'];

  print('Status is:' . $e->getHttpStatus() . "\n");
  print('Type is:' . $err['type'] . "\n");
  print('Code is:' . $err['code'] . "\n");
  // param is '' in this case
  print('Param is:' . $err['param'] . "\n");
  print('Message is:' . $err['message'] . "\n");

Upvotes: 0

James Beard
James Beard

Reputation: 340

Could be a namespacing issue. Try referencing your exception class with respect to the global scope by using a leading slash:

catch (\Stripe\Error\InvalidRequest $e) {

Failing that, add a catch for the base PHP Exception class, and see what you can find out about what is being thrown.

Upvotes: 3

Matthew Arkin
Matthew Arkin

Reputation: 4658

From the Stripe API Docs section on errors:

catch (\Stripe\Error\InvalidRequest $e) {
  // Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
  // Authentication with Stripe's API failed
  // (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
  // Network communication with Stripe failed
} catch (\Stripe\Error\Base $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
}

Upvotes: 3

Related Questions