1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace R3bers\BittrexApi\Middleware; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use Psr\Http\Message\RequestInterface; |
9
|
|
|
|
10
|
|
|
class Authentication |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
private $key; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
private $secret; |
17
|
|
|
|
18
|
|
|
/** @var string */ |
19
|
|
|
private $subaccountId; |
20
|
|
|
|
21
|
|
|
/** @var string */ |
22
|
|
|
private $baseUri; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Authentication constructor. |
26
|
|
|
* @param string $key |
27
|
|
|
* @param string $secret |
28
|
|
|
* @param string $baseUri |
29
|
|
|
* @param string $subaccountId |
30
|
|
|
*/ |
31
|
17 |
|
public function __construct(string $key, string $secret, string $baseUri, string $subaccountId = '') |
32
|
|
|
{ |
33
|
17 |
|
$this->key = $key; |
34
|
17 |
|
$this->secret = $secret; |
35
|
17 |
|
$this->subaccountId = $subaccountId; |
36
|
17 |
|
$this->baseUri = $baseUri; |
37
|
17 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param callable $next |
41
|
|
|
* @return Closure |
42
|
|
|
*/ |
43
|
15 |
|
public function __invoke(callable $next) |
44
|
|
|
{ |
45
|
|
|
return function (RequestInterface $request, array $options = []) use ($next) { |
46
|
15 |
|
$timestamp = round(microtime(true) * 1000); |
47
|
15 |
|
$contentHash = $this->generateContentHash($request->getBody()->__toString()); |
48
|
|
|
$pre_sign = $timestamp . |
49
|
15 |
|
$this->baseUri . |
50
|
15 |
|
$request->getUri()->__toString() . |
51
|
15 |
|
$request->getMethod() . |
52
|
15 |
|
$contentHash . |
53
|
15 |
|
$this->subaccountId; |
54
|
15 |
|
$sign = $this->generateSign($pre_sign); |
55
|
15 |
|
$request = $request->withAddedHeader('Api-Key', $this->key); |
56
|
15 |
|
$request = $request->withAddedHeader('Api-Timestamp', $timestamp); |
57
|
15 |
|
$request = $request->withAddedHeader('Api-Content-Hash', $contentHash); |
58
|
15 |
|
$request = $request->withAddedHeader('Api-Signature', $sign); |
59
|
15 |
|
$request = $request->withAddedHeader('Api-Subaccount-Id', $this->subaccountId); |
60
|
|
|
|
61
|
15 |
|
return $next($request, $options); |
62
|
15 |
|
}; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @param string $content |
67
|
|
|
* @return string |
68
|
|
|
*/ |
69
|
15 |
|
private function generateContentHash(string $content): string |
70
|
|
|
{ |
71
|
15 |
|
return hash('sha512', $content); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
/** |
75
|
|
|
* @param string $preSign |
76
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
15 |
|
private function generateSign(string $preSign): string |
79
|
|
|
{ |
80
|
15 |
|
return hash_hmac('sha512', $preSign, $this->secret); |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
|
84
|
|
|
} |
85
|
|
|
|