基于json数组的决策

时间:2015-01-28 08:15:24

标签: php arrays json

我正在使用支付网关API来处理退款。

成功操作后,API会返回一个像这样的

的json数组
{
"currencyCode" : "GBP",
"amount" : 100,
"originalMerchantRefNum" : "MERCHANTREF12346",
"mode" : "live",
"confirmationNumber" : 1997160616609792,
"authType" : "refund",
"id" : "25TWPTLHRR81AIG1LF"
}

错误时返回的数组是

 {
  "error": {
    "code": "400",
    "message": "Amount exceeds refundable amount"
  }
}

我需要解码json输出然后将其显示给用户。但由于json数组的结构在两种情况下都不同,我如何去解析json数组,以便为​​最终用户提供相关的可读数据。

我的代码,来自网关处理器的所有通话和提取数据都在下面给出

<?php
include('lock.php');
$flag=0;
$oid=$_POST['oid'];

if(isset($_POST['amount']))
{
$amount=$_POST['amount'];
$amount = $amount*100;
$flag=1;
}

// generate random number
$merchantref=mt_rand(10,9999999999);

//API Url
$url = 'https://api.netbanx.com/hosted/v1/orders/'.$oid.'/refund';
//Initiate cURL.
$ch = curl_init($url);


//The JSON data.
if($flag==1)
{
$jsonData = array(
    "amount" => $amount,
    'merchantRefNum' => $merchantref
);
}
else
{
$jsonData = array(
    'merchantRefNum' => $merchantref
);
}
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json and HTTP Authorization code

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("..") //Base 64 encoding and appending Authorization: Basic 
);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

//Execute the request
$result = curl_exec($ch);

$jdata=$result;

//decode the json output and store it in a variable
$jfo = json_decode($jdata);

//Handle decision making based on json output


?>

1 个答案:

答案 0 :(得分:1)

基本上简单如下:

$response = json_decode(..., true);

if (isset($response['error'])) {
    echo 'Sorry, ', $response['error']['message'];
} else {
    echo 'Yay!';
}

您需要检查的具体内容取决于API可能返回的可能值。大多数API指定的内容status将设置为'success''error',如果{{1},则可能“ } key存在,这表示错误,否则成功“