0

我从支付网关 (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
    }
?>

没有任何运气,所以我正在寻求有关如何实现这一目标的帮助。能够提取其他键值也会很有用。

谢谢

4

3 回答 3

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
}
于 2013-03-22T07:35:42.473 回答
2

您无法做到的原因json_decode($response)是因为$response它是一个对象,而不是 JSON 字符串。

Pin-PHP 库将根据https://github.com/noetix/pin-php/blob/master/src/Pin/Handler.php#L87自动为您解码所有请求

要查看响应是否成功,请将响应对象用作对象:

if ($response->response->success) {
    echo "Success!";
} else {
    echo "Failed :(";
}
于 2013-03-22T09:00:46.617 回答
0

为什么不直接使用 json 对象,例如:

$jsonobject = json_encode($responseText);
$response = $jsonobject->response->success;
if($response === true) {
    // code here
}
于 2013-03-22T07:50:08.780 回答