什么时候尝试成为Catch?

时间:2016-02-11 13:54:37

标签: php stripe-payments

我有这个尝试使用Stripe处理付款的Try / Catch块。我想检查一下,如果在Charge :: create方法中出现错误,那么TRY块中的其余代码是否会继续执行?否则,我的数据库将会更新,即使他们的付款没有通过,也会通过电子邮件发送客户。

请有人澄清一下Try / Catch的行为吗?

try {
  $charge = \Stripe\Charge::create(array(
    "amount" => $charge_amount, // amount in cents, again
    "currency" => CURRENCY,
    "source" => $token,
    "description" => $description,
    "receipt_email" => $email,
    "metadata" => $metadata)
  );

//adjust inventory
foreach ($_SESSION['cart'] as $item => $quantity)
{
  $db->query("UPDATE stock SET stock = stock - '$quantity', reserved = reserved + '$quantity' WHERE id = '$item'");
}
unset($_SESSION['cart']);
//update cart
$db->query("UPDATE cart SET paid = 1 WHERE id = '$cart_id'");

blah blah, lots of other stuff...

} catch(\Stripe\Error\Card $e) {
  // The card has been declined
  echo $e;
}

2 个答案:

答案 0 :(得分:4)

是的,就是这样。

try(几乎)任何编程语言中的try ... catch块基本上都会尝试在块中运行代码,但是当它遇到错误(特别是异常)时会停止,并且会被CAUGHT处理并作为有向 - 假设catch块成功运行,执行将在try ... catch块结束后继续执行(除非您将执行作为catch语句的一部分退出)。

答案 1 :(得分:1)

尝试在抛出错误时成为catch。这意味着如果\ Stripe \ Charge :: Create方法失败,它将立即转到您的catch块并绕过数据库更新,客户电子邮件和所有其他方法。

话虽如此,您可能仍希望在对客户收费和其他处理之间进行更多检查。至少检查$ charge-> paid == true。为了更加小心(我们在这里谈钱)检查livemode是否为真,货币是你的货币(美元?),金额是你预期的。

查看Larry Ullman的网站,了解如何处理条带错误以获取更多信息: http://www.larryullman.com/2013/01/30/handling-stripe-errors/

此外:
http://www.larryullman.com/2013/01/09/writing-the-php-code-to-process-payments-with-stripe/