1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Payment247\SDK; |
4
|
|
|
|
5
|
|
|
class Signer |
6
|
|
|
{ |
7
|
|
|
protected $publicKey; |
8
|
|
|
protected $privateKey; |
9
|
|
|
|
10
|
4 |
|
public function __construct($publicKey, $privateKey) |
11
|
|
|
{ |
12
|
4 |
|
$this->publicKey = $publicKey; |
13
|
4 |
|
$this->privateKey = $privateKey; |
14
|
4 |
|
} |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param array $data |
18
|
|
|
* |
19
|
|
|
* @return array |
20
|
|
|
*/ |
21
|
1 |
|
public function sign(array $data) |
22
|
|
|
{ |
23
|
1 |
|
$data = array_merge($data, ['public_key' => $this->publicKey]); |
24
|
|
|
|
25
|
1 |
|
$signature = $this->getSignature($data); |
26
|
|
|
|
27
|
1 |
|
$data = array_merge($data, ['sign' => $signature]); |
28
|
|
|
|
29
|
1 |
|
return $data; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param array $data |
34
|
|
|
* |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
2 |
|
protected function getSignature(array $data) |
38
|
|
|
{ |
39
|
2 |
|
$baseString = json_encode($data).$this->privateKey; |
40
|
|
|
|
41
|
2 |
|
return hash('sha256', $baseString); |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* @param array $data |
46
|
|
|
* |
47
|
|
|
* @return string |
48
|
|
|
* @deprecated |
49
|
|
|
*/ |
50
|
|
|
protected function getSignatureOld(array $data) |
51
|
|
|
{ |
52
|
|
|
$baseString = $this->concatenateParams($data) . $this->privateKey; |
53
|
|
|
|
54
|
|
|
return hash('sha256', $baseString); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param array $data |
59
|
|
|
* |
60
|
|
|
* @return bool |
61
|
|
|
*/ |
62
|
1 |
|
public function checkSignature(array $data) |
63
|
|
|
{ |
64
|
1 |
|
$signature = $data['sign']; |
65
|
1 |
|
unset($data['sign']); |
66
|
|
|
|
67
|
1 |
|
return $this->getSignature($data) === $signature || |
68
|
1 |
|
$this->getSignatureOld($data) === $signature; |
|
|
|
|
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param array $data |
73
|
|
|
* @param string $arrayKey |
74
|
|
|
* @return string |
75
|
|
|
*/ |
76
|
|
|
protected function concatenateParams(array $data = [], $arrayKey = '') |
77
|
|
|
{ |
78
|
|
|
ksort($data); |
79
|
|
|
|
80
|
|
|
$string = ''; |
81
|
|
|
|
82
|
|
|
foreach ($data as $key => $value) { |
83
|
|
|
$generatedArrayKey = empty($arrayKey) ? $key : ($arrayKey . '[' . $key . ']'); |
84
|
|
|
if (is_array($value)) { |
85
|
|
|
$string .= $this->concatenateParams($value, $generatedArrayKey); |
86
|
|
|
} else { |
87
|
|
|
$string .= $generatedArrayKey . '=' . $value; |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $string; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|
This method has been deprecated.