1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sausin\Signere; |
4
|
|
|
|
5
|
|
|
use UnexpectedValueException; |
6
|
|
|
use Illuminate\Contracts\Config\Repository as Config; |
7
|
|
|
|
8
|
|
|
class Headers |
9
|
|
|
{ |
10
|
|
|
/** @var \Illuminate\Contracts\Config\Repository */ |
11
|
|
|
protected $config; |
12
|
|
|
|
13
|
|
|
/** valid request types */ |
14
|
|
|
const VALID_REQUESTS = ['GET', 'POST', 'PUT', 'DELETE']; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Instantiate the class. |
18
|
|
|
* |
19
|
|
|
* @param \Illuminate\Contracts\Config\Repository |
20
|
|
|
*/ |
21
|
22 |
|
public function __construct(Config $config) |
22
|
|
|
{ |
23
|
22 |
|
$this->config = $config; |
24
|
22 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Make headers for a request. |
28
|
|
|
* |
29
|
|
|
* @param string $reqType |
30
|
|
|
* @param bool|null $needPrimary |
31
|
|
|
* @return array |
32
|
|
|
*/ |
33
|
6 |
|
public function make(string $reqType, string $url, array $body = [], bool $needPrimary = null) |
34
|
|
|
{ |
35
|
|
|
// check if the request type is valid |
36
|
6 |
|
if (! in_array($reqType, self::VALID_REQUESTS)) { |
37
|
|
|
throw new UnexpectedValueException('Incorrect request type '.$reqType); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
// generate timestamp in the correct format |
41
|
6 |
|
$timestamp = explode('+', gmdate('c'))[0]; |
42
|
|
|
// get the algorithm |
43
|
6 |
|
$algorithm = $this->config->get('signere.hash_algorithm'); |
44
|
|
|
|
45
|
|
|
// get the primary / secondary key |
46
|
6 |
|
$key = $needPrimary ? |
47
|
1 |
|
$this->config->get('signere.primary_key') : |
48
|
6 |
|
$this->config->get('signere.secondary_key'); |
49
|
|
|
|
50
|
|
|
// set the basic headers |
51
|
|
|
$headers = [ |
52
|
6 |
|
'API-ID' => $this->config->get('signere.id'), |
53
|
6 |
|
'API-TIMESTAMP' => $timestamp, |
54
|
6 |
|
'API-USINGSECONDARYTOKEN' => is_null($needPrimary) ? 'TRUE' : ! $needPrimary, |
55
|
6 |
|
'API-ALGORITHM' => strtoupper($algorithm), |
56
|
6 |
|
'API-RETURNERRORHEADER' => 'TRUE', |
57
|
|
|
]; |
58
|
|
|
|
59
|
|
|
// make request type specific headers |
60
|
6 |
|
if ($reqType === 'GET' || $reqType === 'DELETE') { |
61
|
3 |
|
$toEncode = sprintf('%s&Timestamp=%s&Httpverb=%s', $url, $timestamp, $reqType); |
62
|
|
|
|
63
|
3 |
|
$headers['API-TOKEN'] = strtoupper(hash_hmac($algorithm, $toEncode, $key)); |
64
|
|
|
|
65
|
3 |
|
return $headers; |
66
|
|
|
} |
67
|
|
|
|
68
|
3 |
|
$toEncode = sprintf('%s{Timestamp:"%s",Httpverb:"%s"}', json_encode($body), $timestamp, $reqType); |
69
|
|
|
|
70
|
3 |
|
$headers['API-TOKEN'] = strtoupper(hash_hmac($algorithm, $toEncode, $key)); |
71
|
|
|
|
72
|
3 |
|
return $headers; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|