Stripe how to handle InvalidRequest error - php

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.";
}

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
}

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.

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");

Related

Cannot Catch Errors in Stripe payment gateway in Codeigniter 3

I am very new to stripe payment gateway integration. I am facing a problem on catching errors. I saw their official documentation for catching errors, but nothing is working. My payment is working fine and when I enter the correct information stripe takes my payment and successfully redirect to the success page, but the problem happens when I tried with wrong information it doesn't give me any error just shows HTTP 500 error (In production environment). When I set error_reporting(E_ALL) then it shows me the actual errors but I can't catch those errors on Try Catch.
Here is my controller
//check whether stripe token is not empty
if (!empty($_POST['stripeToken'])) {
$stripe = array(
"secret_key" => "secret key",
"publishable_key" => "public key"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
//add customer to stripe
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
try {
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $itemPrice * 100,
'currency' => $currency,
'description' => $itemNumber,
'metadata' => array(
'item_id' => $itemNumber
)
));
$chargeJson = $charge->jsonSerialize();
} catch (\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$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");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Error\InvalidRequest $e) {
echo "I am this error";
$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");
} 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
}
here is the error if I turn on error_reporting(E_ALL)
PHP error. According to the Strip's documentation I should catch the errors in Try Catch block, but I am failing to catch the errors. It is in local server but in live server it is same.

Handling pure PHP errors in CodeIgniter

I have a mobile application with an API developed with CodeIgniter, and this API performs payments by Stripe.
These payments are recursive, so once a month I charge my users. But some users cannot be charged (for an example if an user has insufficient funds on his card), and in this case Stripe throws an exception.
I'd like to be able to perform a try/catch in my controller. For now I have this code :
try {
$charge = \Stripe\Charge::create(array(
"amount" => xxx,
"currency" => "eur",
"customer" => xxx)
);
} catch (Exception $e) {
// If user has insufficient funds, perfom this code
}
I recently saw that the piece of code in the catch was never executed, and I saw that CI had its own error handling system, and I could see in my logs that errors from controllers run by cli were displayed on this view : application/views/errors/cli/error_php.php. So how can I simply detect if my Stripe code returns an exception ?
Thanks in advance for any answer :)
Try using the global namespace for your exception like this:
catch (\Exception $e) //note the backslash
Please refer Stripe's API document carefully.
They have described error handling in a very detailed manner. You can read about it here: https://stripe.com/docs/api/php#error_handling
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$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");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} 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
}

How to catch a Stripe Fatal Error in PHP?

I am spinning up an application using the Stripe.js elements. Using the test card numbers provided by Stripe, I have no issues. All works as expected.
I'm now focusing on error handling. When using the test card 4000 0000 0000 0002 to handle a card that is intentionally declined, I get this error:
Fatal error: Uncaught Stripe\Error\Card: Your card was declined. in
C:\Apache24\htdocs...\vendor\stripe\stripe-php\lib\ApiRequestor.php:128 from API request {token}....
Now I'm assuming this is not a PHP Fatal Error (which can not be handled in a try/catch block), so I searched and found this example and implemented it into my code like this:
\Stripe\Stripe::setApiKey(self::APIKEY);
$charge_arr = array(
"key" => value, etc ... )
try {
$charge = \Stripe\Charge::create($charge_arr);
if($charge->paid == true) {
echo '<br>the card was successfully charged!';
}
} catch (\Stripe\Error\Base $e) {
echo '<br>base';
echo ($e->getMessage());
} catch (\Stripe\Error\Card $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");
echo ($e->getMessage());
} catch (\Stripe\Error\Authentication $e) {
echo '<br>Auth';
// a good one to catch
} catch (\Stripe\Error\InvalidRequest $e) {
echo '<br>Invalid Request';
// and catch this one just in case
} catch (Exception $e) {
//catch any non-stripe exceptions
}
This does not, however, catch the error. The message continues to be displayed as it was before I had the catch block.
Any clues why I'm getting the Fatal Error? I, of course, expected the card to be declined, but I expected the result of the decline to be something I could handle in the try/catch block.
EDITS
I should add that I'm using composer to include the Stripe php libraries.
Further note: It may not be relevant, but the Fatal Error message appears for all test cards that are supposed to be declined. The reason for the decline is stated clearly in the error message for each card like (not verbatim) zip code failed validation, CVC not correct, card expired, etc.
As #Ywain rightfully notes, this actually isn't a try/catch block problem. The Fatal Error is generated by the charge transaction in the first place. In other words the call to \Stripe\Charge should return a JSON array with appropriate flags or field values, not a Fatal Error.
Stripe has many exceptions it can throw in the course of a transaction. Their API has excellent sample code to provide a template of catching the various exceptions Stripe API can throw.
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$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");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} 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
}
Also keep in mind that once you catch the exception, unless you do something to specifically end your script or change execution path, that your script will continue to run the rest of the code blissfully unaware there was any exception raised. Consider this overly simple example.
try {
$charge = \Stripe\Charge::create($charge_arr);
} catch (\Stripe\Error\Card $e) {
echo("I had an error!");
}
echo ("I completed Successfully");
The card is declined and the api throws \Stripe\Error\Card. You then receive the following output.
I had an error!I completed successfully
This matters if you have multiple API calls in your execution path. You could very well catch the exception thrown just to have another one thrown by a later call that you were not expecting to run. You should have all calls to the API that could raise an exception wrapped in try/catch. You will also need to pay attention to your execution path if you are expecting errors caught from earlier calls to keep other code from executing. Overly simple example.
try {
$charge = \Stripe\Charge::create($charge_arr);
$declined = false;
} catch (\Stripe\Error\Card $e) {
echo("I had an error!");
$declined = true;
}
if(!$declined) {
echo ("I completed Successfully");
}
I think you need to catch the different types of tossed errors.
\Stripe\Stripe::setApiKey(self::APIKEY);
$charge_arr = array(
"key" => value, etc ... )
try {
$charge = \Stripe\Charge::create($charge_arr);
} catch (\Stripe\Error\Base $e) {
echo ($e->getMessage());
} catch (\Stripe\Error\Card $e) {
echo ($e->getMessage()); // I think this is the missing one
} catch (\Stripe\Error\Authentication $e) {
// a good one to catch
} catch (\Stripe\Error\InvalidRequest $e) {
// and catch this one just in case
} catch (Exception $e) {
//catch any non-stripe exceptions
}

