-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMeprPaystackGateway.php
1545 lines (1269 loc) · 53.1 KB
/
MeprPaystackGateway.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
if (!defined('ABSPATH')) {
die('You are not allowed to call this page directly.');
}
class MeprPaystackGateway extends MeprBaseRealGateway
{
public static $paystack_plan_id_str = '_mepr_paystack_plan_id';
/** This will be where the gateway api will interacted from */
public $paystack_api;
/** Used in the view to identify the gateway */
public function __construct()
{
$this->name = __("Paystack", 'memberpress');
$this->icon = MP_PAYSTACK_IMAGES_URL . '/cards.png';
$this->desc = __('Pay via Paystack', 'memberpress');
$this->set_defaults();
$this->key = __("Paystack", 'memberpress');
$this->capabilities = array(
'process-payments',
'process-refunds',
'create-subscriptions',
'cancel-subscriptions',
'suspend-subscriptions',
'resume-subscriptions',
'send-cc-expirations'
);
// Setup the notification actions for this gateway
$this->notifiers = array(
'whk' => 'webhook_listener',
'callback' => 'callback_handler',
);
$this->message_pages = array('subscription' => 'subscription_message');
}
public function load($settings)
{
$this->settings = (object) $settings;
$this->set_defaults();
$this->paystack_api = new MeprPaystackAPI($this->settings);
}
protected function set_defaults()
{
if (!isset($this->settings)) {
$this->settings = array();
}
$this->settings = (object) array_merge(
array(
'gateway' => 'MeprPaystackGateway',
'id' => $this->generate_id(),
'label' => '',
'use_label' => true,
'icon' => MP_PAYSTACK_IMAGES_URL . '/paystack.png',
'use_icon' => true,
'use_desc' => true,
'email' => '',
'sandbox' => false,
'force_ssl' => false,
'debug' => false,
'test_mode' => false,
'api_keys' => array(
'test' => array(
'public' => '',
'secret' => ''
),
'live' => array(
'public' => '',
'secret' => ''
)
)
),
(array) $this->settings
);
$this->id = $this->settings->id;
$this->label = $this->settings->label;
$this->use_label = $this->settings->use_label;
$this->use_icon = $this->settings->use_icon;
$this->use_desc = $this->settings->use_desc;
// $this->has_spc_form = $this->settings->use_paystack_checkout ? false : true;
//$this->recurrence_type = $this->settings->recurrence_type;
if ($this->is_test_mode()) {
$this->settings->public_key = trim($this->settings->api_keys['test']['public']);
$this->settings->secret_key = trim($this->settings->api_keys['test']['secret']);
} else {
$this->settings->public_key = trim($this->settings->api_keys['live']['public']);
$this->settings->secret_key = trim($this->settings->api_keys['live']['secret']);
}
}
/**
* Used to send data to a given payment gateway. In gateways which redirect
* before this step is necessary this method should just be left blank.
*/
public function process_payment($txn, $trial = false)
{
if (isset($txn) and $txn instanceof MeprTransaction) {
$usr = $txn->user();
$prd = $txn->product();
} else {
throw new MeprGatewayException(__('Payment transaction intialization was unsuccessful, please try again.', 'memberpress'));
}
$mepr_options = MeprOptions::fetch();
// Handle zero decimal currencies in Paystack
$amount = (MeprUtils::is_zero_decimal_currency()) ? MeprUtils::format_float(($txn->total), 0) : MeprUtils::format_float(($txn->total * 100), 0);
$custom_data[] = [
'display_name' => 'Plugin Name',
'variable_name' => 'plugin_name',
'value' => $this->paystack_api->plugin_name
];
// Initialize the charge on Paystack's servers - this will charge the user's card
$args = MeprHooks::apply_filters('mepr_paystack_payment_args', array(
'amount' => $amount,
'currency' => $mepr_options->currency_code,
'email' => $usr->user_email,
'reference' => $txn->trans_num,
'callback_url' => $this->notify_url('callback'),
'description' => sprintf(__('%s (transaction: %s)', 'memberpress'), $prd->post_title, $txn->id),
'metadata' => array(
'platform' => 'MemberPress Paystack',
'transaction_id' => $txn->id,
'trial_payment' => $trial,
'site_url' => esc_url(get_site_url()),
'ip_address' => $_SERVER['REMOTE_ADDR'],
'custom_fields' => $custom_data
)
), $txn);
// Initialize a new payment here
$response = (object) $this->paystack_api->send_request("transaction/initialize/", $args);
if (!$response->status) {
return false;
}
return MeprUtils::wp_redirect("{$response->data['authorization_url']}");
}
/**
* Used to record a successful payment by the given gateway. It should have
* the ability to record a successful payment or a failure. It is this method
* that should be used when receiving a Paystack Webhook.
*/
public function record_payment()
{
$this->email_status("Starting record_payment: " . MeprUtils::object_to_string($_REQUEST), $this->settings->debug);
if (isset($_REQUEST['data'])) {
$charge = $this->get_request_data();
$this->email_status("record_payment: \n" . MeprUtils::object_to_string($charge, true) . "\n", $this->settings->debug);
$obj = MeprTransaction::get_one_by_trans_num($charge->reference);
if (is_object($obj) and isset($obj->id)) {
$txn = new MeprTransaction;
$txn->load_data($obj);
$usr = $txn->user();
// Just short circuit if the txn has already completed
if ($txn->status == MeprTransaction::$complete_str)
return $txn;
$txn->status = MeprTransaction::$complete_str;
// This will only work before maybe_cancel_old_sub is run
$upgrade = $txn->is_upgrade();
$downgrade = $txn->is_downgrade();
$event_txn = $txn->maybe_cancel_old_sub();
$txn->store();
if ($charge->metadata['trial_payment'] == "1") {
$this->record_trial_payment($txn);
}
// Set Auth Token for Current User
$this->set_auth_token($usr, $charge->authorization);
$this->email_status("Standard Transaction\n" . MeprUtils::object_to_string($txn->rec, true) . "\n", $this->settings->debug);
$prd = $txn->product();
if ($prd->period_type == 'lifetime') {
if ($upgrade) {
$this->upgraded_sub($txn, $event_txn);
} else if ($downgrade) {
$this->downgraded_sub($txn, $event_txn);
} else {
$this->new_sub($txn);
}
MeprUtils::send_signup_notices($txn);
}
MeprUtils::send_transaction_receipt_notices($txn);
// MeprUtils::send_cc_expiration_notices($txn);
return $txn;
}
}
return false;
}
/**
* Used to send subscription data to a given payment gateway. In gateways
* which redirect before this step is necessary this method should just be
* left blank.
*/
public function process_create_subscription($txn)
{
if (isset($txn) and $txn instanceof MeprTransaction) {
$usr = $txn->user();
$prd = $txn->product();
} else {
throw new MeprGatewayException(__('Payment was unsuccessful, please check your payment details and try again.', 'memberpress'));
}
$mepr_options = MeprOptions::fetch();
$sub = $txn->subscription();
// Handle Free Trial period stuff
if ($sub->trial) {
//Prepare the $txn for the process_payment method
$txn->set_subtotal($sub->trial_amount);
$txn->status = MeprTransaction::$pending_str;
$this->record_trial_payment($txn);
return $txn;
}
// Handle zero decimal currencies in Paystack
$amount = (MeprUtils::is_zero_decimal_currency()) ? MeprUtils::format_float(($txn->total), 0) : MeprUtils::format_float(($txn->total * 100), 0);
error_log("********** MeprPaystackGateway::process_create_subscription Subscription:\n" . MeprUtils::object_to_string($sub));
// Get the plan
$plan = $this->paystack_plan($txn->subscription(), true);
//Reload the subscription now that it should have a token set
$sub = new MeprSubscription($sub->id);
// Default to 0 for infinite occurrences
$total_occurrences = $sub->limit_cycles ? $sub->limit_cycles_num : 0;
$custom_data[] = [
'display_name' => 'Plugin Name',
'variable_name' => 'plugin_name',
'value' => $this->paystack_api->plugin_name
];
$args = MeprHooks::apply_filters('mepr_paystack_subscription_args', array(
'amount' => $amount,
'callback_url' => $this->notify_url('callback'),
'reference' => $txn->trans_num, // MeprTransaction::generate_trans_num(),
'email' => $usr->user_email,
'plan' => $plan->plan_code,
'invoice_limit' => $total_occurrences,
'currency' => $mepr_options->currency_code,
'channels' => ['card'], // Set payment channel to accept only card for subscriptions
"start_date" => MeprUtils::get_date_from_ts((time() + (($sub->trial) ? MeprUtils::days($sub->trial_days) : 0)), 'Y-m-d'),
'metadata' => array(
'platform' => 'MemberPress Paystack',
'transaction_id' => $txn->id,
'subscription_id' => $sub->id,
'site_url' => esc_url(get_site_url()),
'ip_address' => $_SERVER['REMOTE_ADDR'],
'custom_fields' => $custom_data
)
), $txn, $sub);
$this->email_status("process_create_subscription: \n" . MeprUtils::object_to_string($txn, true) . "\n", $this->settings->debug);
error_log("********** MeprPaystackGateway::process_create_subscription altered Subscription:\n" . MeprUtils::object_to_string($sub));
error_log("********** MeprPaystackGateway::process_create_subscription Transaction:\n" . MeprUtils::object_to_string($txn));
// Initialize a new payment here
$response = (object) $this->paystack_api->send_request("transaction/initialize/", $args);
if ($response->status) {
return MeprUtils::wp_redirect("{$response->data['authorization_url']}");
}
return false;
}
/**
* This method should be used by the class to record a successful subscription transaction from
* the gateway. This method should also be used by a Silent Posts.
*/
public function record_transaction_for_subscription()
{
$mepr_options = MeprOptions::fetch();
if (isset($_REQUEST['data'])) {
$charge = $this->get_request_data();
// Get Transaction from paystack reference or charge id
$obj = MeprTransaction::get_one($charge->metadata['transaction_id']) ?? MeprTransaction::get_one_by_trans_num($charge->reference);
if (!is_object($obj) and !isset($obj->id)) {
MeprUtils::wp_redirect($mepr_options->account_page_url('action=subscriptions'));
}
$txn = new MeprTransaction();
$txn->load_data($obj);
if ($txn->status == MeprTransaction::$pending_str && $charge->status == 'success') {
$txn->status == MeprTransaction::$confirmed_str;
$txn->store();
}
//Reload the txn now that it should have a proper trans_num set
$txn = new MeprTransaction($txn->id);
return $txn;
}
}
/**
* Used to record a successful subscription by the given gateway. It should have
* the ability to record a successful subscription or a failure. It is this method
* that should be used when receiving a Paystack Webhook.
*/
public function record_create_subscription()
{
$mepr_options = MeprOptions::fetch();
if (isset($_REQUEST['data'])) {
$sdata = $this->get_request_data();
error_log("********** MeprPaystackGateway::record_create_subscription sData: \n" . MeprUtils::object_to_string($sdata));
$sub = $this::get_subscr_by_plan_code($sdata->plan['plan_code']);
if (!$sub) {
return false;
}
error_log("********** MeprPaystackGateway::record_create_subscription Subscription: \n" . MeprUtils::object_to_string($sub));
$sub->status = MeprSubscription::$active_str;
$sub->subscr_id = $sdata->subscription_code;
$card = $this->get_card($sdata);
if (!empty($card) && $card['reusable']) {
$sub->cc_last4 = $card['last4'];
$sub->cc_exp_month = $card['exp_month'];
$sub->cc_exp_year = $card['exp_year'];
}
$sub->created_at = gmdate('c');
$sub->store();
// Add the email token, customer and subcription code and as metadata
$sub->update_meta('paystack_email_token', $sdata->email_token);
$sub->update_meta('paystack_customer_code', $sdata->customer['customer_code']);
$sub->update_meta('paystack_subscription_code', $sdata->subscription_code);
// This will only work before maybe_cancel_old_sub is run
$upgrade = $sub->is_upgrade();
$downgrade = $sub->is_downgrade();
$event_txn = $sub->maybe_cancel_old_sub();
$txn = $sub->first_txn();
if ($txn == false || !($txn instanceof MeprTransaction)) {
$txn = new MeprTransaction();
$txn->user_id = $sub->user_id;
$txn->product_id = $sub->product_id;
}
$old_total = $txn->total;
// If no trial or trial amount is zero then we've got to make
// sure the confirmation txn lasts through the trial
// if (!$sub->trial || ($sub->trial && $sub->trial_amount <= 0.00)) {
// $trial_days = ($sub->trial) ? $sub->trial_days : $mepr_options->grace_init_days;
// $txn->status = MeprTransaction::$confirmed_str;
// $txn->txn_type = MeprTransaction::$subscription_confirmation_str;
// $txn->expires_at = MeprUtils::ts_to_mysql_date(time() + MeprUtils::days($trial_days), 'Y-m-d 23:59:59');
// $txn->set_subtotal(0.00); // Just a confirmation txn
// $txn->store();
// }
if (!$sub->trial) {
$txn->status = MeprTransaction::$confirmed_str;
$txn->txn_type = MeprTransaction::$subscription_confirmation_str;
$next_payment_date = $sdata->next_payment_date;
$txn->expires_at = MeprUtils::ts_to_mysql_date(strtotime($next_payment_date), 'Y-m-d 23:59:59');
$txn->store();
}
else if($sub->trial && $sub->trial_amount <= 0.00) {
$trial_days = $sub->trial_days;
$txn->status = MeprTransaction::$confirmed_str;
$txn->txn_type = MeprTransaction::$subscription_confirmation_str;
$txn->expires_at = MeprUtils::ts_to_mysql_date(time() + MeprUtils::days($trial_days), 'Y-m-d 23:59:59');
$txn->store();
}
$txn->set_gross($old_total); // Artificially set the subscription amount
if ($upgrade) {
$this->upgraded_sub($sub, $event_txn);
} else if ($downgrade) {
$this->downgraded_sub($sub, $event_txn);
} else {
$this->new_sub($sub, true);
}
//Reload the txn now that it should have a proper trans_num set
$txn = new MeprTransaction($txn->id);
MeprUtils::send_signup_notices($txn);
return array('subscription' => $sub, 'transaction' => $txn);
}
return false;
}
/**
* Used to record a successful recurring payment by the given gateway. It
* should have the ability to record a successful payment or a failure. It is
* this method that should be used when receiving a Paystack Webhook.
*/
public function record_subscription_payment()
{
if (isset($_REQUEST['data'])) {
$sdata = $this->get_request_data();
error_log("********** MeprPaystackGateway::record_subscription_payment sData: \n" . MeprUtils::object_to_string($sdata));
if (isset($sdata->invoice_code)) {
if ($sdata->paid == true) {
return $this->record_subscription_invoice($sdata);
}
return $this->record_payment_failure();
}
return $this->record_subscription_charge($sdata);
}
return false;
}
protected function record_subscription_invoice($invoice)
{
// Make sure there's a valid subscription for this request and this payment hasn't already been recorded
if (
!($sub = MeprSubscription::get_one_by_subscr_id($invoice->subscription['subscription_code'])) && MeprTransaction::txn_exists($invoice->transaction['reference'])
) {
return false;
}
//If this isn't for us, bail
if ($sub->gateway != $this->id) {
return false;
}
$first_txn = $txn = $sub->first_txn();
if ($first_txn == false || !($first_txn instanceof MeprTransaction)) {
$coupon_id = $sub->coupon_id;
} else {
$coupon_id = $first_txn->coupon_id;
}
$this->email_status(
"record_subscription_invoice:" .
"\nSubscription: " . MeprUtils::object_to_string($sub, true) .
"\nTransaction: " . MeprUtils::object_to_string($txn, true),
$this->settings->debug
);
$txn = new MeprTransaction();
$txn->user_id = $sub->user_id;
$txn->product_id = $sub->product_id;
$txn->status = MeprTransaction::$complete_str;
$txn->coupon_id = $coupon_id;
$txn->trans_num = $invoice->transaction['reference'] ?? MeprTransaction::generate_trans_num();
$txn->gateway = $this->id;
$txn->subscription_id = $sub->id;
if (MeprUtils::is_zero_decimal_currency()) {
$txn->set_gross((float) $invoice->amount);
} else {
$txn->set_gross((float) $invoice->amount / 100);
}
$txn->expires_at = MeprUtils::ts_to_mysql_date(strtotime($invoice->subscription['next_payment_date']), 'Y-m-d 23:59:59');
$txn->store();
$usr = $txn->user();
// Set Auth Token for Current User
$this->set_auth_token($usr, $invoice->authorization);
$sub->status = MeprSubscription::$active_str;
$sub->update_meta('paystack_invoice_code', $invoice->invoice_code);
$sub->update_meta('paystack_email_token', $invoice->subscription['email_token']);
if ($card = $this->get_card($invoice)) {
$sub->cc_exp_month = $card['exp_month'];
$sub->cc_exp_year = $card['exp_year'];
$sub->cc_last4 = $card['last4'];
}
// $sub->subscr_id = $invoice->subscription['subscription_code'];
// $sub->gateway = $this->id;
$sub->store();
// If a limit was set on the recurring cycles we need
// to cancel the subscr if the txn_count >= limit_cycles_num
// This is not possible natively with Paystack so we
// just cancel the subscr when limit_cycles_num is hit
$sub->limit_payment_cycles();
$this->email_status(
"Subscription Invoice\n" .
MeprUtils::object_to_string($txn->rec, true),
$this->settings->debug
);
MeprUtils::send_transaction_receipt_notices($txn);
MeprUtils::send_cc_expiration_notices($txn);
return $txn;
}
protected function record_subscription_charge($charge)
{
error_log("********** MeprPaystackGateway::record_subscription_charge Charge: \n" . MeprUtils::object_to_string($charge));
// Make sure there's a valid subscription for this request and this payment hasn't already been recorded
if (
!($sub = $this::get_subscr_by_plan_code($charge->plan['plan_code'])) && MeprTransaction::txn_exists($charge->reference)
) {
return false;
}
error_log("********** MeprPaystackGateway::record_subscription_charge Subscription: \n" . MeprUtils::object_to_string($sub));
//If this isn't for us, bail
if ($sub->gateway != $this->id) {
return false;
}
$txn = $sub->first_txn();
error_log("********** MeprPaystackGateway::record_subscription_charge Transaction: \n" . MeprUtils::object_to_string($txn));
if ($txn == false || !($txn instanceof MeprTransaction)) {
$coupon_id = $sub->coupon_id;
} else {
$coupon_id = $txn->coupon_id;
}
$this->email_status(
"record_subscription_charge:" .
"\nSubscription: " . MeprUtils::object_to_string($sub, true) .
"\nTransaction: " . MeprUtils::object_to_string($txn, true),
$this->settings->debug
);
$txn = new MeprTransaction();
$txn->user_id = $sub->user_id;
$txn->product_id = $sub->product_id;
$txn->status = MeprTransaction::$complete_str;
$txn->coupon_id = $coupon_id;
$txn->trans_num = $charge->reference;
$txn->gateway = $this->id;
$txn->subscription_id = $sub->id;
if (MeprUtils::is_zero_decimal_currency()) {
$txn->set_gross((float) $charge->amount);
} else {
$txn->set_gross((float) $charge->amount / 100);
}
// $txn->expires_at = MeprUtils::ts_to_mysql_date($sdata['subscription']['current_period_end'], 'Y-m-d 23:59:59');
$txn->store();
$usr = $txn->user();
// Set Auth Token for Current User
$this->set_auth_token($usr, $charge->authorization);
// Let's sleep the process, so we can wait for the subscription create webhook to be handled fully.
// sleep(10);
// $sub->subscr_id = $sub->get_meta('paystack_subscription_code', true);
$sub->status = MeprSubscription::$active_str;
if ($card = $this->get_card($charge)) {
$sub->cc_exp_month = $card['exp_month'];
$sub->cc_exp_year = $card['exp_year'];
$sub->cc_last4 = $card['last4'];
}
$sub->store();
// If a limit was set on the recurring cycles we need
// to cancel the subscr if the txn_count >= limit_cycles_num
// This is not possible natively with Paystack so we
// just cancel the subscr when limit_cycles_num is hit
$sub->limit_payment_cycles();
$this->email_status(
"Subscription Transaction\n" .
MeprUtils::object_to_string($txn->rec, true),
$this->settings->debug
);
//Reload the txn
$txn = new MeprTransaction($txn->id);
MeprUtils::send_transaction_receipt_notices($txn);
MeprUtils::send_cc_expiration_notices($txn);
return $txn;
}
/**
* @param $plan_code
*
* @return bool|MeprSubscription
*/
protected static function get_subscr_by_plan_code($plan_code)
{
global $wpdb;
$mepr_db = new MeprDb();
$sql = "
SELECT sub.id
FROM {$mepr_db->subscriptions} AS sub
WHERE sub.token=%s
ORDER BY sub.id DESC
LIMIT 1
";
$sql = $wpdb->prepare($sql, $plan_code);
//error_log("********** MeprPaystackGateway::get_subscr_by_plan_code SQL: \n" . MeprUtils::object_to_string($sql));
$sub_id = $wpdb->get_var($sql);
//error_log("********** MeprPaystackGateway::get_subscr_by_plan_code sub_id: {$sub_id}\n");
if ($sub_id) {
return new MeprSubscription($sub_id);
} else {
return false;
}
}
/**
* Used to cancel a subscription by the given gateway. This method should be used
* by the class to record a successful cancellation from the gateway. This method
* should also be used by any IPN requests or Silent Posts.
*
* We bill the outstanding amount of the previous subscription,
* cancel the previous subscription and create a new subscription
*/
public function process_update_subscription($sub_id)
{
}
/** This method should be used by the class to record a successful cancellation
* from the gateway. This method should also be used by any IPN requests or
* Silent Posts.
*/
public function record_update_subscription()
{
// No need for this one with paystack
}
/** Used to suspend a subscription by the given gateway.
*/
public function process_suspend_subscription($sub_id)
{
$sub = new MeprSubscription($sub_id);
$args = MeprHooks::apply_filters('mepr_paystack_suspend_subscription_args', array(
'code' => $sub->subscr_id,
'token' => $sub->get_meta('paystack_email_token'),
), $sub);
// Yeah ... we're cancelling here bro ... with paystack we should be able to restart again
$res = $this->paystack_api->send_request("subscription/disable", $args);
$_REQUEST['recurring_payment_id'] = $sub->subscr_id;
return $this->record_suspend_subscription();
}
/** This method should be used by the class to record a successful suspension
* from the gateway.
*/
public function record_suspend_subscription()
{
$subscr_id = sanitize_text_field($_REQUEST['recurring_payment_id']);
$sub = MeprSubscription::get_one_by_subscr_id($subscr_id);
if (!$sub) {
return false;
}
// Seriously ... if sub was already suspended what are we doing here?
if ($sub->status == MeprSubscription::$suspended_str) {
return $sub;
}
$sub->status = MeprSubscription::$suspended_str;
$sub->store();
MeprUtils::send_suspended_sub_notices($sub);
return $sub;
}
/**
* Used to suspend a subscription by the given gateway.
*/
public function process_resume_subscription($sub_id)
{
$mepr_options = MeprOptions::fetch();
MeprHooks::do_action('mepr-pre-paystack-resume-subscription', $sub_id); //Allow users to change the subscription programatically before resuming it
$sub = new MeprSubscription($sub_id);
$orig_trial = $sub->trial;
$orig_trial_days = $sub->trial_days;
$orig_trial_amount = $sub->trial_amount;
if ($sub->is_expired() and !$sub->is_lifetime()) {
$expiring_txn = $sub->expiring_txn();
// if it's already expired with a real transaction
// then we want to resume immediately
if (
$expiring_txn != false && $expiring_txn instanceof MeprTransaction &&
$expiring_txn->status != MeprTransaction::$confirmed_str
) {
$sub->trial = false;
$sub->trial_days = 0;
$sub->trial_amount = 0.00;
$sub->store();
}
} else {
$sub->trial = true;
$sub->trial_days = MeprUtils::tsdays(strtotime($sub->expires_at) - time());
$sub->trial_amount = 0.00;
$sub->store();
}
// Create new plan with optional trial in place ...
// $plan = $this->paystack_plan($sub, true);
$sub->trial = $orig_trial;
$sub->trial_days = $orig_trial_days;
$sub->trial_amount = $orig_trial_amount;
$sub->store();
$args = MeprHooks::apply_filters('mepr_paystack_resume_subscription_args', array(
'code' => $sub->subscr_id,
'token' => $sub->get_meta('paystack_email_token'),
), $sub);
$this->email_status(
"process_resume_subscription: \n" .
MeprUtils::object_to_string($sub, true) . "\n",
$this->settings->debug
);
$this->paystack_api->send_request("subscription/enable", $args);
$_REQUEST['recurring_payment_id'] = $sub->subscr_id;
return $this->record_resume_subscription();
}
/** This method should be used by the class to record a successful resuming of
* as subscription from the gateway.
*/
public function record_resume_subscription()
{
$subscr_id = sanitize_text_field($_REQUEST['recurring_payment_id']);
$sub = MeprSubscription::get_one_by_subscr_id($subscr_id);
if (!$sub) {
return false;
}
// Seriously ... if sub was already active what are we doing here?
if ($sub->status == MeprSubscription::$active_str) {
return $sub;
}
$sub->status = MeprSubscription::$active_str;
$sub->store();
//Check if prior txn is expired yet or not, if so create a temporary txn so the user can access the content immediately
$prior_txn = $sub->latest_txn();
if ($prior_txn == false || !($prior_txn instanceof MeprTransaction) || strtotime($prior_txn->expires_at) < time()) {
$txn = new MeprTransaction();
$txn->subscription_id = $sub->id;
$txn->trans_num = $sub->subscr_id . '-' . uniqid();
$txn->status = MeprTransaction::$confirmed_str;
$txn->txn_type = MeprTransaction::$subscription_confirmation_str;
$txn->expires_at = MeprUtils::ts_to_mysql_date(time() + MeprUtils::days(1), 'Y-m-d H:i:s');
$txn->set_subtotal(0.00); // Just a confirmation txn
$txn->store();
}
MeprUtils::send_resumed_sub_notices($sub);
return $sub;
}
/** Used to cancel a subscription by the given gateway. This method should be used
* by the class to record a successful cancellation from the gateway. This method
* should also be used by any IPN requests or Silent Posts.
*/
public function process_cancel_subscription($sub_id)
{
$sub = new MeprSubscription($sub_id);
//Getting the value of the paystack_email_token from the array and storing the value in a variable
$array = $sub->get_meta('paystack_email_token');
$token = $array[0];
if (!isset($sub->id) || (int) $sub->id <= 0)
throw new MeprGatewayException(__('This subscription is invalid.', 'memberpress'));
$args = MeprHooks::apply_filters('mepr_paystack_cancel_subscription_args', array(
'code' => $sub->subscr_id,
'token' => $token,
), $sub);
// Yeah ... we're cancelling here bro ... but this time we don't want to restart again
$res = $this->paystack_api->send_request("subscription/disable", $args);
$_REQUEST['recurring_payment_id'] = $sub->subscr_id;
return $this->record_cancel_subscription();
}
/** This method should be used by the class to record a successful cancellation
* from the gateway. This method should also be used by any IPN requests or
* Silent Posts.
*/
public function record_cancel_subscription()
{
$subscr_id = $_REQUEST['recurring_payment_id'] ?? $_REQUEST['data']->subscription_code;
$sub = MeprSubscription::get_one_by_subscr_id($subscr_id);
if (!$sub) {
return false;
}
// Seriously ... if sub was already cancelled what are we doing here?
if ($sub->status == MeprSubscription::$cancelled_str) {
return $sub;
}
$sub->status = MeprSubscription::$cancelled_str;
$sub->store();
$sub->limit_reached_actions();
MeprUtils::send_cancelled_sub_notices($sub);
return $sub;
}
public function process_trial_payment($txn)
{
$mepr_options = MeprOptions::fetch();
$sub = $txn->subscription();
// Prepare the $txn for the process_payment method
$txn->set_subtotal($sub->trial_amount);
$txn->status = MeprTransaction::$pending_str;
// Attempt processing the payment here
$this->process_payment($txn, true);
}
public function record_trial_payment($txn)
{
$sub = $txn->subscription();
// Update the txn member vars and store
$txn->txn_type = MeprTransaction::$payment_str;
$txn->status = MeprTransaction::$complete_str;
$txn->expires_at = MeprUtils::ts_to_mysql_date(time() + MeprUtils::days($sub->trial_days), 'Y-m-d 23:59:59');
$txn->store();
return true;
}
/**
* Used to record a declined payment.
*/
public function record_payment_failure()
{
if (isset($_REQUEST['data'])) {
$charge = $this->get_request_data();
$txn_ref = sanitize_text_field($_REQUEST['reference']);
$txn_res = MeprTransaction::get_one_by_trans_num($txn_ref);
if (is_object($txn_res) and isset($txn_res->id)) {
$txn = new MeprTransaction($txn_res->id);
$txn->trans_num = $txn_ref;
$txn->status = MeprTransaction::$failed_str;
$txn->store();
} elseif (
isset($charge) &&
$sub = MeprSubscription::get_one_by_subscr_id($charge->subscription['subscription_code'])
) {
$first_txn = $sub->first_txn();
if ($first_txn == false || !($first_txn instanceof MeprTransaction)) {
$coupon_id = $sub->coupon_id;
} else {
$coupon_id = $first_txn->coupon_id;
}
$txn = new MeprTransaction();
$txn->user_id = $sub->user_id;
$txn->product_id = $sub->product_id;
$txn->coupon_id = $coupon_id;
$txn->txn_type = MeprTransaction::$payment_str;
$txn->status = MeprTransaction::$failed_str;
$txn->subscription_id = $sub->id;
$txn->trans_num = $charge->id;
$txn->gateway = $this->id;
if (MeprUtils::is_zero_decimal_currency()) {
$txn->set_gross((float) $charge->amount);
} else {
$txn->set_gross((float) $charge->amount / 100);
}
$txn->store();
//If first payment fails, Paystack will not set up the subscription, so we need to mark it as cancelled in MP
if ($sub->txn_count == 0) {
$sub->status = MeprSubscription::$cancelled_str;
} else {
$sub->status = MeprSubscription::$active_str;
}
$sub->gateway = $this->id;
$sub->expire_txns(); //Expire associated transactions for the old subscription
$sub->store();
} else {
return false; // Nothing we can do here ... so we outta here
}
MeprUtils::send_failed_txn_notices($txn);
return $txn;
}
return false;
}
/**
* This method should be used by the class to push a refund request to to the gateway.
*/
public function process_refund(MeprTransaction $txn)
{
$mepr_options = MeprOptions::fetch();
$_REQUEST['trans_num'] = $txn->trans_num;
// Handle zero decimal currencies in Paystack
$amount = (MeprUtils::is_zero_decimal_currency()) ? MeprUtils::format_float(($txn->amount), 0) : MeprUtils::format_float(($txn->amount * 100), 0);
$args = MeprHooks::apply_filters('mepr_paystack_refund_args', array(
'transaction' => $txn->trans_num,
'amount' => $amount,
'currency' => $mepr_options->currency_code,
'merchant_note' => 'Refund Memberpress Transaction'
), $txn);
$refund = (object) $this->paystack_api->send_request("refund", $args);