1 | <?php |
||
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 | /** |
||
22 | * Authentication constructor. |
||
23 | * @param string $key |
||
24 | * @param string $secret |
||
25 | * @param string $subaccountId |
||
26 | */ |
||
27 | 20 | public function __construct(string $key, string $secret, ?string $subaccountId = null) |
|
33 | |||
34 | /** |
||
35 | * @param callable $next |
||
36 | * @return Closure |
||
37 | */ |
||
38 | 18 | public function __invoke(callable $next) |
|
39 | { |
||
40 | 18 | return function (RequestInterface $request, array $options = []) use ($next) { |
|
41 | 18 | $timestamp = round(microtime(true) * 1000); |
|
42 | 18 | $contentHash = $this->generateContentHash($request->getBody()->__toString()); |
|
43 | $pre_sign = $timestamp . |
||
44 | 18 | $request->getUri()->__toString() . |
|
45 | 18 | $request->getMethod() . |
|
46 | 18 | $contentHash . |
|
47 | 18 | $this->subaccountId; |
|
48 | 18 | $sign = $this->generateSign($pre_sign); |
|
49 | $newHeaders = [ |
||
50 | 18 | 'Api-Key' => $this->key, |
|
51 | 18 | 'Api-Timestamp' => $timestamp, |
|
52 | 18 | 'Api-Content-Hash' => $contentHash, |
|
53 | 18 | 'Api-Signature' => $sign |
|
54 | ]; |
||
55 | 18 | foreach ($newHeaders as $key => $value) $request = $request->withAddedHeader($key, $value); |
|
56 | 18 | if (!is_null($this->subaccountId)) $request = $request->withAddedHeader('Api-Subaccount-Id', $this->subaccountId); |
|
57 | |||
58 | 18 | return $next($request, $options); |
|
59 | 18 | }; |
|
60 | } |
||
61 | |||
62 | /** |
||
63 | * @param string $content |
||
64 | * @return string |
||
65 | */ |
||
66 | 18 | private function generateContentHash(string $content): string |
|
70 | |||
71 | /** |
||
72 | * @param string $preSign |
||
73 | * @return string |
||
74 | */ |
||
75 | 18 | private function generateSign(string $preSign): string |
|
79 | |||
80 | } |