source

PHP와 함께 JSON POST 수신

goodcode 2022. 9. 11. 17:13
반응형

PHP와 함께 JSON POST 수신

결제 인터페이스 사이트에서 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를 모두 다른 것으로 변경하는 번거로움을 덜 수 있으며, 이 라인을 빼고 싶을 때에도 정상적인 포스트 요청을 할 수 있습니다.

지적할 가치가 있습니다.json_decode(file_get_contents("php://input"))(다른 사람이 언급했듯이) 문자열이 유효한 JSON이 아닐 경우 실패합니다.

이 문제는 먼저 JSON이 유효한지 확인하는 것만으로 해결할 수 있습니다.

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_RAW_POST_DATA대신$_POST.

POST 데이터를 그대로 제공합니다.

다음을 사용하여 디코딩할 수 있습니다.json_decode()이따가.

다음 문서를 읽습니다.

일반적으로 $HTTP_ 대신 php://input을 사용해야 합니다.RAW_POST_DATA.

php 매뉴얼과 같이

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

이건 나한테 효과가 있었어.

Bellow를 사용하면...아래처럼 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의 철자 오류 또는 대문자)
그리고 가장 중요한 것은
URL의 "http" 뒤에 "s"(보안)가 있는지 확인합니다.
예:

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

그래야 한다

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

어느 쪽이든.
URL과 일치하도록 "s"를 추가 또는 제거합니다.

위의 답변이 모두 POST를 위한 NULL 입력으로 이어지는 경우 로컬호스트 설정의 POST/JSON은 SSL을 사용하지 않기 때문일 수 있습니다(단, HTTP에서 tcp/tls를 사용하고 있고 udp/quic를 사용하지 않는 경우).

PHP://input은 비https에서는 무효가 됩니다.플로우에 리다이렉트가 있는 경우 보안/xss 등의 다양한 문제를 피하기 위해 로컬에서 https를 표준 프랙티스로 설정합니다.

php 매직 따옴표로 인해 디코딩이 실패할 수 있습니다(그리고 null을 반환).

_POST/ 모든 되어 있는 _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']));

콘텐츠를 얻기 위해 컬을 사용하고 결과를 PDF에 저장하기 위해 mpdf를 사용하는 답변도 게시하고 싶습니다. 그러면 팁형 사용 사례의 모든 단계를 알 수 있습니다.이것은 (필요에 맞게) 미가공 코드일 뿐이지만 효과가 있습니다.

// 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)

언급URL : https://stackoverflow.com/questions/18866571/receive-json-post-with-php

반응형