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

时间:2014-04-29 09:13:13

标签: php paypal paypal-rest-sdk

我使用来自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 个答案:

答案 0 :(得分:3)

返回的错误是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以显示您喜欢的内容等。