|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Carpenstar\ByBitAPI\Core\Request; |
|
4
|
|
|
|
|
5
|
|
|
use Carpenstar\ByBitAPI\Core\Auth\Credentials; |
|
6
|
|
|
use Carpenstar\ByBitAPI\Core\Auth\SignGenerator; |
|
7
|
|
|
|
|
8
|
|
|
class Curl |
|
9
|
|
|
{ |
|
10
|
|
|
protected bool $isNeedAuthorization; |
|
11
|
|
|
protected Credentials $credentials; |
|
12
|
|
|
private array $curlHeaders = []; |
|
13
|
|
|
private array $curlOptions = []; |
|
14
|
|
|
|
|
15
|
|
|
|
|
16
|
|
|
public function init(bool $isNeedAuthorization, Credentials $credentials): self |
|
17
|
|
|
{ |
|
18
|
|
|
$this->isNeedAuthorization = $isNeedAuthorization; |
|
19
|
|
|
$this->credentials = $credentials; |
|
20
|
|
|
|
|
21
|
|
|
$this->addCurlOpt(CURLOPT_RETURNTRANSFER, true); |
|
22
|
|
|
$this->addCurlHeader('Content-Type', 'application/json'); |
|
23
|
|
|
|
|
24
|
|
|
return $this; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param int $option |
|
29
|
|
|
* @param $value |
|
30
|
|
|
* @return $this |
|
31
|
|
|
*/ |
|
32
|
|
|
protected function addCurlOpt(int $option, $value): self |
|
33
|
|
|
{ |
|
34
|
|
|
$this->curlOptions[$option] = $value; |
|
35
|
|
|
return $this; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @param string $header |
|
40
|
|
|
* @param string $value |
|
41
|
|
|
* @return $this |
|
42
|
|
|
*/ |
|
43
|
|
|
protected function addCurlHeader(string $header, string $value): self |
|
44
|
|
|
{ |
|
45
|
|
|
$this->curlHeaders[$header] = "$header: $value"; |
|
46
|
|
|
return $this; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
protected function query(): array |
|
50
|
|
|
{ |
|
51
|
|
|
$curl = curl_init(); |
|
52
|
|
|
|
|
53
|
|
|
$this->addCurlOpt(CURLOPT_HTTPHEADER, $this->curlHeaders); |
|
54
|
|
|
|
|
55
|
|
|
array_walk($this->curlOptions, function ($value, $option, $curl) { |
|
56
|
|
|
curl_setopt($curl, $option, $value); |
|
57
|
|
|
}, $curl); |
|
58
|
|
|
|
|
59
|
|
|
$response = json_decode(curl_exec($curl), true); |
|
|
|
|
|
|
60
|
|
|
|
|
61
|
|
|
curl_close($curl); |
|
62
|
|
|
|
|
63
|
|
|
return $response; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Создание заголовков авторизации для приватных эндпоинтов |
|
68
|
|
|
* @param string $queryString |
|
69
|
|
|
* @return void |
|
70
|
|
|
*/ |
|
71
|
|
|
protected function auth(string $queryString): void |
|
72
|
|
|
{ |
|
73
|
|
|
if ($this->isNeedAuthorization) { |
|
74
|
|
|
$timestamp = time() * 1000; |
|
75
|
|
|
$sign = SignGenerator::make($this->credentials, $queryString, $timestamp, 5000); |
|
76
|
|
|
$this->addCurlHeader('X-BAPI-API-KEY', $this->credentials->getApiKey()); |
|
77
|
|
|
$this->addCurlHeader('X-BAPI-SIGN', $sign); |
|
78
|
|
|
$this->addCurlHeader('X-BAPI-SIGN-TYPE', 2); |
|
79
|
|
|
$this->addCurlHeader('X-BAPI-TIMESTAMP', $timestamp); |
|
80
|
|
|
$this->addCurlHeader('X-BAPI-RECV-WINDOW', 5000); |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
} |
|
85
|
|
|
|