-
Notifications
You must be signed in to change notification settings - Fork 320
/
Copy pathPaystack.php
699 lines (594 loc) · 19.9 KB
/
Paystack.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
<?php
/*
* This file is part of the Laravel Paystack package.
*
* (c) Prosper Otemuyiwa <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Unicodeveloper\Paystack;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Config;
use Unicodeveloper\Paystack\Exceptions\IsNullException;
use Unicodeveloper\Paystack\Exceptions\PaymentVerificationFailedException;
class Paystack
{
/**
* Transaction Verification Successful
*/
const VS = 'Verification successful';
/**
* Invalid Transaction reference
*/
const ITF = "Invalid transaction reference";
/**
* Issue Secret Key from your Paystack Dashboard
* @var string
*/
protected $secretKey;
/**
* Instance of Client
* @var Client
*/
protected $client;
/**
* Response from requests made to Paystack
* @var mixed
*/
protected $response;
/**
* Paystack API base Url
* @var string
*/
protected $baseUrl;
/**
* Authorization Url - Paystack payment page
* @var string
*/
protected $authorizationUrl;
public function __construct()
{
$this->setKey();
$this->setBaseUrl();
$this->setRequestOptions();
}
/**
* Get Base Url from Paystack config file
*/
public function setBaseUrl()
{
$this->baseUrl = Config::get('paystack.paymentUrl');
}
/**
* Get secret key from Paystack config file
*/
public function setKey()
{
$this->secretKey = Config::get('paystack.secretKey');
}
/**
* Set options for making the Client request
*/
private function setRequestOptions()
{
$authBearer = 'Bearer '. $this->secretKey;
$this->client = new Client(
[
'base_uri' => $this->baseUrl,
'headers' => [
'Authorization' => $authBearer,
'Content-Type' => 'application/json',
'Accept' => 'application/json'
]
]
);
}
/**
* Initiate a payment request to Paystack
* Included the option to pass the payload to this method for situations
* when the payload is built on the fly (not passed to the controller from a view)
* @return Paystack
*/
public function makePaymentRequest($data = null)
{
if ( $data == null ) {
$quantity = intval(request()->quantity ?? 1);
$data = array_filter([
"amount" => intval(request()->amount) * $quantity,
"reference" => request()->reference,
"email" => request()->email,
"plan" => request()->plan,
"first_name" => request()->first_name,
"last_name" => request()->last_name,
"callback_url" => request()->callback_url,
"currency" => (request()->currency != "" ? request()->currency : "NGN"),
/*
Paystack allows for transactions to be split into a subaccount -
The following lines trap the subaccount ID - as well as the ammount to charge the subaccount (if overriden in the form)
both values need to be entered within hidden input fields
*/
"subaccount" => request()->subaccount,
"transaction_charge" => request()->transaction_charge,
/**
* Paystack allows for transaction to be split into multi accounts(subaccounts)
* The following lines trap the split ID handling the split
* More details here: https://paystack.com/docs/payments/multi-split-payments/#using-transaction-splits-with-payments
*/
"split_code" => request()->split_code,
/**
* Paystack allows transaction to be split into multi account(subaccounts) on the fly without predefined split
* form need an input field: <input type="hidden" name="split" value="{{ json_encode($split) }}" >
* array must be set up as:
* $split = [
* "type" => "percentage",
* "currency" => "KES",
* "subaccounts" => [
* { "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 10 },
* { "subaccount" => "ACCT_li4p6kte2dolodo", "share" => 30 },
* ],
* "bearer_type" => "all",
* "main_account_share" => 70,
* ]
* More details here: https://paystack.com/docs/payments/multi-split-payments/#dynamic-splits
*/
"split" => request()->split,
/*
* to allow use of metadata on Paystack dashboard and a means to return additional data back to redirect url
* form need an input field: <input type="hidden" name="metadata" value="{{ json_encode($array) }}" >
* array must be set up as:
* $array = [ 'custom_fields' => [
* ['display_name' => "Cart Id", "variable_name" => "cart_id", "value" => "2"],
* ['display_name' => "Sex", "variable_name" => "sex", "value" => "female"],
* .
* .
* .
* ]
* ]
*/
'metadata' => request()->metadata
]);
}
$this->setHttpResponse('/transaction/initialize', 'POST', $data);
return $this;
}
/**
* @param string $relativeUrl
* @param string $method
* @param array $body
* @return Paystack
* @throws IsNullException
*/
private function setHttpResponse($relativeUrl, $method, $body = [])
{
if (is_null($method)) {
throw new IsNullException("Empty method not allowed");
}
$this->response = $this->client->{strtolower($method)}(
$this->baseUrl . $relativeUrl,
["body" => json_encode($body)]
);
return $this;
}
/**
* Get the authorization url from the callback response
* @return Paystack
*/
public function getAuthorizationUrl($data = null)
{
$this->makePaymentRequest($data);
$this->url = $this->getResponse()['data']['authorization_url'];
return $this;
}
/**
* Get the authorization callback response
* In situations where Laravel serves as an backend for a detached UI, the api cannot redirect
* and might need to take different actions based on the success or not of the transaction
* @return array
*/
public function getAuthorizationResponse($data)
{
$this->makePaymentRequest($data);
$this->url = $this->getResponse()['data']['authorization_url'];
return $this->getResponse();
}
/**
* Hit Paystack Gateway to Verify that the transaction is valid
*/
private function verifyTransactionAtGateway()
{
$transactionRef = request()->query('trxref');
$relativeUrl = "/transaction/verify/{$transactionRef}";
$this->response = $this->client->get($this->baseUrl . $relativeUrl, []);
}
/**
* True or false condition whether the transaction is verified
* @return boolean
*/
public function isTransactionVerificationValid()
{
$this->verifyTransactionAtGateway();
$result = $this->getResponse()['message'];
switch ($result) {
case self::VS:
$validate = true;
break;
case self::ITF:
$validate = false;
break;
default:
$validate = false;
break;
}
return $validate;
}
/**
* Get Payment details if the transaction was verified successfully
* @return json
* @throws PaymentVerificationFailedException
*/
public function getPaymentData()
{
if ($this->isTransactionVerificationValid()) {
return $this->getResponse();
} else {
throw new PaymentVerificationFailedException("Invalid Transaction Reference");
}
}
/**
* Fluent method to redirect to Paystack Payment Page
*/
public function redirectNow()
{
//return redirect($this->url);
return redirect()->to($this->url)->send();
}
/**
* Get Access code from transaction callback respose
* @return string
*/
public function getAccessCode()
{
return $this->getResponse()['data']['access_code'];
}
/**
* Generate a Unique Transaction Reference
* @return string
*/
public function genTranxRef()
{
return TransRef::getHashedToken();
}
/**
* Get all the customers that have made transactions on your platform
* @return array
*/
public function getAllCustomers()
{
$this->setRequestOptions();
return $this->setHttpResponse("/customer", 'GET', [])->getData();
}
/**
* Get all the plans that you have on Paystack
* @return array
*/
public function getAllPlans()
{
$this->setRequestOptions();
return $this->setHttpResponse("/plan", 'GET', [])->getData();
}
/**
* Get all the transactions that have happened overtime
* @return array
*/
public function getAllTransactions()
{
$this->setRequestOptions();
return $this->setHttpResponse("/transaction", 'GET', [])->getData();
}
/**
* Get the whole response from a get operation
* @return array
*/
private function getResponse()
{
return json_decode($this->response->getBody(), true);
}
/**
* Get the data response from a get operation
* @return array
*/
private function getData()
{
return $this->getResponse()['data'];
}
/**
* Create a plan
*/
public function createPlan()
{
$data = [
"name" => request()->name,
"description" => request()->desc,
"amount" => intval(request()->amount),
"interval" => request()->interval,
"send_invoices" => request()->send_invoices,
"send_sms" => request()->send_sms,
"currency" => request()->currency,
];
$this->setRequestOptions();
return $this->setHttpResponse("/plan", 'POST', $data)->getResponse();
}
/**
* Fetch any plan based on its plan id or code
* @param $plan_code
* @return array
*/
public function fetchPlan($plan_code)
{
$this->setRequestOptions();
return $this->setHttpResponse('/plan/' . $plan_code, 'GET', [])->getResponse();
}
/**
* Update any plan's details based on its id or code
* @param $plan_code
* @return array
*/
public function updatePlan($plan_code)
{
$data = [
"name" => request()->name,
"description" => request()->desc,
"amount" => intval(request()->amount),
"interval" => request()->interval,
"send_invoices" => request()->send_invoices,
"send_sms" => request()->send_sms,
"currency" => request()->currency,
];
$this->setRequestOptions();
return $this->setHttpResponse('/plan/' . $plan_code, 'PUT', $data)->getResponse();
}
/**
* Create a customer
*/
public function createCustomer()
{
$data = [
"email" => request()->email,
"first_name" => request()->fname,
"last_name" => request()->lname,
"phone" => request()->phone,
"metadata" => request()->additional_info /* key => value pairs array */
];
$this->setRequestOptions();
return $this->setHttpResponse('/customer', 'POST', $data)->getResponse();
}
/**
* Fetch a customer based on id or code
* @param $customer_id
* @return array
*/
public function fetchCustomer($customer_id)
{
$this->setRequestOptions();
return $this->setHttpResponse('/customer/'. $customer_id, 'GET', [])->getResponse();
}
/**
* Update a customer's details based on their id or code
* @param $customer_id
* @return array
*/
public function updateCustomer($customer_id)
{
$data = [
"email" => request()->email,
"first_name" => request()->fname,
"last_name" => request()->lname,
"phone" => request()->phone,
"metadata" => request()->additional_info /* key => value pairs array */
];
$this->setRequestOptions();
return $this->setHttpResponse('/customer/'. $customer_id, 'PUT', $data)->getResponse();
}
/**
* Export transactions in .CSV
* @return array
*/
public function exportTransactions()
{
$data = [
"from" => request()->from,
"to" => request()->to,
'settled' => request()->settled
];
$this->setRequestOptions();
return $this->setHttpResponse('/transaction/export', 'GET', $data)->getResponse();
}
/**
* Create a subscription to a plan from a customer.
*/
public function createSubscription()
{
$data = [
"customer" => request()->customer, //Customer email or code
"plan" => request()->plan,
"authorization" => request()->authorization_code
];
$this->setRequestOptions();
return $this->setHttpResponse('/subscription', 'POST', $data)->getResponse();
}
/**
* Get all the subscriptions made on Paystack.
*
* @return array
*/
public function getAllSubscriptions()
{
$this->setRequestOptions();
return $this->setHttpResponse("/subscription", 'GET', [])->getData();
}
/**
* Get customer subscriptions
*
* @param integer $customer_id
* @return array
*/
public function getCustomerSubscriptions($customer_id)
{
$this->setRequestOptions();
return $this->setHttpResponse('/subscription?customer=' . $customer_id, 'GET', [])->getData();
}
/**
* Get plan subscriptions
*
* @param integer $plan_id
* @return array
*/
public function getPlanSubscriptions($plan_id)
{
$this->setRequestOptions();
return $this->setHttpResponse('/subscription?plan=' . $plan_id, 'GET', [])->getData();
}
/**
* Enable a subscription using the subscription code and token
* @return array
*/
public function enableSubscription()
{
$data = [
"code" => request()->code,
"token" => request()->token,
];
$this->setRequestOptions();
return $this->setHttpResponse('/subscription/enable', 'POST', $data)->getResponse();
}
/**
* Disable a subscription using the subscription code and token
* @return array
*/
public function disableSubscription()
{
$data = [
"code" => request()->code,
"token" => request()->token,
];
$this->setRequestOptions();
return $this->setHttpResponse('/subscription/disable', 'POST', $data)->getResponse();
}
/**
* Fetch details about a certain subscription
* @param mixed $subscription_id
* @return array
*/
public function fetchSubscription($subscription_id)
{
$this->setRequestOptions();
return $this->setHttpResponse('/subscription/'.$subscription_id, 'GET', [])->getResponse();
}
/**
* Create pages you can share with users using the returned slug
*/
public function createPage()
{
$data = [
"name" => request()->name,
"description" => request()->description,
"amount" => request()->amount
];
$this->setRequestOptions();
return $this->setHttpResponse('/page', 'POST', $data)->getResponse();
}
/**
* Fetches all the pages the merchant has
* @return array
*/
public function getAllPages()
{
$this->setRequestOptions();
return $this->setHttpResponse('/page', 'GET', [])->getResponse();
}
/**
* Fetch details about a certain page using its id or slug
* @param mixed $page_id
* @return array
*/
public function fetchPage($page_id)
{
$this->setRequestOptions();
return $this->setHttpResponse('/page/'.$page_id, 'GET', [])->getResponse();
}
/**
* Update the details about a particular page
* @param $page_id
* @return array
*/
public function updatePage($page_id)
{
$data = [
"name" => request()->name,
"description" => request()->description,
"amount" => request()->amount
];
$this->setRequestOptions();
return $this->setHttpResponse('/page/'.$page_id, 'PUT', $data)->getResponse();
}
/**
* Creates a subaccount to be used for split payments . Required params are business_name , settlement_bank , account_number , percentage_charge
*
* @return array
*/
public function createSubAccount(){
$data = [
"business_name" => request()->business_name,
"settlement_bank" => request()->settlement_bank,
"account_number" => request()->account_number,
"percentage_charge" => request()->percentage_charge,
"primary_contact_email" => request()->primary_contact_email,
"primary_contact_name" => request()->primary_contact_name,
"primary_contact_phone" => request()->primary_contact_phone,
"metadata" => request()->metadata,
'settlement_schedule' => request()->settlement_schedule
];
$this->setRequestOptions();
return $this->setHttpResponse('/subaccount', 'POST', array_filter($data))->getResponse();
}
/**
* Fetches details of a subaccount
* @param subaccount code
* @return array
*/
public function fetchSubAccount($subaccount_code){
$this->setRequestOptions();
return $this->setHttpResponse("/subaccount/{$subaccount_code}","GET",[])->getResponse();
}
/**
* Lists all the subaccounts associated with the account
* @param $per_page - Specifies how many records to retrieve per page , $page - SPecifies exactly what page to retrieve
* @return array
*/
public function listSubAccounts($per_page,$page){
$this->setRequestOptions();
return $this->setHttpResponse("/subaccount/?perPage=".(int) $per_page."&page=".(int) $page,"GET")->getResponse();
}
/**
* Updates a subaccount to be used for split payments . Required params are business_name , settlement_bank , account_number , percentage_charge
* @param subaccount code
* @return array
*/
public function updateSubAccount($subaccount_code){
$data = [
"business_name" => request()->business_name,
"settlement_bank" => request()->settlement_bank,
"account_number" => request()->account_number,
"percentage_charge" => request()->percentage_charge,
"description" => request()->description,
"primary_contact_email" => request()->primary_contact_email,
"primary_contact_name" => request()->primary_contact_name,
"primary_contact_phone" => request()->primary_contact_phone,
"metadata" => request()->metadata,
'settlement_schedule' => request()->settlement_schedule
];
$this->setRequestOptions();
return $this->setHttpResponse("/subaccount/{$subaccount_code}", "PUT", array_filter($data))->getResponse();
}
}