Hello Guys,
I have created a small but effective PHP consumer for WHMCS the code is below;
<?php
/**
* @author Thomas Bibb
* @version 0.1
* @copyright Oxide Technologies Ltd 2011
*/
class WHMCS_Api{
private $config = Array();
public function __construct(array $config) {
if (!(isset($config['endpoint']))) {
throw new Exception(
"A endpoint must be specfied"
);
}
if (!(isset($config['username']))) {
throw new Exception(
"A username must be specfied"
);
}
if (!(isset($config['password']))) {
throw new Exception(
"A password must be specfied"
);
}
$config['responsetype'] = 'json';
$config['password'] = md5($config['password']);
$this->config = $config;
}
public function __get($name) {
if (!(isset($config[$name]))) {
throw new Exception(
"Unknown variable {$name}"
);
}
return $config[$name];
}
/**
* @name __call
* @desc call a remote method
*/
public function __call($action, array $arguments) {
if (!(isset($action))) {
throw new Exception(
"A action name is required"
);
}
$opt = Array ('action' => $action);
$opt = array_merge($opt, $arguments);
$opt = array_merge($opt, $this->config);
unset($opt['endpoint']);
return $this->__rpc($opt);
}
/**
*
* @name RPC
* @desc Faciliates the call to the remote Web Service
* @param array $post
*/
private function __rpc(array $arguments) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->config['endpoint']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
$responce = curl_exec($ch);
curl_close($ch);
$responce = json_decode($responce);
if ($responce->result == 'error') {
throw new Exception(
'API Error: '.$responce->message
);
}
return $responce;
}
}
?>
To use the class just do the following;
require 'api.php';
/* Setup the API */
$api = new WHMCS_Api(array(
'endpoint' => 'http://mydomain.com/includes/api.php',
'username' => 'myusername',
'password' => 'mypassword',
));
$postfields["clientid"] = "0";
$postfields["deptid"] = "1";
$postfields["subject"] = "Testing API Consumer";
$postfields["message"] = "This is a sample ticket opened by the API";
$postfields["priority"] = "Low";
$api->__call('openticket', $postfields);