Paypal PHP Rest API 用于信用卡支付,如何处理错误以显示给用户

Posted

技术标签:

【中文标题】Paypal PHP Rest API 用于信用卡支付,如何处理错误以显示给用户【英文标题】:Paypal PHP Rest API for credit card payment , how to handle the errors to show it to the users 【发布时间】:2014-06-15 03:21:13 【问题描述】:

我正在使用来自here 的 Paypal php Rest API 进行信用卡支付。我可以使用演示数据成功付款。当用户实时面临信用卡支付错误时,我需要一种以用户友好的方式而不是程序化的方式来显示它的方法。

从 paypal developer site 中,我找到了返回的错误对象的格式,但不知道如何使用它。

我的代码如下:

try 
    $payment->create($apiContext);


 catch (PayPal\Exception\PPConnectionException $ex) 

echo "Exception: " . $ex->getMessage() . PHP_EOL;
    var_dump($ex->getData());


故意输入错误数据,出现以下错误消息:

        Exception: Got Http response code 400 when accessing 
    https://api.sandbox.paypal.com/v1/payments/payment.

        string '"name":"VALIDATION_ERROR","details":

    ["field":"payer.funding_instruments[0].credit_card",
    "issue":"Invalid expiration (cannot be in the past)",

    "field":"payer.funding_instruments[0].credit_card.number",
    "issue":"Value is invalid","field":
    "payer.funding_instruments[0].credit_card.cvv2",
    "issue":"Length is invalid (must be 3 or 4, 
    depending on card type)"],"message":"Invalid request 
    - see details","information_link":
    "https://developer.paypal.com/webapps
/developer/docs/api/#VALIDATION_ERROR","debug_id":
"bdcc'... (length=523)

那么我怎样才能得到上面提到的 Paypal 开发者网站中所说的错误对象,以及如何使用它向非技术人员显示错误?

【问题讨论】:

【参考方案1】:

返回的错误是 JSON 格式。您可以使用json_decode 在 PHP 中对其进行解码:

$error_object = json_decode($ex->getData());
switch ($error_object->name)

    case 'VALIDATION_ERROR':
        echo "Payment failed due to invalid Credit Card details:\n";
        foreach ($error_object->details as $e)
        
            echo "\t" . $e->field . "\n\t" . $e->issue . "\n\n";
        
        break;

将您想要的任何情况添加到您的开关。您可以添加自己的风格,解析$e->field$e->issue 以显示您喜欢的任何内容,等等。

【讨论】:

你能给出paypal提到这个的网址吗? 从您发布的链接PayPal Developer Site 请求和响应有效负载格式为 JSON。 SDK 也是如此。至于代码,您可以自行处理错误。

以上是关于Paypal PHP Rest API 用于信用卡支付,如何处理错误以显示给用户的主要内容,如果未能解决你的问题,请参考以下文章