Completed
Pull Request — master (#3)
by
unknown
02:19
created

Paystack::createPlan()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 11

Duplication

Lines 18
Ratio 100 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 18
loc 18
rs 9.4285
cc 1
eloc 11
nc 1
nop 0
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
17
class Paystack {
18
19
    /**
20
     * Transaction Verification Successful
21
     */
22
    const VS = 'Verification successful';
23
24
    /**
25
     *  Invalid Transaction reference
26
     */
27
    const ITF = "Invalid transaction reference";
28
29
    /**
30
     * Issue Secret Key from your Paystack Dashboard
31
     * @var mixed
32
     */
33
    protected $secretKey;
34
35
    /**
36
     * Instance of Client
37
     * @var object
38
     */
39
    protected $client;
40
41
    /**
42
     *  Response from requests made to Paystack
43
     * @var mixed
44
     */
45
    protected $response;
46
47
    /**
48
     * Paystack API base Url
49
     * @var string
50
     */
51
    protected $baseUrl;
52
53
    /**
54
     * Authorization Url - Paystack payment page
55
     * @var string
56
     */
57
    protected $authorizationUrl;
58
59
    public function __construct()
60
    {
61
        $this->setKey();
62
        $this->setBaseUrl();
63
        $this->setRequestOptions();
64
    }
65
66
    /**
67
     * Get Base Url from Paystack config file
68
     */
69
    public function setBaseUrl()
70
    {
71
        $this->baseUrl = Config::get('paystack.paymentUrl');
72
    }
73
74
    /**
75
     * Get secret key from Paystack config file
76
     * @return  void
77
     */
78
    public function setKey()
79
    {
80
        $this->secretKey = Config::get('paystack.secretKey');
81
    }
82
83
    /**
84
     * Set options for making the Client request
85
     * @return  void
86
     */
87
    private function setRequestOptions()
88
    {
89
        $authBearer = 'Bearer '. $this->secretKey;
90
91
        $this->client = new Client(['base_uri' => $this->baseUrl,
92
            'headers' => [
93
                'Authorization' => $authBearer,
94
                'Content-Type'  => 'application/json',
95
                'Accept'        => 'application/json'
96
        ]]);
97
    }
98
99
    /**
100
     * Initiate a payment request to Paystack
101
     * @return Unicodeveloper\Paystack\Paystack
102
     */
103
    public function makePaymentRequest()
104
    {
105
        $this->setResponse('/transaction/initialize');
106
107
        return $this;
108
    }
109
110
    /**
111
     * Make the client request and get the response
112
     * @param string $relativeUrl
113
     * @return Unicodeveloper\Paystack\Paystack
114
     */
115
    public function setResponse($relativeUrl)
116
    {
117
        $data = [
118
            "amount" => intval(request()->amount),
119
            "reference" => request()->reference,
120
            "email" => request()->email
121
        ];
122
123
        $this->response = $this->client->post($this->baseUrl . $relativeUrl, [
124
            'body' => json_encode($data)
125
        ]);
126
127
        return $this;
128
    }
129
130
    private function setGetResponse($relativeUrl, $body = array())
131
    {
132
        $this->response = $this->client->get($this->baseUrl . $relativeUrl, $body);
133
134
        return $this;
135
    }
136
137
    /**
138
     * Get the authorization url from the callback response
139
     * @return Unicodeveloper\Paystack\Paystack
140
     */
141
    public function getAuthorizationUrl()
142
    {
143
        $this->makePaymentRequest();
144
145
        $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...
146
147
        return $this;
148
    }
149
150
    /**
151
     * Hit Paystack Gateway to Verify that the transaction is valid
152
     * @return void
153
     */
154
    private function verifyTransactionAtGateway()
155
    {
156
        $transactionRef = request()->query('trxref');
157
158
        $relativeUrl = "/transaction/verify/{$transactionRef}";
159
160
        $this->response = $this->client->get($this->baseUrl . $relativeUrl, []);
161
    }
162
163
    /**
164
     * True or false condition whether the transaction is verified
165
     * @return boolean
166
     */
167
    public function isTransactionVerificationValid()
168
    {
169
        $this->verifyTransactionAtGateway();
170
171
        $result = $this->getResponse()['message'];
172
173
        switch ($result)
174
        {
175
            case self::VS:
176
                $validate = true;
177
                break;
178
            case self:ITF:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
179
                $validate = false;
180
                break;
181
            default:
182
                $validate = false;
183
                break;
184
        }
185
186
        return $validate;
187
    }
188
189
    /**
190
     * Get Payment details if the transaction was verified successfully
191
     * @return json
192
     * @throws PaymentVerificationFailedException
193
     */
194
    public function getPaymentData()
195
    {
196
        if ($this->isTransactionVerificationValid()) {
197
            return $this->getResponse();
198
        } else {
199
            throw new PaymentVerificationFailedException("Invalid Transaction Reference");
200
        }
201
    }
202
203
    /**
204
     * Fluent method to redirect to Paystack Payment Page
205
     * @return Illuminate\Support\Redirect
206
     */
207
    public function redirectNow()
208
    {
209
        return redirect($this->url);
210
    }
211
212
    /**
213
     * Get Access code from transaction callback respose
214
     * @return string
215
     */
216
    public function getAccessCode()
217
    {
218
        return $this->getResponse()['data']['access_code'];
219
    }
220
221
    /**
222
     * Generate a Unique Transaction Reference
223
     * @return string
224
     */
225
    public function genTranxRef()
226
    {
227
        return TransRef::getHashedToken();
228
    }
229
230
    /**
231
     * Get all the customers that have made transactions on your platform
232
     * @return array
233
     */
234
    public function getAllCustomers()
235
    {
236
        $this->setRequestOptions();
237
238
        return $this->setGetResponse("/customer", [])->getData();
239
    }
240
241
    /**
242
     * Get all the plans that you have on Paystack
243
     * @return array
244
     */
245
    public function getAllPlans()
246
    {
247
        $this->setRequestOptions();
248
249
        return $this->setGetResponse("/plan", [])->getData();
250
    }
251
252
    /**
253
     * Get all the transactions that have happened overtime
254
     * @return array
255
     */
256
    public function getAllTransactions()
257
    {
258
        $this->setRequestOptions();
259
260
        return $this->setGetResponse("/transaction", [])->getData();
261
    }
262
263
    /**
264
     * Get the whole response from a get operation
265
     * @return array
266
     */
267
    private function getResponse()
268
    {
269
        return json_decode($this->response->getBody(), true);
270
    }
271
272
    /**
273
     * Get the data response from a get operation
274
     * @return array
275
     */
276
    private function getData()
277
    {
278
        return $this->getResponse()['data'];
279
    }
280
281
    //Edits by Funsho http://devfunsho.com | @iamfusnho - 22/05/2016
282
283
    /**
284
     * Create a plan
285
     * @return array
286
     */
287 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...
288
289
        $data = [
290
291
            "name" => request()->name,
292
            "description" => request()->desc,
293
            "amount" => intval(request()->amount),
294
            "interval" => request()->interval,
295
            "send_invoices" => request()->send_invoices,
296
            "send_sms" => request()->send_sms,
297
            "currency" => request()->currency,
298
        ];
299
300
        $this->setRequestOptions();
301
302
        return $this->setGetResponse("/plan", $data)->getResponse();
303
304
    }
305
306
    /**
307
     * Fetch any plan based on its plan id or code
308
     * @param $plan_code
309
     * @return array
310
     */
311
    public function fetchPlan($plan_code){
312
313
        $this->setRequestOptions();
314
315
        return $this->setGetResponse('/plan/' . $plan_code, [])->getResponse();
316
317
    }
318
319
    /**
320
     * Update any plan's details based on its id or code
321
     * @param $plan_code
322
     * @return array
323
     */
324 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...
325
326
        $data = [
327
328
            "name" => request()->name,
329
            "description" => request()->desc,
330
            "amount" => intval(request()->amount),
331
            "interval" => request()->interval,
332
            "send_invoices" => request()->send_invoices,
333
            "send_sms" => request()->send_sms,
334
            "currency" => request()->currency,
335
        ];
336
337
        $this->setRequestOptions();
338
339
        return $this->setGetResponse('/plan/' . $plan_code, $data)->getResponse();
340
341
    }
