ayat
ayat

Reputation: 171

How to make a GuzzleHttp post request with body and header?

I'm not able to understand how to modify this cURL into Laravel 5.8, getting {"code":"11", "message":"invalid Request found", "status":"DECLINED"} response.

Here is my cURL code which is working fine (in postman and browser):

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => 'https://api.hylo.biz/Api/v1.0/Payment',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{
       "orderId":"KJDHKSGIU768",
       "amount":"100",
       "redirect_url":"google.com"
    }',
    CURLOPT_HTTPHEADER => [
        'Authorization: Basic WUR1pYQ1hYY3U2Og2OGM6JJE5tWEDJhJDEwZReVE=',
        'Content-Type: application/json',
    ],
]);
$response = curl_exec($curl);
curl_close($curl);

echo $response;

Here is my laravel code:

public function process(Request $request)
{
    // return $request['request'];
    $client = new \GuzzleHttp\Client();
    $url = "https://api.hylo.biz/Api/v1.0/Payment";
    $response = $client->request('POST', $url, [
        'headers' => [
            'Authorization' => 'Basic WUR1pYQ1hYY3U2Og2OGM6JJE5tWEDJhJDEwZReVE=',
            'Content-Type'  => 'application/json'
         ],
         'form_params' => $request['request']
    ]);

    return $response = $response->getBody();
}

Upvotes: 2

Views: 788

Answers (1)

ayat
ayat

Reputation: 171

in this way it's working

public function process(Request $request)
{
    $curl = curl_init();
    curl_setopt_array($curl, [
    CURLOPT_URL => 'https://api.hylo.biz/Api/v1.0/Payment',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => '{
      "orderId":"KJDHKSGIU768",
      "amount":"100",
      "redirect_url":"google.com"
    }',
    CURLOPT_HTTPHEADER => [
       'Authorization: Basic WUR1pYQ1hYY3U2Og2OGM6JJE5tWEDJhJDEwZReVE=',
       'Content-Type: application/json',
      ],
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
}

and also I forgot to add use Illuminate\Http\Request;

Upvotes: 2

Related Questions