1
|
|
|
<?php |
2
|
|
|
namespace Yabacon\Paystack; |
3
|
|
|
|
4
|
|
|
use Yabacon\Paystack\Http\Request; |
5
|
|
|
|
6
|
|
|
class Event |
7
|
|
|
{ |
8
|
|
|
public $raw = ''; |
9
|
|
|
protected $signature = ''; |
10
|
|
|
public $obj; |
11
|
|
|
const SIGNATURE_KEY = 'HTTP_X_PAYSTACK_SIGNATURE'; |
12
|
|
|
|
13
|
6 |
|
protected function __construct() |
14
|
|
|
{ |
15
|
6 |
|
} |
16
|
|
|
|
17
|
2 |
|
public static function capture() |
|
|
|
|
18
|
1 |
|
{ |
19
|
2 |
|
$evt = new Event(); |
20
|
2 |
|
$evt->raw = @file_get_contents('php://input'); |
21
|
2 |
|
$evt->signature = ( isset($_SERVER[self::SIGNATURE_KEY]) ? $_SERVER[self::SIGNATURE_KEY] : '' ); |
22
|
2 |
|
$evt->loadObject(); |
23
|
2 |
|
return $evt; |
24
|
|
|
} |
25
|
|
|
|
26
|
6 |
|
protected function loadObject() |
27
|
|
|
{ |
28
|
6 |
|
$this->obj = json_decode($this->raw); |
29
|
6 |
|
} |
30
|
|
|
|
31
|
1 |
|
public function discoverOwner(array $keys) |
32
|
|
|
{ |
33
|
1 |
|
if (!$this->obj || !property_exists($this->obj, 'data')) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
1 |
|
foreach ($keys as $index => $key) { |
37
|
1 |
|
if ($this->validFor($key)) { |
38
|
1 |
|
return $index; |
39
|
|
|
} |
40
|
1 |
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
2 |
|
public function validFor($key) |
44
|
|
|
{ |
45
|
2 |
|
if ($this->signature === hash_hmac('sha512', $this->raw, $key)) { |
46
|
2 |
|
return true; |
47
|
|
|
} |
48
|
1 |
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
public function package() |
52
|
|
|
{ |
53
|
3 |
|
$pack = new Request(); |
54
|
3 |
|
$pack->method = "POST"; |
55
|
3 |
|
$pack->headers = [ |
56
|
3 |
|
"X-Paystack-Signature: ". $this->signature, |
57
|
3 |
|
"Content-Type: application/json", |
58
|
|
|
]; |
59
|
3 |
|
$pack->body = $this->raw; |
60
|
3 |
|
return $pack; |
61
|
|
|
} |
62
|
|
|
|
63
|
2 |
|
public function forwardTo($url) |
64
|
|
|
{ |
65
|
2 |
|
if (!filter_var($url, FILTER_VALIDATE_URL)) { |
66
|
1 |
|
return false; |
67
|
|
|
} |
68
|
1 |
|
$packed = $this->package(); |
69
|
1 |
|
$packed->endpoint = $url; |
70
|
1 |
|
return $packed->send()->wrapUp(); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: