Completed
Push — master ( 22ee16...2aebd9 )
by PROSPER
13s
created

Paystack::listSubAccounts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Laravel Paystack package.
5
 *
6
 * (c) Prosper Otemuyiwa <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Unicodeveloper\Paystack;
13
14
use GuzzleHttp\Client;
15
use Illuminate\Support\Facades\Config;
16
use Unicodeveloper\Paystack\Exceptions\IsNullException;
17
use Unicodeveloper\Paystack\Exceptions\PaymentVerificationFailedException;
18
19
class Paystack
20
{
21
    /**
22
     * Transaction Verification Successful
23
     */
24
    const VS = 'Verification successful';
25
26
    /**
27
     *  Invalid Transaction reference
28
     */
29
    const ITF = "Invalid transaction reference";
30
31
    /**
32
     * Issue Secret Key from your Paystack Dashboard
33
     * @var string
34
     */
35
    protected $secretKey;
36
37
    /**
38
     * Instance of Client
39
     * @var Client
40
     */
41
    protected $client;
42
43
    /**
44
     *  Response from requests made to Paystack
45
     * @var mixed
46
     */
47
    protected $response;
48
49
    /**
50
     * Paystack API base Url
51
     * @var string
52
     */
53
    protected $baseUrl;
54
55
    /**
56
     * Authorization Url - Paystack payment page
57
     * @var string
58
     */
59
    protected $authorizationUrl;
60
61
    public function __construct()
62
    {
63
        $this->setKey();
64
        $this->setBaseUrl();
65
        $this->setRequestOptions();
66
    }
67
68
    /**
69
     * Get Base Url from Paystack config file
70
     */
71
    public function setBaseUrl()
72
    {
73
        $this->baseUrl = Config::get('paystack.paymentUrl');
74
    }
75
76
    /**
77
     * Get secret key from Paystack config file
78
     */
79
    public function setKey()
80
    {
81
        $this->secretKey = Config::get('paystack.secretKey');
82
    }
83
84
    /**
85
     * Set options for making the Client request
86
     */
87
    private function setRequestOptions()
88
    {
89
        $authBearer = 'Bearer '. $this->secretKey;
90
91
        $this->client = new Client(
92
            [
93
                'base_uri' => $this->baseUrl,
94
                'headers' => [
95
                    'Authorization' => $authBearer,
96
                    'Content-Type'  => 'application/json',
97
                    'Accept'        => 'application/json'
98
                ]
99
            ]
100
        );
101
    }
102
103
   
104
     /**
105
     
106
     * Initiate a payment request to Paystack
107
     * Included the option to pass the payload to this method for situations 
108
     * when the payload is built on the fly (not passed to the controller from a view)
109
     * @return Paystack
110
     */
111
112
    public function makePaymentRequest( $data = null)
113
    {
114
        if ( $data == null ) {
115
            $data = [
116
                "amount" => intval(request()->amount),
117
                "reference" => request()->reference,
118
                "email" => request()->email,
119
                "plan" => request()->plan,
120
                "first_name" => request()->first_name,
121
                "last_name" => request()->last_name,
122
                "callback_url" => request()->callback_url,
123
                /*
124
                * to allow use of metadata on Paystack dashboard and a means to return additional data back to redirect url
125
                * form need an input field: <input type="hidden" name="metadata" value="{{ json_encode($array) }}" >
126
                *array must be set up as: $array = [ 'custom_fields' => [
127
                *                                                            ['display_name' => "Cart Id", "variable_name" => "cart_id", "value" => "2"],
128
                *                                                            ['display_name' => "Sex", "variable_name" => "sex", "value" => "female"],
129
                *                                                            .
130
                *                                                            .
131
                *                                                            .
132
                *                                                        ]
133
                *                                        
134
                *                                  ]
135
                */
136
                'metadata' => request()->metadata
137
            ];
138
139
            // Remove the fields which were not sent (value would be null)
140
            array_filter($data);
141
        }
142
143
        $this->setHttpResponse('/transaction/initialize', 'POST', $data);
144
145
        return $this;
146
    }
147
148
149
    /**
150
     * @param string $relativeUrl
151
     * @param string $method
152
     * @param array $body
153
     * @return Paystack
154
     * @throws IsNullException
155
     */
156
    private function setHttpResponse($relativeUrl, $method, $body = [])
157
    {
158
        if (is_null($method)) {
159
            throw new IsNullException("Empty method not allowed");
160
        }
161
162
        $this->response = $this->client->{strtolower($method)}(
163
            $this->baseUrl . $relativeUrl,
164
            ["body" => json_encode($body)]
165
        );
166
167
        return $this;
168
    }
169
170
    /**
171
     * Get the authorization url from the callback response
172
     * @return Paystack
173
     */
174
    public function getAuthorizationUrl()
175
    {
176
        $this->makePaymentRequest();
177
178
        $this->url = $this->getResponse()['data']['authorization_url'];
0 ignored issues
show
Bug introduced by
The property url does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
179
180
        return $this;
181
    }
182
    
183
     /**
184
     * Get the authorization callback response
185
     * In situations where Laravel serves as an backend for a detached UI, the api cannot redirect 
186
     * and might need to take different actions based on the success or not of the transaction
187
     * @return array
188
     */
189
    public function getAuthorizationResponse($data)
190
    {
191
        $this->makePaymentRequest($data);
192
193
        $this->url = $this->getResponse()['data']['authorization_url'];
194
195
        return $this->getResponse();
196
    }
197
198
    /**
199
     * Hit Paystack Gateway to Verify that the transaction is valid
200
     */
201
    private function verifyTransactionAtGateway()
202
    {
203
        $transactionRef = request()->query('trxref');
204
205
        $relativeUrl = "/transaction/verify/{$transactionRef}";
206
207
        $this->response = $this->client->get($this->baseUrl . $relativeUrl, []);
208
    }
209
210
    /**
211
     * True or false condition whether the transaction is verified
212
     * @return boolean
213
     */
214
    public function isTransactionVerificationValid()
215
    {
216
        $this->verifyTransactionAtGateway();
217
218
        $result = $this->getResponse()['message'];
219
220
        switch ($result) {
221
            case self::VS:
222
                $validate = true;
223
                break;
224
            case self::ITF:
225
                $validate = false;
226
                break;
227
            default:
228
                $validate = false;
229
                break;
230
        }
231
232
        return $validate;
233
    }
234
235
    /**
236
     * Get Payment details if the transaction was verified successfully
237
     * @return json
238
     * @throws PaymentVerificationFailedException
239
     */
240
    public function getPaymentData()
241
    {
242
        if ($this->isTransactionVerificationValid()) {
243
            return $this->getResponse();
244
        } else {
245
            throw new PaymentVerificationFailedException("Invalid Transaction Reference");
246
        }
247
    }
248
249
    /**
250
     * Fluent method to redirect to Paystack Payment Page
251
     */
252
    public function redirectNow()
253
    {
254
        return redirect($this->url);
255
    }
256
257
    /**
258
     * Get Access code from transaction callback respose
259
     * @return string
260
     */
261
    public function getAccessCode()
262
    {
263
        return $this->getResponse()['data']['access_code'];
264
    }
265
266
    /**
267
     * Generate a Unique Transaction Reference
268
     * @return string
269
     */
270
    public function genTranxRef()
271
    {
272
        return TransRef::getHashedToken();
273
    }
274
275
    /**
276
     * Get all the customers that have made transactions on your platform
277
     * @return array
278
     */
279
    public function getAllCustomers()
280
    {
281
        $this->setRequestOptions();
282
283
        return $this->setHttpResponse("/customer", 'GET', [])->getData();
284
    }
285
286
    /**
287
     * Get all the plans that you have on Paystack
288
     * @return array
289
     */
290
    public function getAllPlans()
291
    {
292
        $this->setRequestOptions();
293
294
        return $this->setHttpResponse("/plan", 'GET', [])->getData();
295
    }
296
297
    /**
298
     * Get all the transactions that have happened overtime
299
     * @return array
300
     */
301
    public function getAllTransactions()
302
    {
303
        $this->setRequestOptions();
304
305
        return $this->setHttpResponse("/transaction", 'GET', [])->getData();
306
    }
307
308
    /**
309
     * Get the whole response from a get operation
310
     * @return array
311
     */
312
    private function getResponse()
313
    {
314
        return json_decode($this->response->getBody(), true);
315
    }
316
317
    /**
318
     * Get the data response from a get operation
319
     * @return array
320
     */
321
    private function getData()
322
    {
323
        return $this->getResponse()['data'];
324
    }
325
326
    /**
327
     * Create a plan
328
     */
329 View Code Duplication
    public function createPlan()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
    {
331
        $data = [
332
            "name" => request()->name,
333
            "description" => request()->desc,
334
            "amount" => intval(request()->amount),
335
            "interval" => request()->interval,
336
            "send_invoices" => request()->send_invoices,
337
            "send_sms" => request()->send_sms,
338
            "currency" => request()->currency,
339
        ];
340
341
        $this->setRequestOptions();
342
343
        $this->setHttpResponse("/plan", 'POST', $data);
344
345
    }
346
347
    /**
348
     * Fetch any plan based on its plan id or code
349
     * @param $plan_code
350
     * @return array
351
     */
352
    public function fetchPlan($plan_code)
353
    {
354
        $this->setRequestOptions();
355
        return $this->setHttpResponse('/plan/' . $plan_code, 'GET', [])->getResponse();
356
    }
357
358
    /**
359
     * Update any plan's details based on its id or code
360
     * @param $plan_code
361
     * @return array
362
     */
363 View Code Duplication
    public function updatePlan($plan_code)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
364
    {
365
        $data = [
366
            "name" => request()->name,
367
            "description" => request()->desc,
368
            "amount" => intval(request()->amount),
369
            "interval" => request()->interval,
370
            "send_invoices" => request()->send_invoices,
371
            "send_sms" => request()->send_sms,
372
            "currency" => request()->currency,
373
        ];
374
375
        $this->setRequestOptions();
376
        return $this->setHttpResponse('/plan/' . $plan_code, 'PUT', $data)->getResponse();
377
    }
378
379
    /**
380
     * Create a customer
381
     */
382 View Code Duplication
    public function createCustomer()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
383
    {
384
        $data = [
385
            "email" => request()->email,
386
            "first_name" => request()->fname,
387
            "last_name" => request()->lname,
388
            "phone" => request()->phone,
389
            "metadata" => request()->additional_info /* key => value pairs array */
390
391
        ];
392
393
        $this->setRequestOptions();
394
        return $this->setHttpResponse('/customer', 'POST', $data)->getResponse();
395
    }
396
397
    /**
398
     * Fetch a customer based on id or code
399
     * @param $customer_id
400
     * @return array
401
     */
402
    public function fetchCustomer($customer_id)
403
    {
404
        $this->setRequestOptions();
405
        return $this->setHttpResponse('/customer/'. $customer_id, 'GET', [])->getResponse();
406
    }
407
408
    /**
409
     * Update a customer's details based on their id or code
410
     * @param $customer_id
411
     * @return array
412
     */
413 View Code Duplication
    public function updateCustomer($customer_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
414
    {
415
        $data = [
416
            "email" => request()->email,
417
            "first_name" => request()->fname,
418
            "last_name" => request()->lname,
419
            "phone" => request()->phone,
420
            "metadata" => request()->additional_info /* key => value pairs array */
421
422
        ];
423
424
        $this->setRequestOptions();
425
        return $this->setHttpResponse('/customer/'. $customer_id, 'PUT', $data)->getResponse();
426
    }
427
428
    /**
429
     * Export transactions in .CSV
430
     * @return array
431
     */
432
    public function exportTransactions()
433
    {
434
        $data = [
435
            "from" => request()->from,
436
            "to" => request()->to,
437
            'settled' => request()->settled
438
        ];
439
440
        $this->setRequestOptions();
441
        return $this->setHttpResponse('/transaction/export', 'GET', $data)->getResponse();
442
    }
443
444
    /**
445
     * Create a subscription to a plan from a customer.
446
     */
447 View Code Duplication
    public function createSubscription()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
448
    {
449
        $data = [
450
            "customer" => request()->customer, //Customer email or code
451
            "plan" => request()->plan,
452
            "authorization" => request()->authorization_code
453
        ];
454
455
        $this->setRequestOptions();
456
        $this->setHttpResponse('/subscription', 'POST', $data);
457
    }
458
459
    /**
460
     * Get all the subscriptions made on Paystack.
461
     *
462
     * @return array
463
     */
464
    public function getAllSubscriptions()
465
    {
466
        $this->setRequestOptions();
467
468
        return $this->setHttpResponse("/subscription", 'GET', [])->getData();
469
    }
470
471
    /**
472
     * Get customer subscriptions
473
     *
474
     * @param integer $customer_id
475
     * @return array
476
     */
477
    public function getCustomerSubscriptions($customer_id)
478
    {
479
        $this->setRequestOptions();
480
481
        return $this->setHttpResponse('/subscription?customer=' . $customer_id, 'GET', [])->getData();
482
    }
483
484
    /**
485
     * Get plan subscriptions
486
     *
487
     * @param  integer $plan_id
488
     * @return array
489
     */
490
    public function getPlanSubscriptions($plan_id)
491
    {
492
        $this->setRequestOptions();
493
494
        return $this->setHttpResponse('/subscription?plan=' . $plan_id, 'GET', [])->getData();
495
    }
496
497
    /**
498
     * Enable a subscription using the subscription code and token
499
     * @return array
500
     */
501 View Code Duplication
    public function enableSubscription()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
502
    {
503
        $data = [
504
            "code" => request()->code,
505
            "token" => request()->token,
506
        ];
507
508
        $this->setRequestOptions();
509
        return $this->setHttpResponse('/subscription/enable', 'POST', $data)->getResponse();
510
    }
511
512
    /**
513
     * Disable a subscription using the subscription code and token
514
     * @return array
515
     */
516 View Code Duplication
    public function disableSubscription()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
517
    {
518
        $data = [
519
            "code" => request()->code,
520
            "token" => request()->token,
521
        ];
522
523
        $this->setRequestOptions();
524
        return $this->setHttpResponse('/subscription/disable', 'POST', $data)->getResponse();
525
    }
526
527
    /**
528
     * Fetch details about a certain subscription
529
     * @param mixed $subscription_id
530
     * @return array
531
     */
532
    public function fetchSubscription($subscription_id)
533
    {
534
        $this->setRequestOptions();
535
        return $this->setHttpResponse('/subscription/'.$subscription_id, 'GET', [])->getResponse();
536
    }
537
538
    /**
539
     * Create pages you can share with users using the returned slug
540
     */
541 View Code Duplication
    public function createPage()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
542
    {
543
        $data = [
544
            "name" => request()->name,
545
            "description" => request()->description,
546
            "amount" => request()->amount
547
        ];
548
549
        $this->setRequestOptions();
550
        $this->setHttpResponse('/page', 'POST', $data);
551
    }
552
553
    /**
554
     * Fetches all the pages the merchant has
555
     * @return array
556
     */
557
    public function getAllPages()
558
    {
559
        $this->setRequestOptions();
560
        return $this->setHttpResponse('/page', 'GET', [])->getResponse();
561
    }
562
563
    /**
564
     * Fetch details about a certain page using its id or slug
565
     * @param mixed $page_id
566
     * @return array
567
     */
568
    public function fetchPage($page_id)
569
    {
570
        $this->setRequestOptions();
571
        return $this->setHttpResponse('/page/'.$page_id, 'GET', [])->getResponse();
572
    }
573
574
    /**
575
     * Update the details about a particular page
576
     * @param $page_id
577
     * @return array
578
     */
579 View Code Duplication
    public function updatePage($page_id)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
580
    {
581
        $data = [
582
            "name" => request()->name,
583
            "description" => request()->description,
584
            "amount" => request()->amount
585
        ];
586
587
        $this->setRequestOptions();
588
        return $this->setHttpResponse('/page/'.$page_id, 'PUT', $data)->getResponse();
589
    }
590
591
     /**
592
     * Creates a subaccount to be used for split payments . Required    params are business_name , settlement_bank , account_number ,   percentage_charge
593
     * 
594
     * @return array
595
     */
596
    
597 View Code Duplication
    public function createSubAccount(){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
598
        $data = [
599
            "business_name" => request()->business_name, 
600
            "settlement_bank" => request()->settlement_bank,
601
            "account_number" => request()->account_number,
602
            "percentage_charge" => request()->percentage_charge,
603
            "primary_contact_email" => request()->primary_contact_email,
604
            "primary_contact_name" => request()->primary_contact_name,
605
            "primary_contact_phone" => request()->primary_contact_phone,
606
            "metadata" => request()->metadata,
607
            'settlement_schedule' => request()->settlement_schedule
608
        ];
609
610
        $this->setRequestOptions();
611
        return $this->setHttpResponse('/subaccount', 'POST', array_filter($data))->getResponse();
612
613
    }
614
615
     /**
616
     * Fetches details of a subaccount
617
     * @param subaccount code
618
     * @return array
619
     */
620
    public function fetchSubAccount($subaccount_code){
621
622
        $this->setRequestOptions();
623
        return $this->setHttpResponse("/subaccount/{$subaccount_code}","GET",[])->getResponse();
624
625
    }
626
627
     /**
628
     * Lists all the subaccounts associated with the account
629
     * @param $per_page - Specifies how many records to retrieve per page , $page - SPecifies exactly what page to retrieve
630
     * @return array
631
     */
632
    public function listSubAccounts($per_page,$page){
633
634
        $this->setRequestOptions();
635
        return $this->setHttpResponse("/subaccount/?perPage=".(int) $per_page."&page=".(int) $page,"GET")->getResponse();
636
637
    }
638
639
640
    /**
641
     * Updates a subaccount to be used for split payments . Required params are business_name , settlement_bank , account_number , percentage_charge
642
     * @param subaccount code 
643
     * @return array
644
     */
645
    
646 View Code Duplication
    public function updateSubAccount($subaccount_code){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
647
        $data = [
648
            "business_name" => request()->business_name, 
649
            "settlement_bank" => request()->settlement_bank,
650
            "account_number" => request()->account_number,
651
            "percentage_charge" => request()->percentage_charge,
652
            "description" => request()->description,
653
            "primary_contact_email" => request()->primary_contact_email,
654
            "primary_contact_name" => request()->primary_contact_name,
655
            "primary_contact_phone" => request()->primary_contact_phone,
656
            "metadata" => request()->metadata,
657
            'settlement_schedule' => request()->settlement_schedule
658
        ];
659
660
        $this->setRequestOptions();
661
        return $this->setHttpResponse("/subaccount/{$subaccount_code}", "PUT", array_filter($data))->getResponse();
662
663
    }
664
}
665