Отлов ошибок с помощью Stripe PHP

У меня есть собственный код PHP Stripe для пожертвований.

У меня возникают проблемы с обнаружением отклоненных карточек или общая ошибка (например, когда пользователь пытается загрузить PHP-страницу обработки карточек, которая должна перенаправлять на страницу с ошибкой).

ПОЖЕРТВОВАНИЕ.PHP

//Create Customer
$customer = \Stripe\Customer::create(array(
    "email" => $email,
    "source"  => $token
));

try {
    //Charge the Card
    $charge = \Stripe\Charge::create(array(
        "customer" => $customer->id,
        "amount" => $totalAmount,
        "currency" => "usd",
        "description" => "Name: $fname $lname For: Donation",
        "statement_descriptor" => "DONATION",
    ));

} catch (\Stripe\Error\InvalidRequest $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch (\Stripe\Error\Base $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch (Exception $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch(\Stripe\Error\Card $e) {
    // Since it's a decline, \Stripe\Error\Card will be caught
    $body = $e->getJsonBody();
    $err  = $body['error'];
    header("Location: https://example.com/declined/");
    exit();
};

//Send User to Thank You Page
header("Location: https://example.com/thank-you/");
exit();

Во время тестирования отклоненная карта просто переходит на страницу «ошибка» по сравнению со страницей «отклонено». Попытка загрузить страницу «donation.php» напрямую приводит к «ошибке».

Приведенный выше код на самом деле не обрабатывает платеж, насколько я могу судить, поскольку он никогда не отображается на моей вкладке платежей с чередованием в тестовом режиме.

Спасибо вам за помощь!

=== обновлено по запросу

try {
    //Charge the Card
    $charge = \Stripe\Charge::create(array(
        "customer" => $customer->id,
        "amount" => $totalAmount,
        "currency" => "usd",
        "description" => "Name: $fname $lname For: Donation",
        "statement_descriptor" => "DONATION",
    ));

} catch (\Stripe\Error\InvalidRequest $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch(\Stripe\Error\Card $e) {
    // Since it's a decline, \Stripe\Error\Card will be caught
    $body = $e->getJsonBody();
    $err  = $body['error'];
    header("Location: https://example.com/declined/");
    exit();

} catch (\Stripe\Error\Base $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch (Exception $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();
};

//Send User to Thank You Page
header("Location: https://example.com/thank-you/");
exit();

person Luis M    schedule 14.08.2019    source источник
comment
Вы должны поместить исключения в порядке области действия. Exception поймает все, что не указано ранее, поэтому его нужно разместить последним.   -  person aynber    schedule 14.08.2019
comment
Да, я пытался, и после попытки отклонить карту я получаю эту ошибку: Неустранимая ошибка PHP: Uncaught Stripe\Error\Card: Ваша карта была отклонена. в /home/xxx/stripe/lib/ApiRequestor.php:214 из запроса API 'req_xxxxx   -  person Luis M    schedule 14.08.2019
comment
Странный. Все перехвачено с помощью Exception, являющегося универсальным, поэтому оно не должно вызывать неперехваченную ошибку. Можете ли вы отредактировать свой пост с текущим кодом и полной трассировкой, если она у вас есть?   -  person aynber    schedule 14.08.2019
comment
Хорошо, я отредактировал сообщение с последним кодом. У меня нет полной трассировки, спасибо   -  person Luis M    schedule 14.08.2019


Ответы (1)


} catch (Exception $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

}

Будет ловить любое исключение, поэтому он всегда возвращается к этому и не переходит к вашему блоку перехвата отклонения.

Запишите это так:

//Create Customer
$customer = \Stripe\Customer::create(array(
    "email" => $email,
    "source"  => $token
));

try {
    //Charge the Card
    $charge = \Stripe\Charge::create(array(
        "customer" => $customer->id,
        "amount" => $totalAmount,
        "currency" => "usd",
        "description" => "Name: $fname $lname For: Donation",
        "statement_descriptor" => "DONATION",
    ));

} catch (\Stripe\Error\InvalidRequest $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch (\Stripe\Error\Base $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

} catch(\Stripe\Error\Card $e) {
    // Since it's a decline, \Stripe\Error\Card will be caught
    $body = $e->getJsonBody();
    $err  = $body['error'];
    header("Location: https://example.com/declined/");
    exit();
} catch (Exception $e) {
    //Send User to Error Page
    header("Location: https://example.com/error/");
    exit();

};

//Send User to Thank You Page
header("Location: https://example.com/thank-you/");
exit();
person Girgias    schedule 14.08.2019
comment
Спасибо, я внес изменение, и после попытки использовать отклоненную карту я получаю эту ошибку: Неустранимая ошибка PHP: Uncaught Stripe\Error\Card: Ваша карта была отклонена. в /home/xxx/stripe/lib/ApiRequestor.php:214 из запроса API 'req_xxxxx' - person Luis M; 14.08.2019
comment
Это может быть выстрел в темноте, но Base, похоже, является родительским классом Card, что произойдет, если вы поменяете местами эти два блока catch? - person Girgias; 14.08.2019