Stripe payment with php

I am developing a website that is front end made with angularjs and backend with laravel.
I want to integrate stripe payment. I am facing difficulty to add a angularjs api to laravel for stripe payment. So, I am trying to solve it with only procedural php. here is my code.
<?php
require_once('/stripe-php/lib/Stripe.php');
require_once('/stripe-php/lib/Charge.php');
Stripe::setApiKey('my-secret-key');
$charge = Charge::create(array('amount' => 2000, 'currency' => 'usd', 'source' => $token ));
if ($charge) {
echo "Payment successcul";
}
else {
echo "Not success";
}
?>
I can get the token. But the payment is not processing and I see a blank page.
Follow this step to stripe payment.
1. download stripe folder from https://stripe.com/docs/libraries#php
2. Include the folder in your www folder in your project.
3. Make new PHP file and put this code into file.
<?php
{
require_once "./Stripe-php/init.php"; //include your stripe folder
function __construct()
{
// put your keys here
\Stripe\Stripe::setApiKey("Secret-Key");
}
//put your code into function.
$token = $_POST['stripeToken']; // Token ID
$charge = \Stripe\Charge::create([
'amount' => $20 * 100,
'currency' => 'usd',
'description' => 'Message',
'source' => $token,
]);
if($charge['status'] == "succeeded"){ // if success
$status=1;
$post['charge_id']=$charge['id'];
$post['amount']=$charge['amount'];
$post['funding']=$charge['source']['funding'];
$post['holder_name']=$charge['source']['name'];
$post['brand']=$charge['source']['brand'];
$Message="Payment Success";
}
else{
$status=2; // failed
$post=null;
$Message="Payment Failed";
}
$data["status"] = ($status > 1) ? FAILED : SUCCESS;
$data["message"]=$Message;
$data["PaymentData"]=$post;
return $data; // JSON Returen
}
?>
Include Stripes error handling in the page itself.
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
$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");
} catch (\Stripe\Error\RateLimit $e) {
// Too many requests made to the API too quickly
} 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
}

Catching Stripe errors with Try/Catch PHP method