342
343
    /**
344
     * Create a customer
345
     * @return array
346
     */
347 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...
348
349
        $data = [
350
351
            "email" => request()->email,
352
            "first_name" => request()->fname,
353
            "last_name" => request()->lname,
354
            "phone" => request()->phone,
355
            "metadata" => request()->addtional_info /* key => value pairs array */
356
357
        ];
358
359
        $this->setRequestOptions();
360
361
        return $this->setGetResponse('/customer', $data)->getResponse();
362
363
    }
364
365
    /**
366
     * Fetch a customer based on id or code
367
     * @param $customer_id
368
     * @return array
369
     */
370
    public function fetchCustomer($customer_id){
371
372
        $this->setRequestOptions();
373
374
        return $this->setGetResponse('/customer/'. $customer_id, [])->getResponse();
375
376
    }
377
378
    /**
379
     * Update a customer's details based on their id or code
380
     * @param $customer_id
381
     * @return array
382
     */
383 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...
384
385
        $data = [
386
387
            "email" => request()->email,
388
            "first_name" => request()->fname,
389
            "last_name" => request()->lname,
390
            "phone" => request()->phone,
391
            "metadata" => request()->addtional_info /* key => value pairs array */
392
393
        ];
394
395
        $this->setRequestOptions();
396
397
        return $this->setGetResponse('/customer/'. $customer_id, $data)->getResponse();
