1 | <?php |
||
16 | class Authenticator |
||
17 | { |
||
18 | |||
19 | /** |
||
20 | * @var string |
||
21 | */ |
||
22 | protected $endpoint; |
||
23 | /** |
||
24 | * @var Core |
||
25 | */ |
||
26 | protected $engine; |
||
27 | /** |
||
28 | * @var Authenticator |
||
29 | */ |
||
30 | protected static $instance; |
||
31 | /** |
||
32 | * @var bool |
||
33 | */ |
||
34 | public $alt = false; |
||
35 | /** |
||
36 | * @var string |
||
37 | */ |
||
38 | private $credentials; |
||
39 | |||
40 | /** |
||
41 | * Authenticator constructor. |
||
42 | * |
||
43 | * @param Core $core |
||
44 | * @throws MpesaException |
||
45 | */ |
||
46 | 2 | public function __construct(Core $core) |
|
52 | |||
53 | /** |
||
54 | * @param bool $bulk |
||
55 | * @return string |
||
56 | * @throws MpesaException |
||
57 | * @throws \GuzzleHttp\Exception\GuzzleException |
||
58 | */ |
||
59 | 1 | public function authenticate($bulk = false): ?string |
|
60 | { |
||
61 | 1 | if ($bulk) { |
|
62 | $this->alt = true; |
||
63 | } |
||
64 | 1 | $this->generateCredentials(); |
|
65 | 1 | if (config('samerior.mpesa.cache_credentials', false) && !empty($key = $this->getFromCache())) { |
|
66 | return $key; |
||
67 | } |
||
68 | try { |
||
69 | 1 | $response = $this->makeRequest(); |
|
70 | if ($response->getStatusCode() === 200) { |
||
71 | $body = \json_decode($response->getBody()); |
||
72 | $this->saveCredentials($body); |
||
73 | return $body->access_token; |
||
74 | } |
||
75 | throw new MpesaException($response->getReasonPhrase()); |
||
76 | 1 | } catch (RequestException $exception) { |
|
77 | 1 | $message = $exception->getResponse() ? |
|
78 | $exception->getResponse()->getReasonPhrase() : |
||
79 | 1 | $exception->getMessage(); |
|
80 | |||
81 | 1 | throw $this->generateException($message); |
|
82 | } |
||
83 | } |
||
84 | |||
85 | /** |
||
86 | * @param $reason |
||
87 | * @return MpesaException |
||
88 | */ |
||
89 | 1 | private function generateException($reason): ?MpesaException |
|
90 | { |
||
91 | 1 | switch (\strtolower($reason)) { |
|
92 | 1 | case 'bad request: invalid credentials': |
|
93 | return new MpesaException('Invalid consumer key and secret combination'); |
||
94 | default: |
||
95 | 1 | return new MpesaException($reason); |
|
96 | } |
||
97 | } |
||
98 | |||
99 | /** |
||
100 | * @return $this |
||
101 | */ |
||
102 | 1 | private function generateCredentials(): self |
|
114 | |||
115 | /** |
||
116 | * @return ResponseInterface |
||
117 | * @throws \GuzzleHttp\Exception\GuzzleException |
||
118 | */ |
||
119 | 1 | private function makeRequest(): ResponseInterface |
|
132 | |||
133 | /** |
||
134 | * @return mixed |
||
135 | */ |
||
136 | 1 | private function getFromCache() |
|
140 | |||
141 | /** |
||
142 | * Store the credentials in the cache. |
||
143 | * |
||
144 | * @param $credentials |
||
145 | */ |
||
146 | private function saveCredentials($credentials) |
||
150 | } |
||
151 |