首页 > 解决方案 > CURL POST 请求不适用于标头

问题描述

我试图向这个 API 发送一个发布请求, "error": "unauthorized", "error_description": "An Authentication object was not found in the SecurityContext"当我用邮递员发送相同的请求时它会返回给我,它工作正常。

这是我正在使用的代码

$url = config('payhere.cancel_url');
    $postRequest = array(
        'subscription_id'=>$payhereID
    );
    $headers = array(
        'Authorization' =>'Bearer '.$accessToken,
        'Content-Type'=>'application/json'
    );
   
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // SSL important
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$postRequest);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    

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


    $respo = $this -> response['response'] = json_decode($output);

标签: phplaravelcurl

解决方案


标头应定义为数组,而不是关联数组。

此外,由于您已将 Content-Type 设置为application/json,因此您的请求数据应表示为 JSON,这可以使用json_encode.

$url = config('payhere.cancel_url');
$postRequest = array(
    'subscription_id'=>$payhereID
);
$headers = array(
    'Authorization: Bearer '.$accessToken,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// SSL important
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($postRequest));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$output = curl_exec($ch);

curl_close($ch);

$respo = $this->response['response'] = json_decode($output);

https://www.php.net/manual/en/function.curl-setopt.php


推荐阅读