通过PHP curl在API上发布数据时获取null

时间:2018-12-15 10:23:29

标签: php curl

我正在一个项目中,正在通过PHP Curl将一些数据发布到API。正在获得成功的响应,除了在dd()之后在数据对象中得到null之外。

dd之后的浏览器上的数据

  {#367 ▼
      +"request_time": "2018-12-15 12:26:49"
      +"response_time": "2018-12-15 12:26:49"
      +"status": "success"
      +"message": "All Output"
      +"data": null
    }

调用控制器中的curl功能

 $data = array(
              "from_date"  => "2018-01-01",
              "to_date" => "2018-11-01"
          );

$general = GeneralHelper::global_Curl($data,'api/v1/b2b/general/ofa/agent-commission');

dd($general);

卷曲功能

public static function global_Curl($data, $url)
    {
        $server = env('API_ENDPOINT_NGINX_IP') !== null ? env('API_ENDPOINT_NGINX_IP') : env('API_ENDPOINT_NGINX_IP');

        $accessToken = session('access_token');

        $headers = ['Accept:application/json',
                    'Authorization:Bearer '.$accessToken
                    ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, ($server.'/'.$url));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        //curl_setopt($ch, CURLOPT_HEADER, array('Accept:application/json', 'Authorization: Bearer '.$accessToken));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $response = json_decode(curl_exec($ch)); //dd(curl_exec($ch));
        curl_close($ch);

        return $response;
    }

1 个答案:

答案 0 :(得分:1)

您必须发送application/json编码的请求。

它是这样完成的:

public static function global_Curl($data, $url)
{
    $server = env('API_ENDPOINT_NGINX_IP') !== null ? env('API_ENDPOINT_NGINX_IP') : env('API_ENDPOINT_NGINX_IP');

    $accessToken = session('access_token');

    $headers = [
      'Content-Type: application/json', 
      'Authorization: Bearer '.$accessToken
    ];
    $url = $server.'/'.$url;
    $data = json_encode($data); // since content type is application/json

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $response = curl_exec($ch);
    curl_close($ch);

    return json_decode($response);
}

示例herehere