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