1
|
|
|
<?php |
2
|
|
|
namespace mikemix\Wiziq\API; |
3
|
|
|
|
4
|
|
|
class Auth |
5
|
|
|
{ |
6
|
|
|
/** @var string */ |
7
|
|
|
protected $secretAcessKey; |
8
|
|
|
|
9
|
|
|
/** @var string */ |
10
|
|
|
protected $accessKey; |
11
|
|
|
|
12
|
|
|
/** @var int */ |
13
|
|
|
protected $currentTime; |
14
|
|
|
|
15
|
3 |
|
public function __construct($secretAcessKey, $accessKey) |
16
|
|
|
{ |
17
|
3 |
|
$this->secretAcessKey = $secretAcessKey; |
18
|
3 |
|
$this->accessKey = $accessKey; |
19
|
3 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @param string $methodName Method name |
23
|
|
|
* @param array $data Method payload |
24
|
|
|
* @return array Send ready request payload |
25
|
|
|
*/ |
26
|
3 |
|
public function preparePayload($methodName, array $data) |
27
|
|
|
{ |
28
|
3 |
|
$params = []; |
29
|
3 |
|
$params['access_key'] = $this->accessKey; |
30
|
3 |
|
$params['timestamp'] = $this->getCurrentTime(); |
31
|
3 |
|
$params['method'] = $methodName; |
32
|
|
|
|
33
|
3 |
|
$hmacsha = $this->hmacsha1(urldecode(http_build_query($params, '', '&'))); |
34
|
|
|
|
35
|
3 |
|
return array_merge( |
36
|
3 |
|
$params, |
37
|
3 |
|
['signature' => base64_encode($hmacsha)], |
38
|
3 |
|
$this->prepareValues($data) |
39
|
3 |
|
); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param array $data |
44
|
|
|
* @return array |
45
|
|
|
*/ |
46
|
3 |
|
protected function prepareValues(array $data) |
47
|
|
|
{ |
48
|
3 |
|
foreach ($data as $key => $val) { |
49
|
3 |
|
if (is_bool($data[$key])) { |
50
|
1 |
|
$data[$key] = (int)$val; |
51
|
3 |
|
} elseif (null === $val) { |
52
|
1 |
|
$data[$key] = ''; |
53
|
1 |
|
} |
54
|
3 |
|
} |
55
|
|
|
|
56
|
3 |
|
return $data; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Based on code from api.wiziq.com |
61
|
|
|
* |
62
|
|
|
* @param string $data |
63
|
|
|
* @param int $blocksize |
64
|
|
|
* @return string |
65
|
|
|
*/ |
66
|
3 |
|
protected function hmacsha1($data, $blocksize = 64) |
67
|
|
|
{ |
68
|
3 |
|
$key = urlencode($this->secretAcessKey); |
69
|
|
|
|
70
|
3 |
|
if (strlen($key) > $blocksize) { |
71
|
|
|
$key = pack('H*', sha1($key)); |
72
|
|
|
} |
73
|
|
|
|
74
|
3 |
|
$key = str_pad($key, $blocksize, chr(0x00)); |
75
|
3 |
|
$ipad = str_repeat(chr(0x36), $blocksize); |
76
|
3 |
|
$opad = str_repeat(chr(0x5c), $blocksize); |
77
|
3 |
|
return pack('H*', sha1(($key^$opad).pack('H*', sha1(($key^$ipad).$data)))); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @return int |
82
|
|
|
*/ |
83
|
3 |
|
protected function getCurrentTime() |
84
|
|
|
{ |
85
|
3 |
|
if (!$this->currentTime) { |
86
|
|
|
$this->currentTime = time(); |
87
|
|
|
} |
88
|
|
|
|
89
|
3 |
|
return $this->currentTime; |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* @param int $time |
94
|
|
|
* @internal For tests only |
95
|
|
|
*/ |
96
|
3 |
|
public function setCurrentTime($time) |
97
|
|
|
{ |
98
|
3 |
|
$this->currentTime = $time; |
99
|
3 |
|
} |
100
|
|
|
} |
101
|
|
|
|