Muzzstick
Muzzstick

Reputation: 344

Converting Request from CURL to PHP's Guzzle to access WHMCS API

I'm attempting to learn the latest version of Guzzle (6.2) and convert my cURL requests to the WHMCS API.

Using the example code from: http://docs.whmcs.com/API:JSON_Sample_Code

// The fully qualified URL to your WHMCS installation root directory
$whmcsUrl = "https://www.yourdomain.com/billing/";

// Admin username and password
$username = "Admin";
$password = "password123";

// Set post values
$postfields = array(
    'username' => $username,
    'password' => md5($password),
    'action' => 'GetClients',
    'responsetype' => 'json',
);

// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
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);

// Attempt to decode response as json
$jsonData = json_decode($response, true);

// Dump array structure for inspection
var_dump($jsonData);

I haven't as yet been able to work out how to get the same thing to work with Guzzle.

Here's what I have tried:

use GuzzleHttp\Client;

// The fully qualified URL to your WHMCS installation root directory
$whmcsUrl = "https://www.yourdomain.com/billing/";

// Admin username and password
$username = "Admin";
$password = "password123";

$client = new Client([
    'base_uri' => $whmcsUrl,
    'timeout'  => 30,
    'auth' => [$username, md5($password)],
    'action' => 'GetClients',
    'responsetype'  =>  'json'
]);

$response = $client->request('POST', 'includes/api.php');
echo $response->getStatusCode();
print_r($response,true);

This will most likely be a very obvious answer to those who've used Guzzle before.

Where am I going wrong here?

Upvotes: 1

Views: 1519

Answers (1)

carlosdubusm
carlosdubusm

Reputation: 1083

I think you need to use 'form_params' to send urlencoded POST data:

$username = "Admin";
$password = "password123";

// Set post values
$postfields = array(
    'username' => $username,
    'password' => md5($password),
    'action' => 'GetClients',
    'responsetype' => 'json',
);

$client = new Client([
    'base_uri' => 'https://www.yourdomain.com',
    'timeout'  => 30,
]);

$response = $client->request('POST', '/billing/includes/api.php', [
    'form_params' => $postfields
]);

Upvotes: 1

Related Questions