1
0
Fork 0
payeer-test-api-lib/lib/Adapter.php
2022-06-14 14:37:09 +07:00

153 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace Payeer;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;
use GuzzleHttp\Psr7\Utils;
class Adapter
{
private array $arParams = array();
private array $arError = array();
public function __construct(array $params = array())
{
$this->arParams = $params;
if (!isset($params['key']) || !is_string($params['key'])) {
throw new \Exception('Payeer API key is required.');
}
}
protected function request(array $req = array())
{
$client = HttpClientDiscovery::find();
$messageFactory = Psr17FactoryDiscovery::findRequestFactory();
$msec = round(microtime(true) * 1000);
$req['post']['ts'] = $msec;
$post = json_encode($req['post']);
$sign = hash_hmac('sha256', $req['method'] . $post, $this->arParams['key']);
$request = $messageFactory->createRequest('POST', 'https://payeer.com/api/trade/' . $req['method'])
->withHeader('Content-Type', 'application/json')
->withHeader('API-ID', $this->arParams['id'])
->withHeader('API-SIGN', $sign)
->withBody(Utils::streamFor($post));
$response = $client->sendRequest($request);
if ($response->getStatusCode() !== 200) {
throw new \Exception('Server returned ' . $response->getStatusCode() . ':' . $response->getReasonPhrase());
}
$arResponse = json_decode((string) $response->getBody(), true);
if ($arResponse['success'] !== true) {
$this->arError = $arResponse['error'];
throw new \Exception($arResponse['error']['code']);
}
return $arResponse;
}
public function getError(): array
{
return $this->arError;
}
/**
* @param string $pair
* @return array Return values
**/
public function orders($pair = 'BTC_USDT')
{
$res = $this->Request(
array(
'method' => 'orders',
'post' => array(
'pair' => $pair,
),
)
);
return $res['pairs'];
}
/**
* @return array Return values
**/
public function account()
{
$res = $this->Request(
array(
'method' => 'account',
)
);
return $res['balances'];
}
public function orderCreate($req = array())
{
return $this->order_create($req);
}
/**
* @param array $req POST parameters.
* @return array Return values
**/
public function orderStatus($req = array())
{
$res = $this->Request(
array(
'method' => 'order_status',
'post' => $req,
)
);
return $res['order'];
}
/**
* @param array $req POST parameters.
* @return array Return values
**/
public function myOrders($req = array()): array
{
$res = $this->Request(
array(
'method' => 'my_orders',
'post' => $req,
)
);
return $res['items'];
}
/**
* Catch-all magic method
*
* @param string $name
* @param array<string, mixed> $arguments
*/
public function __call(string $name, array $arguments): mixed
{
$res = $this->Request(
array(
'method' => strtolower($name),
'post' => $arguments,
)
);
return $res;
}
}