我从支付网关(JSON)获得以下响应:
{
"response": {
"token": "ch_lfUYEBK14zotCTykezJkfg",
"success": true,
"amount": 400,
"currency": null,
"description": "test charge",
"email": "user@user.com",
"ip_address": "203.192.1.172",
"created_at": "2012-06-20T03:10:49Z",
"status_message": "Success!",
"error_message": null,
"card": {
"token": "card_nytGw7koRg23EEp9NTmz9w",
"display_number": "XXXX-XXXX-XXXX-0000",
"scheme": "master",
"address_line1": "42 Sevenoaks St",
"address_line2": null,
"address_city": "Lathlain",
"address_postcode": "6454",
"address_state": "WA",
"address_country": "Australia"
},
"transfer": null
}
}
我正试图将success => true
部分放在if语句中,如下所示:
<?php
if($response['success'] == true) {
// continue transaction
}
?>
没有任何运气,所以我要求我如何实现这一目标。能够提取其他键值也很有用。
谢谢
答案 0 :(得分:3)
<强>更新强>
您的$response
已经是一个对象,因此该表达式应该有效:
if ($response->response->success == true) {
// etc
}
您是否只是在寻找解码字符串表示的代码?如果是这样的话:
$response = <<<'EOM'
{
"response": {
"token": "ch_lfUYEBK14zotCTykezJkfg",
"success": true,
"amount": 400,
"currency": null,
"description": "test charge",
"email": "user@user.com",
"ip_address": "203.192.1.172",
"created_at": "2012-06-20T03:10:49Z",
"status_message": "Success!",
"error_message": null,
"card": {
"token": "card_nytGw7koRg23EEp9NTmz9w",
"display_number": "XXXX-XXXX-XXXX-0000",
"scheme": "master",
"address_line1": "42 Sevenoaks St",
"address_line2": null,
"address_city": "Lathlain",
"address_postcode": "6454",
"address_state": "WA",
"address_country": "Australia"
},
"transfer": null
}
}
EOM;
$responseData = json_decode($responseText, true);
if ($responseData['response']['success'] == true) {
// continue transaction
}
答案 1 :(得分:2)
您无法json_decode($response)
的原因是因为$response
是一个对象,而不是一个JSON字符串。
根据https://github.com/noetix/pin-php/blob/master/src/Pin/Handler.php#L87
,Pin-PHP库会自动为您解码所有请求要查看响应是否成功,请使用响应对象作为对象:
if ($response->response->success) {
echo "Success!";
} else {
echo "Failed :(";
}
答案 2 :(得分:0)
为什么不直接使用json对象:
$jsonobject = json_encode($responseText);
$response = $jsonobject->response->success;
if($response === true) {
// code here
}