如果没有发生错误,如何使Try / catch条带错误处理程序将用户发送到success.php?

时间:2019-02-18 12:34:56

标签: php stripe-payments

我正在为我的业务设置结帐页面,为此我使用Stripe API。错误处理程序未返回任何错误时,我的charge.php文件无法重定向时出现问题。

我尝试使用header()函数,如果我输入了正确的卡详细信息,它会成功重定向,但是当我尝试使用其中一张显示错误消息的卡时,它只会重定向到index.html,输入表单位于。如果我删除标头函数,charge.php将成功显示错误,但是很明显,成功充电不会重定向。

  // added stripe dependencies with composer
require_once('vendor/autoload.php');

  \Stripe\Stripe::setApiKey('SECRETKEY');

 // Sanitize POST Array
 $POST = filter_var_array($_POST, FILTER_SANITIZE_STRING);

 $first_name = $POST['first_name'];
 $last_name = $POST['last_name'];
 $email = $POST['email'];
 $token = $POST['stripeToken'];

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

// Charge Customer

$charge = \Stripe\Charge::create(array(
  "amount" => 4999,
  "currency" => "usd",
  "description" => "Online Purchase",
  "customer" => $customer->id
));

//ERROR HANDLER
} 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>YOU HAVE NOT BEEN CHARGED — <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 '<p>If you have entered the correct details, please try DOMAIN (in Safari or Chrome). If the error persists, please screenshot this message and send it to me alongside your email address.</p>';
  echo '<br> ——— <br>';

// Catch any other non-Stripe exceptions.
} catch ( Exception $e ) {
    $body = $e->getJsonBody();
    $err  = $body['error'];
    echo '<br> ——— <br>';
    echo '<br>Error — <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 '<p>If you have entered the correct details, please try DOMAIN (in Safari or Chrome). If the error persists, please screenshot this message and send it to me alongside your email address.</p>'; 
    echo '<br> ——— <br>';
}

header('Location: success.php?tid='.$charge->id.'&product='.$charge->description);

我希望charge.php在成功充电后重定向到success.php并在错误充电时显示错误。

1 个答案:

答案 0 :(得分:3)

它进行重定向,因为它位于catch块之后。这些块将被执行,并且由于其中没有return语句,它将继续执行该块之后的下一行-您的重定向标题行。

您可以:

  1. 在创建费用之后,将header(....)行移至try块中
  2. return块中执行特定的exitcatch类型的行。

这都是可行的解决方案。