Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

php - CURL POST request is not working with headers

im trying to send a post request to this API and it returns me with "error": "unauthorized", "error_description": "An Authentication object was not found in the SecurityContext" when i send the same request with postman it works fine.

here is the code that I'm using

$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);
question from:https://stackoverflow.com/questions/66060562/curl-post-request-is-not-working-with-headers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The headers should be defined as an array, not an associative array.

Also, because you have set your Content-Type as application/json, your request data should be represented as JSON, this can be done using 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...