웹관련자료(web)/php & ajax

PHP 에서 CURL 로 JSON 형식으로 보내고 리턴받기(POST 전송)

2pie 2022. 8. 24. 08:54

$url = "http://xxx.xxx.xxx.xxx/request";
$post_date = array( "uuid" => $uuid,
   "amount" => $amount,
   "currency" => $currency,
   "from" => $from,
   "way" => $way,
   "to" => $to);
$json_data = json_encode($post_date);

$flg = curlSend($url, $json_data);

if($flg=='Y') {
   //결과가 "Y" 경우 처리
} else if($flg=='N') {
   //결과가 "N" 경우 처리
}


function curlSend($url, $json_data)
{
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

   curl_setopt($ch, CURLOPT_POST, true);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);

   curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
   curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));

   curl_setopt($ch, CURLOPT_VERBOSE, true);
    
   curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   curl_setopt($ch, CURLOPT_FAILONERROR, true);

   $response = curl_exec($ch);
   curl_close($ch);

   if(curl_error($ch)) {
      $curl_data = null;
   } else {
      $curl_data = $response;
   }

   //받은 JSON데이터를 배열로 만듬
   $json_data = json_decode($curl_data,true);

   //배열 제어
   if($json_data["result"] == "success") {
     return "Y";
   } else {
    return "N";
   }
}