Call with curl works, its version with Guzzle 6 does not

226 Views Asked by At

I am trying to convert a code that works, to its version with Guzzle, but I do not get the desired result, and I think it is due to a lack of understanding of Guzzle v6.

If I execute the following code, it's work fine

$postfields = array(
    'identifier' => $this->username,
    'secret' => $this->password,
    'accesskey' => $this->accesskey,
    'action' => 'GetClients',
    'responsetype' => self::RESPONSE_TYPE,
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url.self::ENDPOINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));

$response = curl_exec($ch);

if (curl_error($ch)) {
    die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}

curl_close($ch);

// Decode response
$jsonData = json_decode($response, true);

But if I try to convert to Guzzle v6, fails

$client = new GuzzleHttp\Client();

$response = $client->post($this->url.self::ENDPOINT, [
    'headers' => [
        'action' => 'GetClients',
        'identifier' => $this->username,
        'secret' => $this->password,
        'accesskey' => $this->accesskey,
        'responsetype' => self::RESPONSE_TYPE
    ]
]);

I get an exception

GuzzleHttp\Exception\ClientException  : Client error: `GET https://mydomain.test/intranet/includes/api.php` resulted in a `403 Forbidden` response:
result=error;message=Invalid IP 2.137.XXX.XX

On the other hand I do not know how to understand the call (url that forms Guzzle) with the get() method of Guzzle client.

1

There are 1 best solutions below

0
On

An error in understanding the mechanism of sending the parameters, using headers instead of a correct form_params since it is a POST method

Correct code is

$response = $client->post($this->url.self::ENDPOINT, [
    'form_params' => [
        'action' => 'GetClients',
        'identifier' => $this->username,
        'secret' => $this->password,
        'accesskey' => $this->accesskey,
        'responsetype' => self::RESPONSE_TYPE
    ]
]);