Skip to content

Instantly share code, notes, and snippets.

@ondrejnov
Last active February 25, 2017 15:49
Show Gist options
  • Select an option

  • Save ondrejnov/f385de491cb9b78e4429dfbe576d097c to your computer and use it in GitHub Desktop.

Select an option

Save ondrejnov/f385de491cb9b78e4429dfbe576d097c to your computer and use it in GitHub Desktop.
JsonRpcClient
<?php
define('API', 'https://HOST/api');
define('USERNAME', '******');
define('PASSWORD', '******');
$client = new SimpleJsonRpcClient(API);
$result = $client->login(['username' => USERNAME, 'password' => PASSWORD]);
$client->setAuthToken($result->token);
$result = $client->{'product.sell'}(['id' => 1, 'price' => 100]);
class SimpleJsonRpcClient
{
private $id;
protected $endpoint;
private $authToken;
public function __construct($endpointUrl) {
$this->endpoint = $endpointUrl;
$this->id = 0;
}
public function setAuthToken($authToken)
{
$this->authToken = $authToken;
}
protected function _requestFactory($method, $args) {
$request = new stdClass;
$request->jsonrpc = '2.0';
$request->method = $method;
$request->params = $args;
$request->id = $this->id++;
return json_encode($request);
}
protected function _curlFactory($data) {
$options = array(
CURLOPT_FRESH_CONNECT => false,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data,
);
if ($this->authToken) {
$options[CURLOPT_HTTPHEADER] = ['X-Auth-Token: '.$this->authToken];
}
$curl = curl_init($this->endpoint);
curl_setopt_array($curl, $options);
return $curl;
}
public function __call($method, $args) {
$request = $this->_requestFactory($method, (object) $args[0]);
$curl = $this->_curlFactory(json_encode($request));
$raw = curl_exec($curl);
$return = json_decode($raw);
curl_close($curl);
if(isset($return->error)) {
throw new Exception($return->error->message, $return->error->code);
}
return $return->result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment