我在这里看了一堆问题/答案,似乎没有一个能解决我的问题。我正在集成一个支付系统,它通过JS库返回一个JSON字符串,然后我需要在服务器上解析它以比较哈希值以确保它是有效的。所以我得到他们的回应,并尝试通过jQuery AJAX将其传递给服务器上的PHP文件。我从支付系统得到的回复是有效的JSON。如果我直接传递它,我在服务器上得到的结果似乎是URL编码。如果我JSON.stringify()它,它会添加一堆额外的引号,导致无效的JSON。
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
$json_params = file_get_contents("php://input");
error_log($json_params);
//error_log($_POST['jsresp']);
//$respObj = json_decode(stripslashes($_POST['jsresp']));
//error_log($json_params);
if (strlen($json_params) > 0 && isValidJSON($json_params)) {
$respObj = json_decode($json_params);
} else {
error_log('bad json '.$json_params);
}
$result = 0;
$resp = json_encode($respObj->Response);
$hash = $respObj->Hash;
error_log($hash);
$calcHash = base64_encode(hash_hmac('sha512', $resp, $app->getSageClientSecret(), true));
error_log($calcHash);
if($hash === $calcHash) {
$result = 1;
}
$app->updateCartResponse($_COOKIE['qid'], $result);
这是发送数据的jQuery AJAX调用:
$(document).on('click', 'button#sps-close.sps.btn.btn-primary', function(){
var resp = $("#resp_holder").val();
$.ajax({
url: "<?=$env?>sources/processors/process_hash.php",
data: { jsresp : resp },
type: "post",
//dataType: "json",
success: function( data ) {
// nothing to do here.
}
});
var url = $("#redirect_url").val();
if(url != "") {
location.href = $("#redirect_url").val();
}
});
当我这样做时,到达服务器的JSON如下所示:
jsresp%5Bresponse%5D=%7B%22requestId%22%3A%22443594%22%2C%22gatewayResponse%22%3A%7B%22status%22%3A%22Approved%22%2C%22reference%22%3A%22EBGHNHChw0%22%2C%22message%22%3A%22APPROVED+658658%22%2C%22code%22%3A%22658658%22%2C%22cvvResult%22%3A%22P%22%2C%22avsResult%22%3A%22+%22%2C%22riskCode%22%3A%2200%22%2C%22networkId%22%3A%2210%22%2C%22isPurchaseCard%22%3Afalse%2C%22orderNumber%22%3A%22443594%22%2C%22transactionId%22%3A%22NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ%22%2C%22timestamp%22%3A%222017-11-16T23%3A17%3A12.6584893-05%3A00%22%7D%7D&jsresp%5Bhash%5D=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp%2B4MyN9chFZZoo%2F3IuZPX7bbQ%2BRyaReKN1CNJXxRmjnLMRQ%3D%3D
我不明白我做错了什么或如何正确地把它弄到那里。
答案 0 :(得分:0)
根据您的示例,这是您在服务器上获得的
jsresp[response]={"requestId":"443594","gatewayResponse":{"status":"Approved","reference":"EBGHNHChw0","message":"APPROVED 658658","code":"658658","cvvResult":"P","avsResult":" ","riskCode":"00","networkId":"10","isPurchaseCard":false,"orderNumber":"443594","transactionId":"NDViMWYzNmEwNWNiOGQxZjIwOTAwNzU4MmVjYzJhMWQ","timestamp":"2017-11-16T23:17:12.6584893-05:00"}}&jsresp[hash]=bgd1e0Cxhj5s1FQaUFFYk7BMnSIl4Ez1jPMopZFp+4MyN9chFZZoo/3IuZPX7bbQ+RyaReKN1CNJXxRmjnLMRQ==
所以你的$_REQUEST['jsresp']
是一个数组
你需要json_decode数组的'response'
索引:
$respObj = json_decode($_REQUEST['jsresp']['response']);
$hash = $_REQUEST['jsresp']['hash'];
然后你可以继续......
答案 1 :(得分:0)
首先我会建议你查看#resp_holder中的值,如果你想要它的值是正确的,那么你可以使用任何你想要的方式发布它,json是一个字符串,只要那个string符合json标准,它们就像&amp;中没有特殊字符,那么你可以在php中解码它。
您可以使用html或json dataType发布它。