Laravel 5 在 localhost:8000 上捕获 PayPal PHP API 400 个错误

Laravel 5 catching PayPal PHP API 400 errors on localhost:8000

在我的 Laravel 5.2 安装中使用 PayPal API,特别是这个包:https://github.com/anouarabdsslm/laravel-paypalpayment

这个包很好用!我正在完美地接受付款!当细节不正确时,我正在努力捕捉和重定向,例如银行卡详细信息由用户输入。 Laravel 应用程序仅抛出 400 错误。

我想做的是捕获错误并重定向回来并通知用户。

下面的代码是我提出请求的地方:

try {
    // ### Create Payment
    // Create a payment by posting to the APIService
    // using a valid ApiContext
    // The return object contains the status;

    $payment->create($this->_apiContext);

} catch (\PPConnectionException $ex) {
    return Redirect::back()->withErrors([$ex->getMessage() . PHP_EOL]);
}

dd($payment);

成功付款后,我得到一个很好的 return 对象,我可以参考它并采取相应的行动,当出现 400 错误之类的问题时,它会完全终止应用程序并且不会捕获并重定向错误反馈给用户。

错误代码消息是:

PayPalConnectionException in PayPalHttpConnection.php
Got Http response code 400 when accessing 
https://api.sandbox.paypal.com/v1/payments/payment.

有人在使用 PayPal PHP API 时遇到过类似问题吗?

我知道当应用程序不处于开发模式时,我可以有错误页面专门用于捕获某些错误代码。但我真的很想捕获错误并重定向回带有用户通知的表单。

提前感谢任何可以提供帮助的向导。

对的人,

我在这里发布了答案: 但我想确保访问此主题的任何人都知道我是如何解决这个问题的!

Laravel 的默认 Exception 方法似乎干扰了 PayPal API PayPalConnectionException。所以我修改了代码以仅捕获一般 Exception 错误,因为它包含所有必需的错误对象。 Exception 之前的 \ 很关键!因为它需要正确的命名空间(无论如何,在我的情况下,您的应用程序可能会有所不同)。

try {
    // ### Create Payment
    // Create a payment by posting to the APIService
    // using a valid ApiContext
    // The return object contains the status;
    $payment->create($this->_apiContext);

} catch (\Exception $ex) {
    return Redirect::back()->withErrors([$ex->getData()])->withInput(Input::all());
}

@rchatburn 发布的这个 link 非常有用,应用程序似乎总是在 \Exception 点捕获,而不是 \PayPalConnectionException 一旦我正确命名了所有内容。

在我的调查中,我遇到了 app/Exceptions/Handler.php。在这里,您可以扩展 render 方法以获取 PayPalConnectionException 并针对该特定异常专门处理错误。见代码:

//Be sure to include the exception you want at the top of the file
use PayPal\Exception\PayPalConnectionException;//pull in paypal error exception to work with

public function render($request, Exception $e)
{
    //check the specific exception
    if ($e instanceof PayPalConnectionException) {
        //return with errors and with at the form data
        return Redirect::back()->withErrors($e->getData())->withInput(Input::all());
    }

    return parent::render($request, $e);
} 

两者都很好,但对我来说,将 catch 方法更改为监视一般 Exception 感觉更简洁,我正在测试付款是否成功。

希望这对面临类似问题的人有所帮助 :D!!!

尼克。

如果您想要 API 电话的 JSON 详细信息,您可以添加以下代码。

  try {
          // ### Create Payment
          // Create a payment by posting to the APIService
          // using a valid ApiContext
          // The return object contains the status;
          $payment->create($this->_apiContext);
      } catch (\Exception $ex) {
          return dd($ex->getData());
          exit(1);
      }

希望对你有帮助