chathura
chathura

Reputation: 13

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

Upvotes: 0

Views: 184

Answers (1)

RJK
RJK

Reputation: 516

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

Upvotes: 2

Related Questions