我将PHP 7与Phalcon 3一起使用。我想在一个函数中实现Stripe响应。我可以处理类似that的错误。
这是代码:
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
}
每次我需要调用Stripe方法时,都需要实现所有这些try catch。如何创建一个具有所有Stripe异常的函数?我想到了在参数中发送带区函数并在尝试中使用该函数的想法,但是它不起作用,因为该函数在进入函数内部之前就已执行。
function stripeResponse($function) {
try {
// Use Stripe's library to make requests...
\Stripe\Stripe::setApiKey("my_key");
$function();
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card will be caught
} 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
}
}
return $this->stripeResponse(\Stripe\Charge::create([
"amount" => 100,
"currency" => "eur",
"source" => "token",
"description" => "Description"
]));
您有做我想做的主意吗?
答案 0 :(得分:4)
您呼叫$this->stripeResponse
的方式不正确。您正在传递\Stripe\Charge::create
而不是可调用的响应。
您可以将其更改为:
return $this->stripeResponse(function() {
\Stripe\Charge::create([
"amount" => 100,
"currency" => "eur",
"source" => "token",
"description" => "Description"
]);
});