Collection::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 13
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 18
ccs 14
cts 14
cp 1
crap 1
rs 9.8333
1
<?php
2
3
/**
4
 * Collection.
5
 */
6
7
namespace Bmatovu\MtnMomo\Products;
8
9
use Bmatovu\MtnMomo\Exceptions\CollectionRequestException;
10
use GuzzleHttp\ClientInterface;
11
use GuzzleHttp\Exception\RequestException;
12
use Illuminate\Container\Container;
13
use Illuminate\Contracts\Config\Repository;
14
use Ramsey\Uuid\Uuid;
15
16
/**
17
 * Collection service/product.
18
 */
19
class Collection extends Product
20
{
21
    /**
22
     * Product.
23
     *
24
     * @var string
25
     */
26
    const PRODUCT = 'collection';
27
28
    /**
29
     * Transact URI.
30
     *
31
     * @var string
32
     */
33
    protected $transactionUri;
34
35
    /**
36
     * Transaction status URI.
37
     *
38
     * @var string
39
     */
40
    protected $transactionStatusUri;
41
42
    /**
43
     * Account status URI.
44
     *
45
     * @var string
46
     */
47
    protected $accountStatusUri;
48
49
    /**
50
     * Account balance URI.
51
     *
52
     * @var string
53
     */
54
    protected $accountBalanceUri;
55
56
    /**
57
     * Account holder basic info URI.
58
     *
59
     * @var string
60
     */
61
    protected $accountHolderInfoUri;
62
63
    /**
64
     * @return string
65
     */
66
    public function getTransactionUri()
67
    {
68
        return $this->transactionUri;
69
    }
70
71
    /**
72
     * @param string $transactionUri
73
     */
74
    public function setTransactionUri($transactionUri)
75
    {
76
        $this->transactionUri = $transactionUri;
77
    }
78
79
    /**
80
     * @return string
81
     */
82
    public function getTransactionStatusUri()
83
    {
84
        return $this->transactionStatusUri;
85
    }
86
87
    /**
88
     * @param string $transactionStatusUri
89
     */
90
    public function setTransactionStatusUri($transactionStatusUri)
91
    {
92
        $this->transactionStatusUri = $transactionStatusUri;
93
    }
94
95
    /**
96
     * @return string
97
     */
98
    public function getAccountStatusUri()
99
    {
100
        return $this->accountStatusUri;
101
    }
102
103
    /**
104
     * @param string $accountStatusUri
105
     */
106
    public function setAccountStatusUri($accountStatusUri)
107
    {
108
        $this->accountStatusUri = $accountStatusUri;
109
    }
110
111
    /**
112
     * @return string
113
     */
114
    public function getAppAccountBalanceUri()
115
    {
116
        return $this->accountBalanceUri;
117
    }
118
119
    /**
120
     * @param string $accountBalanceUri
121
     */
122
    public function setAppAccountBalanceUri($accountBalanceUri)
123
    {
124
        $this->accountBalanceUri = $accountBalanceUri;
125
    }
126
127
    /**
128
     * @return string
129
     */
130
    public function getAccountHolderInfoUri()
131
    {
132
        return $this->accountHolderInfoUri;
133
    }
134
135
    /**
136
     * @param string $accountHolderInfoUri
137
     */
138
    public function setAccountHolderInfoUri($accountHolderInfoUri)
139
    {
140
        $this->accountHolderInfoUri = $accountHolderInfoUri;
141
    }
142
143
    /**
144
     * Constructor.
145
     *
146
     * @param array $headers
147
     * @param array $middleware
148
     * @param \GuzzleHttp\ClientInterface $client
149
     *
150
     * @uses \Illuminate\Contracts\Config\Repository
151
     *
152
     * @throws \Exception
153
     */
154 9
    public function __construct($headers = [], $middleware = [], ClientInterface $client = null)
155
    {
156 9
        $config = Container::getInstance()->make(Repository::class);
157
158 9
        $this->subscriptionKey = $config->get('mtn-momo.products.collection.key');
159 9
        $this->clientId = $config->get('mtn-momo.products.collection.id');
160 9
        $this->clientSecret = $config->get('mtn-momo.products.collection.secret');
161 9
        $this->clientCallbackUri = $config->get('mtn-momo.products.collection.callback_uri');
162
163 9
        $this->tokenUri = $config->get('mtn-momo.products.collection.token_uri');
164 9
        $this->transactionUri = $config->get('mtn-momo.products.collection.transaction_uri');
165 9
        $this->transactionStatusUri = $config->get('mtn-momo.products.collection.transaction_status_uri');
166 9
        $this->accountStatusUri = $config->get('mtn-momo.products.collection.account_status_uri');
167 9
        $this->accountBalanceUri = $config->get('mtn-momo.products.collection.account_balance_uri');
168 9
        $this->accountHolderInfoUri = $config->get('mtn-momo.products.collection.account_holder_info_uri');
169 9
        $this->partyIdType = $config->get('mtn-momo.products.collection.party_id_type');
170
171 9
        parent::__construct($headers, $middleware, $client);
172
    }
173
174
    /**
175
     * Request payee to pay.
176
     *
177
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/requesttopay-POST Documentation
178
     *
179
     * @param  string $transactionId Your transaction reference ID, Say: order number.
180
     * @param  string $partyId Account holder. Usually phone number if type is MSISDN.
181
     * @param  int $amount How much to debit the payer.
182
     * @param  string $payerMessage Payer transaction history message.
183
     * @param  string $payeeNote Payee transaction history message.
184
     *
185
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
186
     * @throws \GuzzleHttp\Exception\GuzzleException
187
     * @throws \Exception
188
     *
189
     * @return string                Auto generated payment reference. Format: UUID
190
     */
191 3
    public function requestToPay($transactionId, $partyId, $amount, $payerMessage = '', $payeeNote = '')
192
    {
193 3
        $momoTransactionId = Uuid::uuid4()->toString();
194
195 3
        $headers = [
196 3
            'X-Reference-Id' => $momoTransactionId,
197 3
            'X-Target-Environment' => $this->environment,
198 3
            'X-Callback-Url' => $this->clientCallbackUri,
199 3
        ];
200
201
        try {
202 3
            $this->client->request('POST', $this->transactionUri, [
203 3
                'headers' => $headers,
204 3
                'json' => [
205 3
                    'amount' => $amount,
206 3
                    'currency' => $this->currency,
207 3
                    'externalId' => $transactionId,
208 3
                    'payer' => [
209 3
                        'partyIdType' => $this->partyIdType,
210 3
                        'partyId' => $partyId,
211 3
                    ],
212 3
                    'payerMessage' => alphanumeric($payerMessage),
213 3
                    'payeeNote' => alphanumeric($payeeNote),
214 3
                ],
215 3
            ]);
216
217 1
            return $momoTransactionId;
218 2
        } catch (RequestException $ex) {
219 2
            throw new CollectionRequestException('Request to pay transaction - unsuccessful.', 0, $ex);
220
        }
221
    }
222
223
    /**
224
     * Get transaction status.
225
     *
226
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/requesttopay-referenceId-GET Documentation
227
     *
228
     * @param  string $momoTransactionId MTN Momo transaction ID. Returned from transact (requestToPay)
229
     *
230
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
231
     * @throws \GuzzleHttp\Exception\GuzzleException
232
     *
233
     * @return array
234
     */
235 1
    public function getTransactionStatus($momoTransactionId)
236
    {
237 1
        $transactionStatusUri = str_replace('{momoTransactionId}', $momoTransactionId, $this->transactionStatusUri);
238
239
        try {
240 1
            $response = $this->client->request('GET', $transactionStatusUri, [
241 1
                'headers' => [
242 1
                    'X-Target-Environment' => $this->environment,
243 1
                ],
244 1
            ]);
245
246 1
            return json_decode($response->getBody(), true);
247
        } catch (RequestException $ex) {
248
            throw new CollectionRequestException('Unable to get transaction status.', 0, $ex);
249
        }
250
    }
251
252
    /**
253
     * Request collections access token.
254
     *
255
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/token-POST Documentation
256
     *
257
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
258
     * @throws \GuzzleHttp\Exception\GuzzleException
259
     *
260
     * @return array
261
     */
262 1
    public function getToken()
263
    {
264
        try {
265 1
            $response = $this->client->request('POST', $this->tokenUri, [
266 1
                'headers' => [
267 1
                    'Authorization' => 'Basic '.base64_encode($this->clientId.':'.$this->clientSecret),
268 1
                ],
269 1
                'json' => [
270 1
                    'grant_type' => 'client_credentials',
271 1
                ],
272 1
            ]);
273
274 1
            return json_decode($response->getBody(), true);
275
        } catch (RequestException $ex) {
276
            throw new CollectionRequestException('Unable to get token.', 0, $ex);
277
        }
278
    }
279
280
    /**
281
     * Get account balance.
282
     *
283
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/get-v1_0-account-balance Documentation
284
     *
285
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
286
     * @throws \GuzzleHttp\Exception\GuzzleException
287
     *
288
     * @return array Account balance.
289
     */
290 1
    public function getAccountBalance()
291
    {
292
        try {
293 1
            $response = $this->client->request('GET', $this->accountBalanceUri, [
294 1
                'headers' => [
295 1
                    'X-Target-Environment' => $this->environment,
296 1
                ],
297 1
            ]);
298
299 1
            return json_decode($response->getBody(), true);
300
        } catch (RequestException $ex) {
301
            throw new CollectionRequestException('Unable to get account balance.', 0, $ex);
302
        }
303
    }
304
305
    /**
306
     * Determine if an account holder is registered and active.
307
     *
308
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/get-v1_0-accountholder-accountholderidtype-accountholderid-active Documentation
309
     *
310
     * @param  string $partyId Party number - MSISDN, email, or code - UUID.
311
     * @param  string $partyIdType Allowed values [msisdn, email, party_code].
312
     *
313
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
314
     * @throws \GuzzleHttp\Exception\GuzzleException
315
     *
316
     * @return bool True if account holder is registered and active, false if the account holder is not active or not found
317
     */
318 1
    public function isActive($partyId, $partyIdType = null)
319
    {
320 1
        if (is_null($partyIdType)) {
321 1
            $partyIdType = $this->partyIdType;
322
        }
323
324 1
        $patterns = $replacements = [];
325
326 1
        $patterns[] = '/(\{\bpartyIdType\b\})/';
327 1
        $replacements[] = strtolower($partyIdType);
328
329 1
        $patterns[] = '/(\{\bpartyId\b\})/';
330 1
        $replacements[] = urlencode($partyId);
331
332 1
        $accountStatusUri = preg_replace($patterns, $replacements, $this->accountStatusUri);
333
334
        try {
335 1
            $response = $this->client->request('GET', $accountStatusUri, [
336 1
                'headers' => [
337 1
                    'X-Target-Environment' => $this->environment,
338 1
                ],
339 1
            ]);
340
341 1
            $body = json_decode($response->getBody(), true);
342
343 1
            return (bool) $body['result'];
344
        } catch (RequestException $ex) {
345
            throw new CollectionRequestException('Unable to get user account information.', 0, $ex);
346
        }
347
    }
348
349
    /**
350
     * Get basic info of an account holder.
351
     *
352
     * @see https://momodeveloper.mtn.com/docs/services/collection/operations/basicuserInfo-GET Documentation
353
     *
354
     * @param  string $partyId Party number - MSISDN.
355
     *
356
     * @throws \Bmatovu\MtnMomo\Exceptions\CollectionRequestException
357
     * @throws \GuzzleHttp\Exception\GuzzleException
358
     *
359
     * @return array account basic info
360
     */
361 1
    public function getAccountHolderBasicInfo($partyId)
362
    {
363 1
        $patterns = $replacements = [];
364
365 1
        $patterns[] = '/(\{\bpartyId\b\})/';
366 1
        $replacements[] = urlencode($partyId);
367
368 1
        $accountHolderInfoUri = preg_replace($patterns, $replacements, $this->accountHolderInfoUri);
369
370
        try {
371 1
            $response = $this->client->request('GET', $accountHolderInfoUri, [
372 1
                'headers' => [
373 1
                    'X-Target-Environment' => $this->environment,
374 1
                ],
375 1
            ]);
376
377 1
            return json_decode($response->getBody(), true);
378
        } catch (RequestException $ex) {
379
            throw new CollectionRequestException('Unable to get user account information.', 0, $ex);
380
        }
381
    }
382
}
383