During my testing of STRIPE in a website, I built the code like this:
try {
$charge = Stripe_Charge::create(array(
"amount" => $clientPriceStripe, // amount in cents
"currency" => "usd",
"customer" => $customer->id,
"description" => $description));
$success = 1;
$paymentProcessor="Credit card (www.stripe.com)";
}
catch (Stripe_InvalidRequestError $a) {
// Since it's a decline, Stripe_CardError will be caught
$error3 = $a->getMessage();
}
catch (Stripe_Error $e) {
// Since it's a decline, Stripe_CardError will be caught
$error2 = $e->getMessage();
$error = 1;
}
if ($success!=1)
{
$_SESSION['error3'] = $error3;
$_SESSION['error2'] = $error2;
header('Location: checkout.php');
exit();
}
The problem is that sometimes there is an error with the card (not catched by the "catch" arguments I have there) and the "try" fails and the page immediately posts the error in the screen instead of going into the "if" and redirecting back to checkout.php.
How should I structure my error handling so I get the error and immediately redirect back to checkout.php and display the error there?
Thanks!
Error thrown:
Fatal error: Uncaught exception 'Stripe_CardError' with message 'Your card was declined.' in ............
/lib/Stripe/ApiRequestor.php on line 92
If you're using the Stripe PHP libraries and they have been namespaced (such as when they're installed via Composer) you can catch all Stripe exceptions with:
<?php
try {
// Use a Stripe PHP library method that may throw an exception....
\Stripe\Customer::create($args);
} catch (\Stripe\Error\Base $e) {
// Code to do something with the $e exception object when an error occurs
echo($e->getMessage());
} catch (Exception $e) {
// Catch any other non-Stripe exceptions
}
I think there is more than these exceptions (Stripe_InvalidRequestError and Stripe_Error) to catch.
The code below is from Stripe's web site. Probably, these additional exceptions, which you didn't consider, occurs and your code fails sometimes.
try {
// Use Stripe's bindings...
} catch(Stripe_CardError $e) {
// Since it's a decline, Stripe_CardError will be caught
$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");
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $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
}
EDIT:
try {
$charge = Stripe_Charge::create(array(
"amount" => $clientPriceStripe, // amount in cents
"currency" => "usd",
"customer" => $customer->id,
"description" => $description));
$success = 1;
$paymentProcessor="Credit card (www.stripe.com)";
} catch(Stripe_CardError $e) {
$error1 = $e->getMessage();
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
$error2 = $e->getMessage();
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
$error3 = $e->getMessage();
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
$error4 = $e->getMessage();
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
$error5 = $e->getMessage();
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
$error6 = $e->getMessage();
}
if ($success!=1)
{
$_SESSION['error1'] = $error1;
$_SESSION['error2'] = $error2;
$_SESSION['error3'] = $error3;
$_SESSION['error4'] = $error4;
$_SESSION['error5'] = $error5;
$_SESSION['error6'] = $error6;
header('Location: checkout.php');
exit();
}
Now, you will catch all possible exceptions and you can display error message as you wish. And also $error6 is for unrelated exceptions.
This is an update to another answer, but the docs have changed very slightly so I had success using the following method:
try {
// Use Stripe's library to make requests...
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $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
}
You can find the source of this in the Stripe docs right here:
https://stripe.com/docs/api/errors/handling?lang=php
I may be late to this question, but I ran into the same issue and found this.
You just need to use "Stripe_Error" class.
use Stripe_Error;
After declaring that, I was able to catch errors successfully.
This is how Stripe catches errors: Documentation.
try {
// make Stripe API calls
} catch(\Stripe\Exception\ApiErrorException $e) {
$return_array = [
"status" => $e->getHttpStatus(),
"type" => $e->getError()->type,
"code" => $e->getError()->code,
"param" => $e->getError()->param,
"message" => $e->getError()->message,
];
$return_str = json_encode($return_array);
http_response_code($e->getHttpStatus());
echo $return_str;
}
You can then catch the error in ajax with the following code:
$(document).ajaxError(function ajaxError(event, jqXHR, ajaxSettings, thrownError) {
try {
var url = ajaxSettings.url;
var http_status_code = jqXHR.status;
var response = jqXHR.responseText;
var message = "";
if (isJson(response)) { // see here for function: https://stackoverflow.com/a/32278428/4056146
message = " " + (JSON.parse(response)).message;
}
var error_str = "";
// 1. handle HTTP status code
switch (http_status_code) {
case 0: {
error_str = "No Connection. Cannot connect to " + new URL(url).hostname + ".";
break;
} // No Connection
case 400: {
error_str = "Bad Request." + message + " Please see help.";
break;
} // Bad Request
case 401: {
error_str = "Unauthorized." + message + " Please see help.";
break;
} // Unauthorized
case 402: {
error_str = "Request Failed." + message;
break;
} // Request Failed
case 404: {
error_str = "Not Found." + message + " Please see help.";
break;
} // Not Found
case 405: {
error_str = "Method Not Allowed." + message + " Please see help.";
break;
} // Method Not Allowed
case 409: {
error_str = "Conflict." + message + " Please see help.";
break;
} // Conflict
case 429: {
error_str = "Too Many Requests." + message + " Please try again later.";
break;
} // Too Many Requests
case 500: {
error_str = "Internal Server Error." + message + " Please see help.";
break;
} // Internal Server Error
case 502: {
error_str = "Bad Gateway." + message + " Please see help.";
break;
} // Bad Gateway
case 503: {
error_str = "Service Unavailable." + message + " Please see help.";
break;
} // Service Unavailable
case 504: {
error_str = "Gateway Timeout." + message + " Please see help.";
break;
} // Gateway Timeout
default: {
console.error(loc + "http_status_code unhandled >> http_status_code = " + http_status_code);
error_str = "Unknown Error." + message + " Please see help.";
break;
}
}
// 2. show popup
alert(error_str);
console.error(arguments.callee.name + " >> http_status_code = " + http_status_code.toString() + "; thrownError = " + thrownError + "; URL = " + url + "; Response = " + response);
}
catch (e) {
console.error(arguments.callee.name + " >> ERROR >> " + e.toString());
alert("Internal Error. Please see help.");
}
});
I think all you really need to check is the base error class of Stripe and the exception if it's unrelated to Stripe. Here's how I do it.
/**
* Config.
*/
require_once( dirname( __FILE__ ) . '/config.php' );
// Hit Stripe API.
try {
// Register a Customer.
$customer = \Stripe\Customer::create(array(
'email' => 'AA#TESTING.com',
'source' => $token,
'metadata' => array( // Note: You can specify up to 20 keys, with key names up to 40 characters long and values up to 500 characters long.
'NAME' => 'AA',
'EMAIL' => 'a#a.c.o',
'ORDER DETAILS' => $order_details,
)
));
// Charge a customer.
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => 5000, // In cents.
'currency' => 'usd'
));
// If there is an error from Stripe.
} catch ( Stripe\Error\Base $e ) {
// Code to do something with the $e exception object when an error occurs.
echo $e->getMessage();
// DEBUG.
$body = $e->getJsonBody();
$err = $body['error'];
echo '<br> ——— <br>';
echo '<br>THE ERROR DEFINED — <br>';
echo '— Status is: ' . $e->getHttpStatus() . '<br>';
echo '— Message is: ' . $err['message'] . '<br>';
echo '— Type is: ' . $err['type'] . '<br>';
echo '— Param is: ' . $err['param'] . '<br>';
echo '— Code is: ' . $err['code'] . '<br>';
echo '<br> ——— <br>';
// Catch any other non-Stripe exceptions.
} catch ( Exception $e ) {
$body = $e->getJsonBody();
$err = $body['error'];
echo '<br> ——— <br>';
echo '<br>THE ERROR DEFINED — <br>';
echo '— Status is: ' . $e->getHttpStatus() . '<br>';
echo '— Message is: ' . $err['message'] . '<br>';
echo '— Type is: ' . $err['type'] . '<br>';
echo '— Param is: ' . $err['param'] . '<br>';
echo '— Code is: ' . $err['code'] . '<br>';
echo '<br> ——— <br>';
}
How to get error message if your provided token is invalid. It break and show some exception in laravel. so i used stripe exception by using try and catch. It will work fine. try this code.You can show your own custom message instead of stripe message.
try{
\Stripe\Stripe::setApiKey ("your stripe secret key");
$charge = \Stripe\Charge::create ( array (
"amount" => 100,
"currency" => "USD",
"source" => 'sdf', // obtained with Stripe.js
"description" => "Test payment."
) );
$order_information = array(
'paid'=>'true',
'transaction_id'=>$charge->id,
'type'=>$charge->outcome->type,
'balance_transaction'=>$charge->balance_transaction,
'status'=>$charge->status,
'currency'=>$charge->currency,
'amount'=>$charge->amount,
'created'=>date('d M,Y', $charge->created),
'dispute'=>$charge->dispute,
'customer'=>$charge->customer,
'address_zip'=>$charge->source->address_zip,
'seller_message'=>$charge->outcome->seller_message,
'network_status'=>$charge->outcome->network_status,
'expirationMonth'=>$charge->outcome->type
);
$result['status'] = 1;
$result['message'] = 'success';
$result['transactions'] = $order_information;
}
catch(\Stripe\Exception\InvalidRequestException $e){
$result['message'] = $e->getMessage();
$result['status'] = 0;
}
Here is a functional demo of the try / catch with all the possible errors, just add your own functionality in each catch
try {
// Use Stripe's library to make requests...
$charge = \Stripe\Charge::create([
'amount' => $amount,
'currency' => "usd",
'description' => $description,
"receipt_email" => $mail,
]);
} catch(\Stripe\Exception\CardException $e) {
// Since it's a decline, \Stripe\Exception\CardException will be caught
echo 'Status is:' . $e->getHttpStatus() . '\n';
echo 'Type is:' . $e->getError()->type . '\n';
echo 'Code is:' . $e->getError()->code . '\n';
// param is '' in this case
echo 'Param is:' . $e->getError()->param . '\n';
echo 'Message is:' . $e->getError()->message . '\n';
} catch (\Stripe\Exception\RateLimitException $e) {
// Too many requests made to the API too quickly
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Exception\AuthenticationException $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Exception\ApiConnectionException $e) {
// Network communication with Stripe failed
} catch (\Stripe\Exception\ApiErrorException $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
}
You can get the official code from here

Categories