398
399
    }
400
401
    /**
402
     * Export tranactions in .CSV
403
     * @return array
404
     */
405 View Code Duplication
    public function exportTransactions(){
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...
406
407
        $data = [
408
            "from" => request()->from,
409
            "to" => request()->to,
410
            'settled' => request()->settled
411
        ];
412
413
        $this->setRequestOptions();
414
415
        return $this->setGetResponse('/transaction/export', $data)->getResponse();
416
417
    }
418
419
    /**
420
     * Create a subscription to a plan from a customer.
421
     * @return array
422
     */
423 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...
424
425
        $data = [
426
            "customer" => request()->customer, //Customer email or code
427
            "plan" => request()->plan,
428
            "authorization" => request()->authorization_code
429
        ];
430
431
        $this->setRequestOptions();
432
433
        return $this->setGetResponse('/subscription', $data)->getResponse();
434
    }
435
436
    /**
437
     * Enable a subscription using the subscription code and token
438
     * @return array
439
     */
440 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...
441
442
        $data = [
443
            "code" => request()->code,
444
            "token" => request()->token,
445
        ];
446
447
        $this->setRequestOptions();
448
449
        return $this->setGetResponse('/subscription/enable', $data)->getResponse();
450
451
    }
452
453
    /**
454
     * Disable a subscription using the subscription code and token
455
     * @return array
456
     */
457 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...
458
459
        $data = [
460
            "code" => request()->code,
461
            "token" => request()->token,
462
        ];
463
464
        $this->setRequestOptions();
465
466
        return $this->setGetResponse('/subscription/disable', $data)->getResponse();
467
468
    }
469
470
    /**
471
     * Fetch details about a certain subscription
472
     * @param $subscription_id
473
     * @return array
474
     */
475
    public function fetchSubscription($subscription_id){
476
477
        $this->setRequestOptions();
478
479
        return $this->setGetResponse('/subscription/'.$subscription_id, [])->getResponse();
480
481
    }
482
483
    /**
484
     * Create pages you can share with users using the returned slug
485
     * @return array
486
     */
487 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...
488
489
        $data = [
490
491
            "name" => request()->name,
492
            "description" => request()->description,
493
            "amount" => request()->amount
494
        ];
495
496
        $this->setRequestOptions();
497
498
        return $this->setGetResponse('/page', $data)->getResponse();
499
500
    }
501
502
    /**
503
     * Fetches all the pages the merchant has
504
     * @return array
505
     */
506
    public function getAllPages(){
507
508
        $this->setRequestOptions();
509
510
        return $this->setGetResponse('/page', [])->getResponse();
511
512
    }
513
514
    /**
515
     * Fetch details about a certain page using its id or slug
516
     * @param $page_id
517
     * @return array
518
     */
519
    public function fetchPage($page_id){
520
521
        $this->setRequestOptions();
522
523
        return $this->setGetResponse('/page/'.$page_id, [])->getResponse();
524
525
    }
526
527
    /**
528
     * Update the details about a particular page
529
     * @param $page_id
530
     * @return array
531
     */
532 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...
533
534
        $data = [
535
536
            "name" => request()->name,
537
            "description" => request()->description,
538
            "amount" => request()->amount
539
        ];
540
541
        $this->setRequestOptions();
542
543
        return $this->setGetResponse('/page/'.$page_id, $data)->getResponse();
544
545
    }
546
547
}
548
549
550
551