繁体   English   中英

使用 PHP 接收 JSON POST

[英]Receive JSON POST with PHP

我正在尝试在支付接口网站上接收 JSON POST,但我无法对其进行解码。

当我打印时:

echo $_POST;

我得到:

Array

当我尝试这个时我什么也没得到:

if ( $_POST ) {
    foreach ( $_POST as $key => $value ) {
        echo "llave: ".$key."- Valor:".$value."<br />";
    }
}

当我尝试这个时我什么也没得到:

$string = $_POST['operation'];
$var = json_decode($string);
echo $var;

当我尝试这个时,我得到 NULL:

$data = json_decode( file_get_contents('php://input') );
var_dump( $data->operation );

当我做:

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

我得到:

NULL

JSON 格式是(根据支付站点文档):

{
   "operacion": {
       "tok": "[generated token]",
       "shop_id": "12313",
       "respuesta": "S",
       "respuesta_details": "respuesta S",
       "extended_respuesta_description": "respuesta extendida",
       "moneda": "PYG",
       "monto": "10100.00",
       "authorization_number": "123456",
       "ticket_number": "123456789123456",
       "response_code": "00",
       "response_description": "Transacción aprobada.",
       "security_information": {
           "customer_ip": "123.123.123.123",
           "card_source": "I",
           "card_country": "Croacia",
           "version": "0.3",
           "risk_index": "0"
       }
    }
}

支付站点日志显示一切正常。 有什么问题?

尝试;

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];

从您的 json 和您的代码来看,您似乎已经正确拼写了operation一词,但它不在 json 中。

编辑

也许还值得尝试从 php://input 回显 json 字符串。

echo file_get_contents('php://input');

如果您已经设置了诸如 $_POST['eg'] 之类的参数,并且您不想更改它,只需这样做:

$_POST = json_decode(file_get_contents('php://input'), true);

这将为您省去将所有 $_POST 更改为其他内容的麻烦,并且如果您希望删除此行,您仍然可以发出正常的 post 请求。

值得指出的是,如果您使用json_decode(file_get_contents("php://input")) (正如其他人所提到的),如果字符串不是有效的 JSON,这将失败。

这可以通过首先检查 JSON 是否有效来简单地解决。 IE

function isValidJSON($str) {
   json_decode($str);
   return json_last_error() == JSON_ERROR_NONE;
}

$json_params = file_get_contents("php://input");

if (strlen($json_params) > 0 && isValidJSON($json_params))
  $decoded_params = json_decode($json_params);

编辑:请注意,删除上面的strlen($json_params)可能会导致细微的错误,因为json_last_error()在传递null或空白字符串时不会改变,如下所示:http: //ideone.com/va3u8U

使用$HTTP_RAW_POST_DATA而不是$_POST

它会按原样为您提供 POST 数据。

稍后您将能够使用json_decode()对其进行解码。

阅读文档:

通常,应使用 php://input 而不是 $HTTP_RAW_POST_DATA。

php 手册中所述

$data = file_get_contents('php://input');
echo $data;

这对我有用。

你可以像下面这样使用.. 像下面这样发布 JSON

在此处输入图像描述

从下面的php项目用户获取数据

// takes raw data from the request 
$json = file_get_contents('php://input');
// Converts it into a PHP object 
$data = json_decode($json, true);

 echo $data['requestCode'];
 echo $data['mobileNo'];
 echo $data['password'];

很晚了。
看来,(OP)已经尝试了所有给他的答案。
不过,如果您(OP)没有收到传递给“.PHP”文件的内容,则错误可能是 URL 不正确。
检查您是否调用了正确的“.PHP”文件。
(网址中的拼写错误或大写字母)
重要的是
检查您的 URL 在“http”之后是否有“s”(安全)。
例子:

"http://yourdomain.com/read_result.php"

应该

"https://yourdomain.com/read_result.php"

或任何一种方式。
添加或删除“s”以匹配您的 URL。

如果以上所有答案仍然导致您为 POST 输入 NULL,请注意 localhost 设置中的 POST/JSON,这可能是因为您没有使用 SSL。 (前提是您是带有 tcp/tls 而不是 udp/quic 的 HTTP)

PHP://input 将在非 https 上为空,如果您在流程中有重定向,请尝试在本地配置 https 作为标准做法以避免各种安全/xss 等问题

由于 php 魔术引号,解码可能会失败(并返回 null)。

如果魔术引号打开了从 _POST/_REQUEST/etc 读取的任何内容。 将有特殊字符,例如"\ ,它们也是 JSON 的一部分。尝试json_decode(这个转义字符串将失败。这是一个已弃用的功能,但某些主机仍然打开。

检查魔术引号是否打开的解决方法,如果是,则将其删除:

function strip_magic_slashes($str) {
    return get_magic_quotes_gpc() ? stripslashes($str) : $str;
}

$operation = json_decode(strip_magic_slashes($_POST['operation']));

当我尝试在 php 中检索发布的数据时,我得到了“null”

{
    "product_id": "48",
    "customer_id": "2",  
    "location": "shelf",  // shelf, store <-- comments create php problems
    "damage_types":{"Pests":1, "Poke":0, "Tear":0}
     // "picture":"jhgkuignk"  <-- comments create php problems
}

避免注释 json 代码,即使它没有显示错误

我想发布一个答案,该答案也使用 curl 获取内容,并使用 mpdf将结果保存到 pdf,因此您可以获得典型用例的所有步骤。 它只是原始代码(以便适应您的需求),但它可以工作。

// import mpdf somewhere
require_once dirname(__FILE__) . '/mpdf/vendor/autoload.php';

// get mpdf instance
$mpdf = new \Mpdf\Mpdf();

// src php file
$mysrcfile = 'http://www.somesite.com/somedir/mysrcfile.php';
// where we want to save the pdf
$mydestination = 'http://www.somesite.com/somedir/mypdffile.pdf';

// encode $_POST data to json
$json = json_encode($_POST);

// init curl > pass the url of the php file we want to pass 
// data to and then print out to pdf
$ch = curl_init($mysrcfile);

// tell not to echo the results
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1 );

// set the proper headers
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json', 'Content-Length: ' . strlen($json) ]);

// pass the json data to $mysrcfile
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

// exec curl and save results
$html = curl_exec($ch);

curl_close($ch);

// parse html and then save to a pdf file
$mpdf->WriteHTML($html);
$this->mpdf->Output($mydestination, \Mpdf\Output\Destination::FILE);

在 $mysrcfile 中,我将读取这样的 json 数据(如先前答案所述):

$data = json_decode(file_get_contents('php://input'));
// (then process it and build the page source)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM